babylon.no-module.max.js 5.2 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504
  1. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  2. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  3. var BABYLON;
  4. (function (BABYLON) {
  5. /**
  6. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  7. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  8. */
  9. var EffectFallbacks = /** @class */ (function () {
  10. function EffectFallbacks() {
  11. this._defines = {};
  12. this._currentRank = 32;
  13. this._maxRank = -1;
  14. }
  15. /**
  16. * Removes the fallback from the bound mesh.
  17. */
  18. EffectFallbacks.prototype.unBindMesh = function () {
  19. this._mesh = null;
  20. };
  21. /**
  22. * Adds a fallback on the specified property.
  23. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  24. * @param define The name of the define in the shader
  25. */
  26. EffectFallbacks.prototype.addFallback = function (rank, define) {
  27. if (!this._defines[rank]) {
  28. if (rank < this._currentRank) {
  29. this._currentRank = rank;
  30. }
  31. if (rank > this._maxRank) {
  32. this._maxRank = rank;
  33. }
  34. this._defines[rank] = new Array();
  35. }
  36. this._defines[rank].push(define);
  37. };
  38. /**
  39. * Sets the mesh to use CPU skinning when needing to fallback.
  40. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  41. * @param mesh The mesh to use the fallbacks.
  42. */
  43. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  44. this._mesh = mesh;
  45. if (rank < this._currentRank) {
  46. this._currentRank = rank;
  47. }
  48. if (rank > this._maxRank) {
  49. this._maxRank = rank;
  50. }
  51. };
  52. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  53. /**
  54. * Checks to see if more fallbacks are still availible.
  55. */
  56. get: function () {
  57. return this._currentRank <= this._maxRank;
  58. },
  59. enumerable: true,
  60. configurable: true
  61. });
  62. /**
  63. * Removes the defines that shoould be removed when falling back.
  64. * @param currentDefines defines the current define statements for the shader.
  65. * @param effect defines the current effect we try to compile
  66. * @returns The resulting defines with defines of the current rank removed.
  67. */
  68. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  69. // First we try to switch to CPU skinning
  70. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  71. this._mesh.computeBonesUsingShaders = false;
  72. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  73. effect._bonesComputationForcedToCPU = true;
  74. var scene = this._mesh.getScene();
  75. for (var index = 0; index < scene.meshes.length; index++) {
  76. var otherMesh = scene.meshes[index];
  77. if (!otherMesh.material) {
  78. continue;
  79. }
  80. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  81. continue;
  82. }
  83. if (otherMesh.material.getEffect() === effect) {
  84. otherMesh.computeBonesUsingShaders = false;
  85. }
  86. else if (otherMesh.subMeshes) {
  87. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  88. var subMesh = _a[_i];
  89. var subMeshEffect = subMesh.effect;
  90. if (subMeshEffect === effect) {
  91. otherMesh.computeBonesUsingShaders = false;
  92. break;
  93. }
  94. }
  95. }
  96. }
  97. }
  98. else {
  99. var currentFallbacks = this._defines[this._currentRank];
  100. if (currentFallbacks) {
  101. for (var index = 0; index < currentFallbacks.length; index++) {
  102. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  103. }
  104. }
  105. this._currentRank++;
  106. }
  107. return currentDefines;
  108. };
  109. return EffectFallbacks;
  110. }());
  111. BABYLON.EffectFallbacks = EffectFallbacks;
  112. /**
  113. * Options to be used when creating an effect.
  114. */
  115. var EffectCreationOptions = /** @class */ (function () {
  116. function EffectCreationOptions() {
  117. }
  118. return EffectCreationOptions;
  119. }());
  120. BABYLON.EffectCreationOptions = EffectCreationOptions;
  121. /**
  122. * Effect containing vertex and fragment shader that can be executed on an object.
  123. */
  124. var Effect = /** @class */ (function () {
  125. /**
  126. * Instantiates an effect.
  127. * An effect can be used to create/manage/execute vertex and fragment shaders.
  128. * @param baseName Name of the effect.
  129. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  130. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  131. * @param samplers List of sampler variables that will be passed to the shader.
  132. * @param engine Engine to be used to render the effect
  133. * @param defines Define statements to be added to the shader.
  134. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  135. * @param onCompiled Callback that will be called when the shader is compiled.
  136. * @param onError Callback that will be called if an error occurs during shader compilation.
  137. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  138. */
  139. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  140. if (samplers === void 0) { samplers = null; }
  141. if (defines === void 0) { defines = null; }
  142. if (fallbacks === void 0) { fallbacks = null; }
  143. if (onCompiled === void 0) { onCompiled = null; }
  144. if (onError === void 0) { onError = null; }
  145. var _this = this;
  146. /**
  147. * Unique ID of the effect.
  148. */
  149. this.uniqueId = 0;
  150. /**
  151. * Observable that will be called when the shader is compiled.
  152. */
  153. this.onCompileObservable = new BABYLON.Observable();
  154. /**
  155. * Observable that will be called if an error occurs during shader compilation.
  156. */
  157. this.onErrorObservable = new BABYLON.Observable();
  158. /** @hidden */
  159. this._bonesComputationForcedToCPU = false;
  160. this._uniformBuffersNames = {};
  161. this._isReady = false;
  162. this._compilationError = "";
  163. this.name = baseName;
  164. if (attributesNamesOrOptions.attributes) {
  165. var options = attributesNamesOrOptions;
  166. this._engine = uniformsNamesOrEngine;
  167. this._attributesNames = options.attributes;
  168. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  169. this._samplers = options.samplers.slice();
  170. this.defines = options.defines;
  171. this.onError = options.onError;
  172. this.onCompiled = options.onCompiled;
  173. this._fallbacks = options.fallbacks;
  174. this._indexParameters = options.indexParameters;
  175. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  176. if (options.uniformBuffersNames) {
  177. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  178. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  179. }
  180. }
  181. }
  182. else {
  183. this._engine = engine;
  184. this.defines = defines;
  185. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  186. this._samplers = samplers ? samplers.slice() : [];
  187. this._attributesNames = attributesNamesOrOptions;
  188. this.onError = onError;
  189. this.onCompiled = onCompiled;
  190. this._indexParameters = indexParameters;
  191. this._fallbacks = fallbacks;
  192. }
  193. this.uniqueId = Effect._uniqueIdSeed++;
  194. var vertexSource;
  195. var fragmentSource;
  196. if (baseName.vertexElement) {
  197. vertexSource = document.getElementById(baseName.vertexElement);
  198. if (!vertexSource) {
  199. vertexSource = baseName.vertexElement;
  200. }
  201. }
  202. else {
  203. vertexSource = baseName.vertex || baseName;
  204. }
  205. if (baseName.fragmentElement) {
  206. fragmentSource = document.getElementById(baseName.fragmentElement);
  207. if (!fragmentSource) {
  208. fragmentSource = baseName.fragmentElement;
  209. }
  210. }
  211. else {
  212. fragmentSource = baseName.fragment || baseName;
  213. }
  214. this._loadVertexShader(vertexSource, function (vertexCode) {
  215. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  216. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  217. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  218. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  219. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  220. if (baseName) {
  221. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  222. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  223. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  224. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  225. }
  226. else {
  227. _this._vertexSourceCode = migratedVertexCode;
  228. _this._fragmentSourceCode = migratedFragmentCode;
  229. }
  230. _this._prepareEffect();
  231. });
  232. });
  233. });
  234. });
  235. });
  236. });
  237. }
  238. Object.defineProperty(Effect.prototype, "onBindObservable", {
  239. /**
  240. * Observable that will be called when effect is bound.
  241. */
  242. get: function () {
  243. if (!this._onBindObservable) {
  244. this._onBindObservable = new BABYLON.Observable();
  245. }
  246. return this._onBindObservable;
  247. },
  248. enumerable: true,
  249. configurable: true
  250. });
  251. Object.defineProperty(Effect.prototype, "key", {
  252. /**
  253. * Unique key for this effect
  254. */
  255. get: function () {
  256. return this._key;
  257. },
  258. enumerable: true,
  259. configurable: true
  260. });
  261. /**
  262. * If the effect has been compiled and prepared.
  263. * @returns if the effect is compiled and prepared.
  264. */
  265. Effect.prototype.isReady = function () {
  266. return this._isReady;
  267. };
  268. /**
  269. * The engine the effect was initialized with.
  270. * @returns the engine.
  271. */
  272. Effect.prototype.getEngine = function () {
  273. return this._engine;
  274. };
  275. /**
  276. * The compiled webGL program for the effect
  277. * @returns the webGL program.
  278. */
  279. Effect.prototype.getProgram = function () {
  280. return this._program;
  281. };
  282. /**
  283. * The set of names of attribute variables for the shader.
  284. * @returns An array of attribute names.
  285. */
  286. Effect.prototype.getAttributesNames = function () {
  287. return this._attributesNames;
  288. };
  289. /**
  290. * Returns the attribute at the given index.
  291. * @param index The index of the attribute.
  292. * @returns The location of the attribute.
  293. */
  294. Effect.prototype.getAttributeLocation = function (index) {
  295. return this._attributes[index];
  296. };
  297. /**
  298. * Returns the attribute based on the name of the variable.
  299. * @param name of the attribute to look up.
  300. * @returns the attribute location.
  301. */
  302. Effect.prototype.getAttributeLocationByName = function (name) {
  303. var index = this._attributesNames.indexOf(name);
  304. return this._attributes[index];
  305. };
  306. /**
  307. * The number of attributes.
  308. * @returns the numnber of attributes.
  309. */
  310. Effect.prototype.getAttributesCount = function () {
  311. return this._attributes.length;
  312. };
  313. /**
  314. * Gets the index of a uniform variable.
  315. * @param uniformName of the uniform to look up.
  316. * @returns the index.
  317. */
  318. Effect.prototype.getUniformIndex = function (uniformName) {
  319. return this._uniformsNames.indexOf(uniformName);
  320. };
  321. /**
  322. * Returns the attribute based on the name of the variable.
  323. * @param uniformName of the uniform to look up.
  324. * @returns the location of the uniform.
  325. */
  326. Effect.prototype.getUniform = function (uniformName) {
  327. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  328. };
  329. /**
  330. * Returns an array of sampler variable names
  331. * @returns The array of sampler variable neames.
  332. */
  333. Effect.prototype.getSamplers = function () {
  334. return this._samplers;
  335. };
  336. /**
  337. * The error from the last compilation.
  338. * @returns the error string.
  339. */
  340. Effect.prototype.getCompilationError = function () {
  341. return this._compilationError;
  342. };
  343. /**
  344. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  345. * @param func The callback to be used.
  346. */
  347. Effect.prototype.executeWhenCompiled = function (func) {
  348. if (this.isReady()) {
  349. func(this);
  350. return;
  351. }
  352. this.onCompileObservable.add(function (effect) {
  353. func(effect);
  354. });
  355. };
  356. /** @hidden */
  357. Effect.prototype._loadVertexShader = function (vertex, callback) {
  358. if (BABYLON.Tools.IsWindowObjectExist()) {
  359. // DOM element ?
  360. if (vertex instanceof HTMLElement) {
  361. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  362. callback(vertexCode);
  363. return;
  364. }
  365. }
  366. // Base64 encoded ?
  367. if (vertex.substr(0, 7) === "base64:") {
  368. var vertexBinary = window.atob(vertex.substr(7));
  369. callback(vertexBinary);
  370. return;
  371. }
  372. // Is in local store ?
  373. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  374. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  375. return;
  376. }
  377. var vertexShaderUrl;
  378. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  379. vertexShaderUrl = vertex;
  380. }
  381. else {
  382. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  383. }
  384. // Vertex shader
  385. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  386. };
  387. /** @hidden */
  388. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  389. if (BABYLON.Tools.IsWindowObjectExist()) {
  390. // DOM element ?
  391. if (fragment instanceof HTMLElement) {
  392. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  393. callback(fragmentCode);
  394. return;
  395. }
  396. }
  397. // Base64 encoded ?
  398. if (fragment.substr(0, 7) === "base64:") {
  399. var fragmentBinary = window.atob(fragment.substr(7));
  400. callback(fragmentBinary);
  401. return;
  402. }
  403. // Is in local store ?
  404. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  405. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  406. return;
  407. }
  408. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  409. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  410. return;
  411. }
  412. var fragmentShaderUrl;
  413. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  414. fragmentShaderUrl = fragment;
  415. }
  416. else {
  417. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  418. }
  419. // Fragment shader
  420. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  421. };
  422. /** @hidden */
  423. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  424. // Rebuild shaders source code
  425. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  426. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  427. vertexCode = prefix + vertexCode;
  428. fragmentCode = prefix + fragmentCode;
  429. // Number lines of shaders source code
  430. var i = 2;
  431. var regex = /\n/gm;
  432. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  433. i = 2;
  434. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  435. // Dump shaders name and formatted source code
  436. if (this.name.vertexElement) {
  437. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  438. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  439. }
  440. else if (this.name.vertex) {
  441. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  442. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  443. }
  444. else {
  445. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  446. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  447. }
  448. };
  449. ;
  450. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  451. var preparedSourceCode = this._processPrecision(sourceCode);
  452. if (this._engine.webGLVersion == 1) {
  453. callback(preparedSourceCode);
  454. return;
  455. }
  456. // Already converted
  457. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  458. callback(preparedSourceCode.replace("#version 300 es", ""));
  459. return;
  460. }
  461. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  462. // Remove extensions
  463. // #extension GL_OES_standard_derivatives : enable
  464. // #extension GL_EXT_shader_texture_lod : enable
  465. // #extension GL_EXT_frag_depth : enable
  466. // #extension GL_EXT_draw_buffers : require
  467. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  468. var result = preparedSourceCode.replace(regex, "");
  469. // Migrate to GLSL v300
  470. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  471. result = result.replace(/attribute[ \t]/g, "in ");
  472. result = result.replace(/[ \t]attribute/g, " in");
  473. if (isFragment) {
  474. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  475. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  476. result = result.replace(/texture2D\s*\(/g, "texture(");
  477. result = result.replace(/textureCube\s*\(/g, "texture(");
  478. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  479. result = result.replace(/gl_FragColor/g, "glFragColor");
  480. result = result.replace(/gl_FragData/g, "glFragData");
  481. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  482. }
  483. callback(result);
  484. };
  485. Effect.prototype._processIncludes = function (sourceCode, callback) {
  486. var _this = this;
  487. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  488. var match = regex.exec(sourceCode);
  489. var returnValue = new String(sourceCode);
  490. while (match != null) {
  491. var includeFile = match[1];
  492. // Uniform declaration
  493. if (includeFile.indexOf("__decl__") !== -1) {
  494. includeFile = includeFile.replace(/__decl__/, "");
  495. if (this._engine.supportsUniformBuffers) {
  496. includeFile = includeFile.replace(/Vertex/, "Ubo");
  497. includeFile = includeFile.replace(/Fragment/, "Ubo");
  498. }
  499. includeFile = includeFile + "Declaration";
  500. }
  501. if (Effect.IncludesShadersStore[includeFile]) {
  502. // Substitution
  503. var includeContent = Effect.IncludesShadersStore[includeFile];
  504. if (match[2]) {
  505. var splits = match[3].split(",");
  506. for (var index = 0; index < splits.length; index += 2) {
  507. var source = new RegExp(splits[index], "g");
  508. var dest = splits[index + 1];
  509. includeContent = includeContent.replace(source, dest);
  510. }
  511. }
  512. if (match[4]) {
  513. var indexString = match[5];
  514. if (indexString.indexOf("..") !== -1) {
  515. var indexSplits = indexString.split("..");
  516. var minIndex = parseInt(indexSplits[0]);
  517. var maxIndex = parseInt(indexSplits[1]);
  518. var sourceIncludeContent = includeContent.slice(0);
  519. includeContent = "";
  520. if (isNaN(maxIndex)) {
  521. maxIndex = this._indexParameters[indexSplits[1]];
  522. }
  523. for (var i = minIndex; i < maxIndex; i++) {
  524. if (!this._engine.supportsUniformBuffers) {
  525. // Ubo replacement
  526. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  527. return p1 + "{X}";
  528. });
  529. }
  530. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  531. }
  532. }
  533. else {
  534. if (!this._engine.supportsUniformBuffers) {
  535. // Ubo replacement
  536. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  537. return p1 + "{X}";
  538. });
  539. }
  540. includeContent = includeContent.replace(/\{X\}/g, indexString);
  541. }
  542. }
  543. // Replace
  544. returnValue = returnValue.replace(match[0], includeContent);
  545. }
  546. else {
  547. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  548. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  549. Effect.IncludesShadersStore[includeFile] = fileContent;
  550. _this._processIncludes(returnValue, callback);
  551. });
  552. return;
  553. }
  554. match = regex.exec(sourceCode);
  555. }
  556. callback(returnValue);
  557. };
  558. Effect.prototype._processPrecision = function (source) {
  559. if (source.indexOf("precision highp float") === -1) {
  560. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  561. source = "precision mediump float;\n" + source;
  562. }
  563. else {
  564. source = "precision highp float;\n" + source;
  565. }
  566. }
  567. else {
  568. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  569. source = source.replace("precision highp float", "precision mediump float");
  570. }
  571. }
  572. return source;
  573. };
  574. /**
  575. * Recompiles the webGL program
  576. * @param vertexSourceCode The source code for the vertex shader.
  577. * @param fragmentSourceCode The source code for the fragment shader.
  578. * @param onCompiled Callback called when completed.
  579. * @param onError Callback called on error.
  580. * @hidden
  581. */
  582. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  583. var _this = this;
  584. this._isReady = false;
  585. this._vertexSourceCodeOverride = vertexSourceCode;
  586. this._fragmentSourceCodeOverride = fragmentSourceCode;
  587. this.onError = function (effect, error) {
  588. if (onError) {
  589. onError(error);
  590. }
  591. };
  592. this.onCompiled = function () {
  593. var scenes = _this.getEngine().scenes;
  594. for (var i = 0; i < scenes.length; i++) {
  595. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  596. }
  597. if (onCompiled) {
  598. onCompiled(_this._program);
  599. }
  600. };
  601. this._fallbacks = null;
  602. this._prepareEffect();
  603. };
  604. /**
  605. * Gets the uniform locations of the the specified variable names
  606. * @param names THe names of the variables to lookup.
  607. * @returns Array of locations in the same order as variable names.
  608. */
  609. Effect.prototype.getSpecificUniformLocations = function (names) {
  610. var engine = this._engine;
  611. return engine.getUniforms(this._program, names);
  612. };
  613. /**
  614. * Prepares the effect
  615. * @hidden
  616. */
  617. Effect.prototype._prepareEffect = function () {
  618. var attributesNames = this._attributesNames;
  619. var defines = this.defines;
  620. var fallbacks = this._fallbacks;
  621. this._valueCache = {};
  622. var previousProgram = this._program;
  623. try {
  624. var engine = this._engine;
  625. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  626. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  627. }
  628. else {
  629. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  630. }
  631. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  632. if (engine.supportsUniformBuffers) {
  633. for (var name in this._uniformBuffersNames) {
  634. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  635. }
  636. }
  637. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  638. this._attributes = engine.getAttributes(this._program, attributesNames);
  639. var index;
  640. for (index = 0; index < this._samplers.length; index++) {
  641. var sampler = this.getUniform(this._samplers[index]);
  642. if (sampler == null) {
  643. this._samplers.splice(index, 1);
  644. index--;
  645. }
  646. }
  647. engine.bindSamplers(this);
  648. this._compilationError = "";
  649. this._isReady = true;
  650. if (this.onCompiled) {
  651. this.onCompiled(this);
  652. }
  653. this.onCompileObservable.notifyObservers(this);
  654. this.onCompileObservable.clear();
  655. // Unbind mesh reference in fallbacks
  656. if (this._fallbacks) {
  657. this._fallbacks.unBindMesh();
  658. }
  659. if (previousProgram) {
  660. this.getEngine()._deleteProgram(previousProgram);
  661. }
  662. }
  663. catch (e) {
  664. this._compilationError = e.message;
  665. // Let's go through fallbacks then
  666. BABYLON.Tools.Error("Unable to compile effect:");
  667. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  668. return " " + uniform;
  669. }));
  670. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  671. return " " + attribute;
  672. }));
  673. BABYLON.Tools.Error("Error: " + this._compilationError);
  674. if (previousProgram) {
  675. this._program = previousProgram;
  676. this._isReady = true;
  677. if (this.onError) {
  678. this.onError(this, this._compilationError);
  679. }
  680. this.onErrorObservable.notifyObservers(this);
  681. }
  682. if (fallbacks && fallbacks.isMoreFallbacks) {
  683. BABYLON.Tools.Error("Trying next fallback.");
  684. this.defines = fallbacks.reduce(this.defines, this);
  685. this._prepareEffect();
  686. }
  687. else { // Sorry we did everything we can
  688. if (this.onError) {
  689. this.onError(this, this._compilationError);
  690. }
  691. this.onErrorObservable.notifyObservers(this);
  692. this.onErrorObservable.clear();
  693. // Unbind mesh reference in fallbacks
  694. if (this._fallbacks) {
  695. this._fallbacks.unBindMesh();
  696. }
  697. }
  698. }
  699. };
  700. Object.defineProperty(Effect.prototype, "isSupported", {
  701. /**
  702. * Checks if the effect is supported. (Must be called after compilation)
  703. */
  704. get: function () {
  705. return this._compilationError === "";
  706. },
  707. enumerable: true,
  708. configurable: true
  709. });
  710. /**
  711. * Binds a texture to the engine to be used as output of the shader.
  712. * @param channel Name of the output variable.
  713. * @param texture Texture to bind.
  714. * @hidden
  715. */
  716. Effect.prototype._bindTexture = function (channel, texture) {
  717. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  718. };
  719. /**
  720. * Sets a texture on the engine to be used in the shader.
  721. * @param channel Name of the sampler variable.
  722. * @param texture Texture to set.
  723. */
  724. Effect.prototype.setTexture = function (channel, texture) {
  725. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  726. };
  727. /**
  728. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  729. * @param channel Name of the sampler variable.
  730. * @param texture Texture to set.
  731. */
  732. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  733. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  734. };
  735. /**
  736. * Sets an array of textures on the engine to be used in the shader.
  737. * @param channel Name of the variable.
  738. * @param textures Textures to set.
  739. */
  740. Effect.prototype.setTextureArray = function (channel, textures) {
  741. if (this._samplers.indexOf(channel + "Ex") === -1) {
  742. var initialPos = this._samplers.indexOf(channel);
  743. for (var index = 1; index < textures.length; index++) {
  744. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  745. }
  746. }
  747. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  748. };
  749. /**
  750. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  751. * @param channel Name of the sampler variable.
  752. * @param postProcess Post process to get the input texture from.
  753. */
  754. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  755. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  756. };
  757. /**
  758. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  759. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  760. * @param channel Name of the sampler variable.
  761. * @param postProcess Post process to get the output texture from.
  762. */
  763. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  764. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  765. };
  766. /** @hidden */
  767. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  768. var cache = this._valueCache[uniformName];
  769. var flag = matrix.updateFlag;
  770. if (cache !== undefined && cache === flag) {
  771. return false;
  772. }
  773. this._valueCache[uniformName] = flag;
  774. return true;
  775. };
  776. /** @hidden */
  777. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  778. var cache = this._valueCache[uniformName];
  779. if (!cache) {
  780. cache = [x, y];
  781. this._valueCache[uniformName] = cache;
  782. return true;
  783. }
  784. var changed = false;
  785. if (cache[0] !== x) {
  786. cache[0] = x;
  787. changed = true;
  788. }
  789. if (cache[1] !== y) {
  790. cache[1] = y;
  791. changed = true;
  792. }
  793. return changed;
  794. };
  795. /** @hidden */
  796. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  797. var cache = this._valueCache[uniformName];
  798. if (!cache) {
  799. cache = [x, y, z];
  800. this._valueCache[uniformName] = cache;
  801. return true;
  802. }
  803. var changed = false;
  804. if (cache[0] !== x) {
  805. cache[0] = x;
  806. changed = true;
  807. }
  808. if (cache[1] !== y) {
  809. cache[1] = y;
  810. changed = true;
  811. }
  812. if (cache[2] !== z) {
  813. cache[2] = z;
  814. changed = true;
  815. }
  816. return changed;
  817. };
  818. /** @hidden */
  819. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  820. var cache = this._valueCache[uniformName];
  821. if (!cache) {
  822. cache = [x, y, z, w];
  823. this._valueCache[uniformName] = cache;
  824. return true;
  825. }
  826. var changed = false;
  827. if (cache[0] !== x) {
  828. cache[0] = x;
  829. changed = true;
  830. }
  831. if (cache[1] !== y) {
  832. cache[1] = y;
  833. changed = true;
  834. }
  835. if (cache[2] !== z) {
  836. cache[2] = z;
  837. changed = true;
  838. }
  839. if (cache[3] !== w) {
  840. cache[3] = w;
  841. changed = true;
  842. }
  843. return changed;
  844. };
  845. /**
  846. * Binds a buffer to a uniform.
  847. * @param buffer Buffer to bind.
  848. * @param name Name of the uniform variable to bind to.
  849. */
  850. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  851. var bufferName = this._uniformBuffersNames[name];
  852. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  853. return;
  854. }
  855. Effect._baseCache[bufferName] = buffer;
  856. this._engine.bindUniformBufferBase(buffer, bufferName);
  857. };
  858. /**
  859. * Binds block to a uniform.
  860. * @param blockName Name of the block to bind.
  861. * @param index Index to bind.
  862. */
  863. Effect.prototype.bindUniformBlock = function (blockName, index) {
  864. this._engine.bindUniformBlock(this._program, blockName, index);
  865. };
  866. /**
  867. * Sets an interger value on a uniform variable.
  868. * @param uniformName Name of the variable.
  869. * @param value Value to be set.
  870. * @returns this effect.
  871. */
  872. Effect.prototype.setInt = function (uniformName, value) {
  873. var cache = this._valueCache[uniformName];
  874. if (cache !== undefined && cache === value)
  875. return this;
  876. this._valueCache[uniformName] = value;
  877. this._engine.setInt(this.getUniform(uniformName), value);
  878. return this;
  879. };
  880. /**
  881. * Sets an int array on a uniform variable.
  882. * @param uniformName Name of the variable.
  883. * @param array array to be set.
  884. * @returns this effect.
  885. */
  886. Effect.prototype.setIntArray = function (uniformName, array) {
  887. this._valueCache[uniformName] = null;
  888. this._engine.setIntArray(this.getUniform(uniformName), array);
  889. return this;
  890. };
  891. /**
  892. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  893. * @param uniformName Name of the variable.
  894. * @param array array to be set.
  895. * @returns this effect.
  896. */
  897. Effect.prototype.setIntArray2 = function (uniformName, array) {
  898. this._valueCache[uniformName] = null;
  899. this._engine.setIntArray2(this.getUniform(uniformName), array);
  900. return this;
  901. };
  902. /**
  903. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  904. * @param uniformName Name of the variable.
  905. * @param array array to be set.
  906. * @returns this effect.
  907. */
  908. Effect.prototype.setIntArray3 = function (uniformName, array) {
  909. this._valueCache[uniformName] = null;
  910. this._engine.setIntArray3(this.getUniform(uniformName), array);
  911. return this;
  912. };
  913. /**
  914. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  915. * @param uniformName Name of the variable.
  916. * @param array array to be set.
  917. * @returns this effect.
  918. */
  919. Effect.prototype.setIntArray4 = function (uniformName, array) {
  920. this._valueCache[uniformName] = null;
  921. this._engine.setIntArray4(this.getUniform(uniformName), array);
  922. return this;
  923. };
  924. /**
  925. * Sets an float array on a uniform variable.
  926. * @param uniformName Name of the variable.
  927. * @param array array to be set.
  928. * @returns this effect.
  929. */
  930. Effect.prototype.setFloatArray = function (uniformName, array) {
  931. this._valueCache[uniformName] = null;
  932. this._engine.setFloatArray(this.getUniform(uniformName), array);
  933. return this;
  934. };
  935. /**
  936. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  937. * @param uniformName Name of the variable.
  938. * @param array array to be set.
  939. * @returns this effect.
  940. */
  941. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  942. this._valueCache[uniformName] = null;
  943. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  944. return this;
  945. };
  946. /**
  947. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  948. * @param uniformName Name of the variable.
  949. * @param array array to be set.
  950. * @returns this effect.
  951. */
  952. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  953. this._valueCache[uniformName] = null;
  954. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  955. return this;
  956. };
  957. /**
  958. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  959. * @param uniformName Name of the variable.
  960. * @param array array to be set.
  961. * @returns this effect.
  962. */
  963. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  964. this._valueCache[uniformName] = null;
  965. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  966. return this;
  967. };
  968. /**
  969. * Sets an array on a uniform variable.
  970. * @param uniformName Name of the variable.
  971. * @param array array to be set.
  972. * @returns this effect.
  973. */
  974. Effect.prototype.setArray = function (uniformName, array) {
  975. this._valueCache[uniformName] = null;
  976. this._engine.setArray(this.getUniform(uniformName), array);
  977. return this;
  978. };
  979. /**
  980. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  981. * @param uniformName Name of the variable.
  982. * @param array array to be set.
  983. * @returns this effect.
  984. */
  985. Effect.prototype.setArray2 = function (uniformName, array) {
  986. this._valueCache[uniformName] = null;
  987. this._engine.setArray2(this.getUniform(uniformName), array);
  988. return this;
  989. };
  990. /**
  991. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  992. * @param uniformName Name of the variable.
  993. * @param array array to be set.
  994. * @returns this effect.
  995. */
  996. Effect.prototype.setArray3 = function (uniformName, array) {
  997. this._valueCache[uniformName] = null;
  998. this._engine.setArray3(this.getUniform(uniformName), array);
  999. return this;
  1000. };
  1001. /**
  1002. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1003. * @param uniformName Name of the variable.
  1004. * @param array array to be set.
  1005. * @returns this effect.
  1006. */
  1007. Effect.prototype.setArray4 = function (uniformName, array) {
  1008. this._valueCache[uniformName] = null;
  1009. this._engine.setArray4(this.getUniform(uniformName), array);
  1010. return this;
  1011. };
  1012. /**
  1013. * Sets matrices on a uniform variable.
  1014. * @param uniformName Name of the variable.
  1015. * @param matrices matrices to be set.
  1016. * @returns this effect.
  1017. */
  1018. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1019. if (!matrices) {
  1020. return this;
  1021. }
  1022. this._valueCache[uniformName] = null;
  1023. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1024. return this;
  1025. };
  1026. /**
  1027. * Sets matrix on a uniform variable.
  1028. * @param uniformName Name of the variable.
  1029. * @param matrix matrix to be set.
  1030. * @returns this effect.
  1031. */
  1032. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1033. if (this._cacheMatrix(uniformName, matrix)) {
  1034. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1035. }
  1036. return this;
  1037. };
  1038. /**
  1039. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1040. * @param uniformName Name of the variable.
  1041. * @param matrix matrix to be set.
  1042. * @returns this effect.
  1043. */
  1044. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1045. this._valueCache[uniformName] = null;
  1046. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1047. return this;
  1048. };
  1049. /**
  1050. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1051. * @param uniformName Name of the variable.
  1052. * @param matrix matrix to be set.
  1053. * @returns this effect.
  1054. */
  1055. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1056. this._valueCache[uniformName] = null;
  1057. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1058. return this;
  1059. };
  1060. /**
  1061. * Sets a float on a uniform variable.
  1062. * @param uniformName Name of the variable.
  1063. * @param value value to be set.
  1064. * @returns this effect.
  1065. */
  1066. Effect.prototype.setFloat = function (uniformName, value) {
  1067. var cache = this._valueCache[uniformName];
  1068. if (cache !== undefined && cache === value)
  1069. return this;
  1070. this._valueCache[uniformName] = value;
  1071. this._engine.setFloat(this.getUniform(uniformName), value);
  1072. return this;
  1073. };
  1074. /**
  1075. * Sets a boolean on a uniform variable.
  1076. * @param uniformName Name of the variable.
  1077. * @param bool value to be set.
  1078. * @returns this effect.
  1079. */
  1080. Effect.prototype.setBool = function (uniformName, bool) {
  1081. var cache = this._valueCache[uniformName];
  1082. if (cache !== undefined && cache === bool)
  1083. return this;
  1084. this._valueCache[uniformName] = bool;
  1085. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1086. return this;
  1087. };
  1088. /**
  1089. * Sets a Vector2 on a uniform variable.
  1090. * @param uniformName Name of the variable.
  1091. * @param vector2 vector2 to be set.
  1092. * @returns this effect.
  1093. */
  1094. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1095. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1096. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1097. }
  1098. return this;
  1099. };
  1100. /**
  1101. * Sets a float2 on a uniform variable.
  1102. * @param uniformName Name of the variable.
  1103. * @param x First float in float2.
  1104. * @param y Second float in float2.
  1105. * @returns this effect.
  1106. */
  1107. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1108. if (this._cacheFloat2(uniformName, x, y)) {
  1109. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1110. }
  1111. return this;
  1112. };
  1113. /**
  1114. * Sets a Vector3 on a uniform variable.
  1115. * @param uniformName Name of the variable.
  1116. * @param vector3 Value to be set.
  1117. * @returns this effect.
  1118. */
  1119. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1120. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1121. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1122. }
  1123. return this;
  1124. };
  1125. /**
  1126. * Sets a float3 on a uniform variable.
  1127. * @param uniformName Name of the variable.
  1128. * @param x First float in float3.
  1129. * @param y Second float in float3.
  1130. * @param z Third float in float3.
  1131. * @returns this effect.
  1132. */
  1133. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1134. if (this._cacheFloat3(uniformName, x, y, z)) {
  1135. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1136. }
  1137. return this;
  1138. };
  1139. /**
  1140. * Sets a Vector4 on a uniform variable.
  1141. * @param uniformName Name of the variable.
  1142. * @param vector4 Value to be set.
  1143. * @returns this effect.
  1144. */
  1145. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1146. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1147. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1148. }
  1149. return this;
  1150. };
  1151. /**
  1152. * Sets a float4 on a uniform variable.
  1153. * @param uniformName Name of the variable.
  1154. * @param x First float in float4.
  1155. * @param y Second float in float4.
  1156. * @param z Third float in float4.
  1157. * @param w Fourth float in float4.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1161. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1162. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a Color3 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param color3 Value to be set.
  1170. * @returns this effect.
  1171. */
  1172. Effect.prototype.setColor3 = function (uniformName, color3) {
  1173. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1174. this._engine.setColor3(this.getUniform(uniformName), color3);
  1175. }
  1176. return this;
  1177. };
  1178. /**
  1179. * Sets a Color4 on a uniform variable.
  1180. * @param uniformName Name of the variable.
  1181. * @param color3 Value to be set.
  1182. * @param alpha Alpha value to be set.
  1183. * @returns this effect.
  1184. */
  1185. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1186. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1187. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1188. }
  1189. return this;
  1190. };
  1191. /**
  1192. * Sets a Color4 on a uniform variable
  1193. * @param uniformName defines the name of the variable
  1194. * @param color4 defines the value to be set
  1195. * @returns this effect.
  1196. */
  1197. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1198. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1199. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1200. }
  1201. return this;
  1202. };
  1203. /**
  1204. * This function will add a new shader to the shader store
  1205. * @param name the name of the shader
  1206. * @param pixelShader optional pixel shader content
  1207. * @param vertexShader optional vertex shader content
  1208. */
  1209. Effect.RegisterShader = function (name, pixelShader, vertexShader) {
  1210. if (pixelShader) {
  1211. Effect.ShadersStore[name + "PixelShader"] = pixelShader;
  1212. }
  1213. if (vertexShader) {
  1214. Effect.ShadersStore[name + "VertexShader"] = vertexShader;
  1215. }
  1216. };
  1217. /**
  1218. * Resets the cache of effects.
  1219. */
  1220. Effect.ResetCache = function () {
  1221. Effect._baseCache = {};
  1222. };
  1223. Effect._uniqueIdSeed = 0;
  1224. Effect._baseCache = {};
  1225. /**
  1226. * Store of each shader (The can be looked up using effect.key)
  1227. */
  1228. Effect.ShadersStore = {};
  1229. /**
  1230. * Store of each included file for a shader (The can be looked up using effect.key)
  1231. */
  1232. Effect.IncludesShadersStore = {};
  1233. return Effect;
  1234. }());
  1235. BABYLON.Effect = Effect;
  1236. })(BABYLON || (BABYLON = {}));
  1237. //# sourceMappingURL=babylon.effect.js.map
  1238. //# sourceMappingURL=babylon.types.js.map
  1239. var BABYLON;
  1240. (function (BABYLON) {
  1241. var KeyboardEventTypes = /** @class */ (function () {
  1242. function KeyboardEventTypes() {
  1243. }
  1244. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1245. get: function () {
  1246. return KeyboardEventTypes._KEYDOWN;
  1247. },
  1248. enumerable: true,
  1249. configurable: true
  1250. });
  1251. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1252. get: function () {
  1253. return KeyboardEventTypes._KEYUP;
  1254. },
  1255. enumerable: true,
  1256. configurable: true
  1257. });
  1258. KeyboardEventTypes._KEYDOWN = 0x01;
  1259. KeyboardEventTypes._KEYUP = 0x02;
  1260. return KeyboardEventTypes;
  1261. }());
  1262. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1263. var KeyboardInfo = /** @class */ (function () {
  1264. function KeyboardInfo(type, event) {
  1265. this.type = type;
  1266. this.event = event;
  1267. }
  1268. return KeyboardInfo;
  1269. }());
  1270. BABYLON.KeyboardInfo = KeyboardInfo;
  1271. /**
  1272. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1273. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1274. */
  1275. var KeyboardInfoPre = /** @class */ (function (_super) {
  1276. __extends(KeyboardInfoPre, _super);
  1277. function KeyboardInfoPre(type, event) {
  1278. var _this = _super.call(this, type, event) || this;
  1279. _this.skipOnPointerObservable = false;
  1280. return _this;
  1281. }
  1282. return KeyboardInfoPre;
  1283. }(KeyboardInfo));
  1284. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1285. })(BABYLON || (BABYLON = {}));
  1286. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1287. var BABYLON;
  1288. (function (BABYLON) {
  1289. var PointerEventTypes = /** @class */ (function () {
  1290. function PointerEventTypes() {
  1291. }
  1292. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1293. get: function () {
  1294. return PointerEventTypes._POINTERDOWN;
  1295. },
  1296. enumerable: true,
  1297. configurable: true
  1298. });
  1299. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1300. get: function () {
  1301. return PointerEventTypes._POINTERUP;
  1302. },
  1303. enumerable: true,
  1304. configurable: true
  1305. });
  1306. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1307. get: function () {
  1308. return PointerEventTypes._POINTERMOVE;
  1309. },
  1310. enumerable: true,
  1311. configurable: true
  1312. });
  1313. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1314. get: function () {
  1315. return PointerEventTypes._POINTERWHEEL;
  1316. },
  1317. enumerable: true,
  1318. configurable: true
  1319. });
  1320. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1321. get: function () {
  1322. return PointerEventTypes._POINTERPICK;
  1323. },
  1324. enumerable: true,
  1325. configurable: true
  1326. });
  1327. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1328. get: function () {
  1329. return PointerEventTypes._POINTERTAP;
  1330. },
  1331. enumerable: true,
  1332. configurable: true
  1333. });
  1334. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1335. get: function () {
  1336. return PointerEventTypes._POINTERDOUBLETAP;
  1337. },
  1338. enumerable: true,
  1339. configurable: true
  1340. });
  1341. PointerEventTypes._POINTERDOWN = 0x01;
  1342. PointerEventTypes._POINTERUP = 0x02;
  1343. PointerEventTypes._POINTERMOVE = 0x04;
  1344. PointerEventTypes._POINTERWHEEL = 0x08;
  1345. PointerEventTypes._POINTERPICK = 0x10;
  1346. PointerEventTypes._POINTERTAP = 0x20;
  1347. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1348. return PointerEventTypes;
  1349. }());
  1350. BABYLON.PointerEventTypes = PointerEventTypes;
  1351. var PointerInfoBase = /** @class */ (function () {
  1352. function PointerInfoBase(type, event) {
  1353. this.type = type;
  1354. this.event = event;
  1355. }
  1356. return PointerInfoBase;
  1357. }());
  1358. BABYLON.PointerInfoBase = PointerInfoBase;
  1359. /**
  1360. * This class is used to store pointer related info for the onPrePointerObservable event.
  1361. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1362. */
  1363. var PointerInfoPre = /** @class */ (function (_super) {
  1364. __extends(PointerInfoPre, _super);
  1365. function PointerInfoPre(type, event, localX, localY) {
  1366. var _this = _super.call(this, type, event) || this;
  1367. /**
  1368. * Ray from a pointer if availible (eg. 6dof controller)
  1369. */
  1370. _this.ray = null;
  1371. _this.skipOnPointerObservable = false;
  1372. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1373. return _this;
  1374. }
  1375. return PointerInfoPre;
  1376. }(PointerInfoBase));
  1377. BABYLON.PointerInfoPre = PointerInfoPre;
  1378. /**
  1379. * This type contains all the data related to a pointer event in Babylon.js.
  1380. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1381. */
  1382. var PointerInfo = /** @class */ (function (_super) {
  1383. __extends(PointerInfo, _super);
  1384. function PointerInfo(type, event, pickInfo) {
  1385. var _this = _super.call(this, type, event) || this;
  1386. _this.pickInfo = pickInfo;
  1387. return _this;
  1388. }
  1389. return PointerInfo;
  1390. }(PointerInfoBase));
  1391. BABYLON.PointerInfo = PointerInfo;
  1392. })(BABYLON || (BABYLON = {}));
  1393. //# sourceMappingURL=babylon.pointerEvents.js.map
  1394. var BABYLON;
  1395. (function (BABYLON) {
  1396. BABYLON.ToGammaSpace = 1 / 2.2;
  1397. BABYLON.ToLinearSpace = 2.2;
  1398. BABYLON.Epsilon = 0.001;
  1399. /**
  1400. * Class used to hold a RBG color
  1401. */
  1402. var Color3 = /** @class */ (function () {
  1403. /**
  1404. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1405. * @param r defines the red component (between 0 and 1, default is 0)
  1406. * @param g defines the green component (between 0 and 1, default is 0)
  1407. * @param b defines the blue component (between 0 and 1, default is 0)
  1408. */
  1409. function Color3(
  1410. /**
  1411. * Defines the red component (between 0 and 1, default is 0)
  1412. */
  1413. r,
  1414. /**
  1415. * Defines the green component (between 0 and 1, default is 0)
  1416. */
  1417. g,
  1418. /**
  1419. * Defines the blue component (between 0 and 1, default is 0)
  1420. */
  1421. b) {
  1422. if (r === void 0) { r = 0; }
  1423. if (g === void 0) { g = 0; }
  1424. if (b === void 0) { b = 0; }
  1425. this.r = r;
  1426. this.g = g;
  1427. this.b = b;
  1428. }
  1429. /**
  1430. * Creates a string with the Color3 current values
  1431. * @returns the string representation of the Color3 object
  1432. */
  1433. Color3.prototype.toString = function () {
  1434. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1435. };
  1436. /**
  1437. * Returns the string "Color3"
  1438. * @returns "Color3"
  1439. */
  1440. Color3.prototype.getClassName = function () {
  1441. return "Color3";
  1442. };
  1443. /**
  1444. * Compute the Color3 hash code
  1445. * @returns an unique number that can be used to hash Color3 objects
  1446. */
  1447. Color3.prototype.getHashCode = function () {
  1448. var hash = this.r || 0;
  1449. hash = (hash * 397) ^ (this.g || 0);
  1450. hash = (hash * 397) ^ (this.b || 0);
  1451. return hash;
  1452. };
  1453. // Operators
  1454. /**
  1455. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1456. * @param array defines the array where to store the r,g,b components
  1457. * @param index defines an optional index in the target array to define where to start storing values
  1458. * @returns the current Color3 object
  1459. */
  1460. Color3.prototype.toArray = function (array, index) {
  1461. if (index === undefined) {
  1462. index = 0;
  1463. }
  1464. array[index] = this.r;
  1465. array[index + 1] = this.g;
  1466. array[index + 2] = this.b;
  1467. return this;
  1468. };
  1469. /**
  1470. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1471. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1472. * @returns a new {BABYLON.Color4} object
  1473. */
  1474. Color3.prototype.toColor4 = function (alpha) {
  1475. if (alpha === void 0) { alpha = 1; }
  1476. return new Color4(this.r, this.g, this.b, alpha);
  1477. };
  1478. /**
  1479. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1480. * @returns the new array
  1481. */
  1482. Color3.prototype.asArray = function () {
  1483. var result = new Array();
  1484. this.toArray(result, 0);
  1485. return result;
  1486. };
  1487. /**
  1488. * Returns the luminance value
  1489. * @returns a float value
  1490. */
  1491. Color3.prototype.toLuminance = function () {
  1492. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1493. };
  1494. /**
  1495. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1496. * @param otherColor defines the second operand
  1497. * @returns the new Color3 object
  1498. */
  1499. Color3.prototype.multiply = function (otherColor) {
  1500. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1501. };
  1502. /**
  1503. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1504. * @param otherColor defines the second operand
  1505. * @param result defines the Color3 object where to store the result
  1506. * @returns the current Color3
  1507. */
  1508. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1509. result.r = this.r * otherColor.r;
  1510. result.g = this.g * otherColor.g;
  1511. result.b = this.b * otherColor.b;
  1512. return this;
  1513. };
  1514. /**
  1515. * Determines equality between Color3 objects
  1516. * @param otherColor defines the second operand
  1517. * @returns true if the rgb values are equal to the given ones
  1518. */
  1519. Color3.prototype.equals = function (otherColor) {
  1520. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1521. };
  1522. /**
  1523. * Determines equality between the current Color3 object and a set of r,b,g values
  1524. * @param r defines the red component to check
  1525. * @param g defines the green component to check
  1526. * @param b defines the blue component to check
  1527. * @returns true if the rgb values are equal to the given ones
  1528. */
  1529. Color3.prototype.equalsFloats = function (r, g, b) {
  1530. return this.r === r && this.g === g && this.b === b;
  1531. };
  1532. /**
  1533. * Multiplies in place each rgb value by scale
  1534. * @param scale defines the scaling factor
  1535. * @returns the updated Color3
  1536. */
  1537. Color3.prototype.scale = function (scale) {
  1538. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1539. };
  1540. /**
  1541. * Multiplies the rgb values by scale and stores the result into "result"
  1542. * @param scale defines the scaling factor
  1543. * @param result defines the Color3 object where to store the result
  1544. * @returns the unmodified current Color3
  1545. */
  1546. Color3.prototype.scaleToRef = function (scale, result) {
  1547. result.r = this.r * scale;
  1548. result.g = this.g * scale;
  1549. result.b = this.b * scale;
  1550. return this;
  1551. };
  1552. /**
  1553. * Scale the current Color3 values by a factor and add the result to a given Color3
  1554. * @param scale defines the scale factor
  1555. * @param result defines color to store the result into
  1556. * @returns the unmodified current Color3
  1557. */
  1558. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1559. result.r += this.r * scale;
  1560. result.g += this.g * scale;
  1561. result.b += this.b * scale;
  1562. return this;
  1563. };
  1564. /**
  1565. * Clamps the rgb values by the min and max values and stores the result into "result"
  1566. * @param min defines minimum clamping value (default is 0)
  1567. * @param max defines maximum clamping value (default is 1)
  1568. * @param result defines color to store the result into
  1569. * @returns the original Color3
  1570. */
  1571. Color3.prototype.clampToRef = function (min, max, result) {
  1572. if (min === void 0) { min = 0; }
  1573. if (max === void 0) { max = 1; }
  1574. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1575. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1576. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1577. return this;
  1578. };
  1579. /**
  1580. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1581. * @param otherColor defines the second operand
  1582. * @returns the new Color3
  1583. */
  1584. Color3.prototype.add = function (otherColor) {
  1585. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1586. };
  1587. /**
  1588. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1589. * @param otherColor defines the second operand
  1590. * @param result defines Color3 object to store the result into
  1591. * @returns the unmodified current Color3
  1592. */
  1593. Color3.prototype.addToRef = function (otherColor, result) {
  1594. result.r = this.r + otherColor.r;
  1595. result.g = this.g + otherColor.g;
  1596. result.b = this.b + otherColor.b;
  1597. return this;
  1598. };
  1599. /**
  1600. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1601. * @param otherColor defines the second operand
  1602. * @returns the new Color3
  1603. */
  1604. Color3.prototype.subtract = function (otherColor) {
  1605. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1606. };
  1607. /**
  1608. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1609. * @param otherColor defines the second operand
  1610. * @param result defines Color3 object to store the result into
  1611. * @returns the unmodified current Color3
  1612. */
  1613. Color3.prototype.subtractToRef = function (otherColor, result) {
  1614. result.r = this.r - otherColor.r;
  1615. result.g = this.g - otherColor.g;
  1616. result.b = this.b - otherColor.b;
  1617. return this;
  1618. };
  1619. /**
  1620. * Copy the current object
  1621. * @returns a new Color3 copied the current one
  1622. */
  1623. Color3.prototype.clone = function () {
  1624. return new Color3(this.r, this.g, this.b);
  1625. };
  1626. /**
  1627. * Copies the rgb values from the source in the current Color3
  1628. * @param source defines the source Color3 object
  1629. * @returns the updated Color3 object
  1630. */
  1631. Color3.prototype.copyFrom = function (source) {
  1632. this.r = source.r;
  1633. this.g = source.g;
  1634. this.b = source.b;
  1635. return this;
  1636. };
  1637. /**
  1638. * Updates the Color3 rgb values from the given floats
  1639. * @param r defines the red component to read from
  1640. * @param g defines the green component to read from
  1641. * @param b defines the blue component to read from
  1642. * @returns the current Color3 object
  1643. */
  1644. Color3.prototype.copyFromFloats = function (r, g, b) {
  1645. this.r = r;
  1646. this.g = g;
  1647. this.b = b;
  1648. return this;
  1649. };
  1650. /**
  1651. * Updates the Color3 rgb values from the given floats
  1652. * @param r defines the red component to read from
  1653. * @param g defines the green component to read from
  1654. * @param b defines the blue component to read from
  1655. * @returns the current Color3 object
  1656. */
  1657. Color3.prototype.set = function (r, g, b) {
  1658. return this.copyFromFloats(r, g, b);
  1659. };
  1660. /**
  1661. * Compute the Color3 hexadecimal code as a string
  1662. * @returns a string containing the hexadecimal representation of the Color3 object
  1663. */
  1664. Color3.prototype.toHexString = function () {
  1665. var intR = (this.r * 255) | 0;
  1666. var intG = (this.g * 255) | 0;
  1667. var intB = (this.b * 255) | 0;
  1668. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1669. };
  1670. /**
  1671. * Computes a new Color3 converted from the current one to linear space
  1672. * @returns a new Color3 object
  1673. */
  1674. Color3.prototype.toLinearSpace = function () {
  1675. var convertedColor = new Color3();
  1676. this.toLinearSpaceToRef(convertedColor);
  1677. return convertedColor;
  1678. };
  1679. /**
  1680. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1681. * @param convertedColor defines the Color3 object where to store the linear space version
  1682. * @returns the unmodified Color3
  1683. */
  1684. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1685. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1686. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1687. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1688. return this;
  1689. };
  1690. /**
  1691. * Computes a new Color3 converted from the current one to gamma space
  1692. * @returns a new Color3 object
  1693. */
  1694. Color3.prototype.toGammaSpace = function () {
  1695. var convertedColor = new Color3();
  1696. this.toGammaSpaceToRef(convertedColor);
  1697. return convertedColor;
  1698. };
  1699. /**
  1700. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1701. * @param convertedColor defines the Color3 object where to store the gamma space version
  1702. * @returns the unmodified Color3
  1703. */
  1704. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1705. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1706. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1707. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1708. return this;
  1709. };
  1710. // Statics
  1711. /**
  1712. * Creates a new Color3 from the string containing valid hexadecimal values
  1713. * @param hex defines a string containing valid hexadecimal values
  1714. * @returns a new Color3 object
  1715. */
  1716. Color3.FromHexString = function (hex) {
  1717. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1718. return new Color3(0, 0, 0);
  1719. }
  1720. var r = parseInt(hex.substring(1, 3), 16);
  1721. var g = parseInt(hex.substring(3, 5), 16);
  1722. var b = parseInt(hex.substring(5, 7), 16);
  1723. return Color3.FromInts(r, g, b);
  1724. };
  1725. /**
  1726. * Creates a new Vector3 from the starting index of the given array
  1727. * @param array defines the source array
  1728. * @param offset defines an offset in the source array
  1729. * @returns a new Color3 object
  1730. */
  1731. Color3.FromArray = function (array, offset) {
  1732. if (offset === void 0) { offset = 0; }
  1733. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1734. };
  1735. /**
  1736. * Creates a new Color3 from integer values (< 256)
  1737. * @param r defines the red component to read from (value between 0 and 255)
  1738. * @param g defines the green component to read from (value between 0 and 255)
  1739. * @param b defines the blue component to read from (value between 0 and 255)
  1740. * @returns a new Color3 object
  1741. */
  1742. Color3.FromInts = function (r, g, b) {
  1743. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1744. };
  1745. /**
  1746. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1747. * @param start defines the start Color3 value
  1748. * @param end defines the end Color3 value
  1749. * @param amount defines the gradient value between start and end
  1750. * @returns a new Color3 object
  1751. */
  1752. Color3.Lerp = function (start, end, amount) {
  1753. var r = start.r + ((end.r - start.r) * amount);
  1754. var g = start.g + ((end.g - start.g) * amount);
  1755. var b = start.b + ((end.b - start.b) * amount);
  1756. return new Color3(r, g, b);
  1757. };
  1758. /**
  1759. * Returns a Color3 value containing a red color
  1760. * @returns a new Color3 object
  1761. */
  1762. Color3.Red = function () { return new Color3(1, 0, 0); };
  1763. /**
  1764. * Returns a Color3 value containing a green color
  1765. * @returns a new Color3 object
  1766. */
  1767. Color3.Green = function () { return new Color3(0, 1, 0); };
  1768. /**
  1769. * Returns a Color3 value containing a blue color
  1770. * @returns a new Color3 object
  1771. */
  1772. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1773. /**
  1774. * Returns a Color3 value containing a black color
  1775. * @returns a new Color3 object
  1776. */
  1777. Color3.Black = function () { return new Color3(0, 0, 0); };
  1778. /**
  1779. * Returns a Color3 value containing a white color
  1780. * @returns a new Color3 object
  1781. */
  1782. Color3.White = function () { return new Color3(1, 1, 1); };
  1783. /**
  1784. * Returns a Color3 value containing a purple color
  1785. * @returns a new Color3 object
  1786. */
  1787. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1788. /**
  1789. * Returns a Color3 value containing a magenta color
  1790. * @returns a new Color3 object
  1791. */
  1792. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1793. /**
  1794. * Returns a Color3 value containing a yellow color
  1795. * @returns a new Color3 object
  1796. */
  1797. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1798. /**
  1799. * Returns a Color3 value containing a gray color
  1800. * @returns a new Color3 object
  1801. */
  1802. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1803. /**
  1804. * Returns a Color3 value containing a teal color
  1805. * @returns a new Color3 object
  1806. */
  1807. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1808. /**
  1809. * Returns a Color3 value containing a random color
  1810. * @returns a new Color3 object
  1811. */
  1812. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1813. return Color3;
  1814. }());
  1815. BABYLON.Color3 = Color3;
  1816. /**
  1817. * Class used to hold a RBGA color
  1818. */
  1819. var Color4 = /** @class */ (function () {
  1820. /**
  1821. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1822. * @param r defines the red component (between 0 and 1, default is 0)
  1823. * @param g defines the green component (between 0 and 1, default is 0)
  1824. * @param b defines the blue component (between 0 and 1, default is 0)
  1825. * @param a defines the alpha component (between 0 and 1, default is 1)
  1826. */
  1827. function Color4(
  1828. /**
  1829. * Defines the red component (between 0 and 1, default is 0)
  1830. */
  1831. r,
  1832. /**
  1833. * Defines the green component (between 0 and 1, default is 0)
  1834. */
  1835. g,
  1836. /**
  1837. * Defines the blue component (between 0 and 1, default is 0)
  1838. */
  1839. b,
  1840. /**
  1841. * Defines the alpha component (between 0 and 1, default is 1)
  1842. */
  1843. a) {
  1844. if (r === void 0) { r = 0; }
  1845. if (g === void 0) { g = 0; }
  1846. if (b === void 0) { b = 0; }
  1847. if (a === void 0) { a = 1; }
  1848. this.r = r;
  1849. this.g = g;
  1850. this.b = b;
  1851. this.a = a;
  1852. }
  1853. // Operators
  1854. /**
  1855. * Adds in place the given Color4 values to the current Color4 object
  1856. * @param right defines the second operand
  1857. * @returns the current updated Color4 object
  1858. */
  1859. Color4.prototype.addInPlace = function (right) {
  1860. this.r += right.r;
  1861. this.g += right.g;
  1862. this.b += right.b;
  1863. this.a += right.a;
  1864. return this;
  1865. };
  1866. /**
  1867. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1868. * @returns the new array
  1869. */
  1870. Color4.prototype.asArray = function () {
  1871. var result = new Array();
  1872. this.toArray(result, 0);
  1873. return result;
  1874. };
  1875. /**
  1876. * Stores from the starting index in the given array the Color4 successive values
  1877. * @param array defines the array where to store the r,g,b components
  1878. * @param index defines an optional index in the target array to define where to start storing values
  1879. * @returns the current Color4 object
  1880. */
  1881. Color4.prototype.toArray = function (array, index) {
  1882. if (index === undefined) {
  1883. index = 0;
  1884. }
  1885. array[index] = this.r;
  1886. array[index + 1] = this.g;
  1887. array[index + 2] = this.b;
  1888. array[index + 3] = this.a;
  1889. return this;
  1890. };
  1891. /**
  1892. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1893. * @param right defines the second operand
  1894. * @returns a new Color4 object
  1895. */
  1896. Color4.prototype.add = function (right) {
  1897. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1898. };
  1899. /**
  1900. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1901. * @param right defines the second operand
  1902. * @returns a new Color4 object
  1903. */
  1904. Color4.prototype.subtract = function (right) {
  1905. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1906. };
  1907. /**
  1908. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1909. * @param right defines the second operand
  1910. * @param result defines the Color4 object where to store the result
  1911. * @returns the current Color4 object
  1912. */
  1913. Color4.prototype.subtractToRef = function (right, result) {
  1914. result.r = this.r - right.r;
  1915. result.g = this.g - right.g;
  1916. result.b = this.b - right.b;
  1917. result.a = this.a - right.a;
  1918. return this;
  1919. };
  1920. /**
  1921. * Creates a new Color4 with the current Color4 values multiplied by scale
  1922. * @param scale defines the scaling factor to apply
  1923. * @returns a new Color4 object
  1924. */
  1925. Color4.prototype.scale = function (scale) {
  1926. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1927. };
  1928. /**
  1929. * Multiplies the current Color4 values by scale and stores the result in "result"
  1930. * @param scale defines the scaling factor to apply
  1931. * @param result defines the Color4 object where to store the result
  1932. * @returns the current unmodified Color4
  1933. */
  1934. Color4.prototype.scaleToRef = function (scale, result) {
  1935. result.r = this.r * scale;
  1936. result.g = this.g * scale;
  1937. result.b = this.b * scale;
  1938. result.a = this.a * scale;
  1939. return this;
  1940. };
  1941. /**
  1942. * Scale the current Color4 values by a factor and add the result to a given Color4
  1943. * @param scale defines the scale factor
  1944. * @param result defines the Color4 object where to store the result
  1945. * @returns the unmodified current Color4
  1946. */
  1947. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1948. result.r += this.r * scale;
  1949. result.g += this.g * scale;
  1950. result.b += this.b * scale;
  1951. result.a += this.a * scale;
  1952. return this;
  1953. };
  1954. /**
  1955. * Clamps the rgb values by the min and max values and stores the result into "result"
  1956. * @param min defines minimum clamping value (default is 0)
  1957. * @param max defines maximum clamping value (default is 1)
  1958. * @param result defines color to store the result into.
  1959. * @returns the cuurent Color4
  1960. */
  1961. Color4.prototype.clampToRef = function (min, max, result) {
  1962. if (min === void 0) { min = 0; }
  1963. if (max === void 0) { max = 1; }
  1964. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1965. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1966. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1967. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1968. return this;
  1969. };
  1970. /**
  1971. * Multipy an Color4 value by another and return a new Color4 object
  1972. * @param color defines the Color4 value to multiply by
  1973. * @returns a new Color4 object
  1974. */
  1975. Color4.prototype.multiply = function (color) {
  1976. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1977. };
  1978. /**
  1979. * Multipy a Color4 value by another and push the result in a reference value
  1980. * @param color defines the Color4 value to multiply by
  1981. * @param result defines the Color4 to fill the result in
  1982. * @returns the result Color4
  1983. */
  1984. Color4.prototype.multiplyToRef = function (color, result) {
  1985. result.r = this.r * color.r;
  1986. result.g = this.g * color.g;
  1987. result.b = this.b * color.b;
  1988. result.a = this.a * color.a;
  1989. return result;
  1990. };
  1991. /**
  1992. * Creates a string with the Color4 current values
  1993. * @returns the string representation of the Color4 object
  1994. */
  1995. Color4.prototype.toString = function () {
  1996. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1997. };
  1998. /**
  1999. * Returns the string "Color4"
  2000. * @returns "Color4"
  2001. */
  2002. Color4.prototype.getClassName = function () {
  2003. return "Color4";
  2004. };
  2005. /**
  2006. * Compute the Color4 hash code
  2007. * @returns an unique number that can be used to hash Color4 objects
  2008. */
  2009. Color4.prototype.getHashCode = function () {
  2010. var hash = this.r || 0;
  2011. hash = (hash * 397) ^ (this.g || 0);
  2012. hash = (hash * 397) ^ (this.b || 0);
  2013. hash = (hash * 397) ^ (this.a || 0);
  2014. return hash;
  2015. };
  2016. /**
  2017. * Creates a new Color4 copied from the current one
  2018. * @returns a new Color4 object
  2019. */
  2020. Color4.prototype.clone = function () {
  2021. return new Color4(this.r, this.g, this.b, this.a);
  2022. };
  2023. /**
  2024. * Copies the given Color4 values into the current one
  2025. * @param source defines the source Color4 object
  2026. * @returns the current updated Color4 object
  2027. */
  2028. Color4.prototype.copyFrom = function (source) {
  2029. this.r = source.r;
  2030. this.g = source.g;
  2031. this.b = source.b;
  2032. this.a = source.a;
  2033. return this;
  2034. };
  2035. /**
  2036. * Copies the given float values into the current one
  2037. * @param r defines the red component to read from
  2038. * @param g defines the green component to read from
  2039. * @param b defines the blue component to read from
  2040. * @param a defines the alpha component to read from
  2041. * @returns the current updated Color4 object
  2042. */
  2043. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2044. this.r = r;
  2045. this.g = g;
  2046. this.b = b;
  2047. this.a = a;
  2048. return this;
  2049. };
  2050. /**
  2051. * Copies the given float values into the current one
  2052. * @param r defines the red component to read from
  2053. * @param g defines the green component to read from
  2054. * @param b defines the blue component to read from
  2055. * @param a defines the alpha component to read from
  2056. * @returns the current updated Color4 object
  2057. */
  2058. Color4.prototype.set = function (r, g, b, a) {
  2059. return this.copyFromFloats(r, g, b, a);
  2060. };
  2061. /**
  2062. * Compute the Color4 hexadecimal code as a string
  2063. * @returns a string containing the hexadecimal representation of the Color4 object
  2064. */
  2065. Color4.prototype.toHexString = function () {
  2066. var intR = (this.r * 255) | 0;
  2067. var intG = (this.g * 255) | 0;
  2068. var intB = (this.b * 255) | 0;
  2069. var intA = (this.a * 255) | 0;
  2070. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2071. };
  2072. /**
  2073. * Computes a new Color4 converted from the current one to linear space
  2074. * @returns a new Color4 object
  2075. */
  2076. Color4.prototype.toLinearSpace = function () {
  2077. var convertedColor = new Color4();
  2078. this.toLinearSpaceToRef(convertedColor);
  2079. return convertedColor;
  2080. };
  2081. /**
  2082. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2083. * @param convertedColor defines the Color4 object where to store the linear space version
  2084. * @returns the unmodified Color4
  2085. */
  2086. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2087. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2088. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2089. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2090. convertedColor.a = this.a;
  2091. return this;
  2092. };
  2093. /**
  2094. * Computes a new Color4 converted from the current one to gamma space
  2095. * @returns a new Color4 object
  2096. */
  2097. Color4.prototype.toGammaSpace = function () {
  2098. var convertedColor = new Color4();
  2099. this.toGammaSpaceToRef(convertedColor);
  2100. return convertedColor;
  2101. };
  2102. /**
  2103. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2104. * @param convertedColor defines the Color4 object where to store the gamma space version
  2105. * @returns the unmodified Color4
  2106. */
  2107. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2108. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2109. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2110. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2111. convertedColor.a = this.a;
  2112. return this;
  2113. };
  2114. // Statics
  2115. /**
  2116. * Creates a new Color4 from the string containing valid hexadecimal values
  2117. * @param hex defines a string containing valid hexadecimal values
  2118. * @returns a new Color4 object
  2119. */
  2120. Color4.FromHexString = function (hex) {
  2121. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2122. return new Color4(0.0, 0.0, 0.0, 0.0);
  2123. }
  2124. var r = parseInt(hex.substring(1, 3), 16);
  2125. var g = parseInt(hex.substring(3, 5), 16);
  2126. var b = parseInt(hex.substring(5, 7), 16);
  2127. var a = parseInt(hex.substring(7, 9), 16);
  2128. return Color4.FromInts(r, g, b, a);
  2129. };
  2130. /**
  2131. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2132. * @param left defines the start value
  2133. * @param right defines the end value
  2134. * @param amount defines the gradient factor
  2135. * @returns a new Color4 object
  2136. */
  2137. Color4.Lerp = function (left, right, amount) {
  2138. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2139. Color4.LerpToRef(left, right, amount, result);
  2140. return result;
  2141. };
  2142. /**
  2143. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2144. * @param left defines the start value
  2145. * @param right defines the end value
  2146. * @param amount defines the gradient factor
  2147. * @param result defines the Color4 object where to store data
  2148. */
  2149. Color4.LerpToRef = function (left, right, amount, result) {
  2150. result.r = left.r + (right.r - left.r) * amount;
  2151. result.g = left.g + (right.g - left.g) * amount;
  2152. result.b = left.b + (right.b - left.b) * amount;
  2153. result.a = left.a + (right.a - left.a) * amount;
  2154. };
  2155. /**
  2156. * Creates a new Color4 from the starting index element of the given array
  2157. * @param array defines the source array to read from
  2158. * @param offset defines the offset in the source array
  2159. * @returns a new Color4 object
  2160. */
  2161. Color4.FromArray = function (array, offset) {
  2162. if (offset === void 0) { offset = 0; }
  2163. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2164. };
  2165. /**
  2166. * Creates a new Color3 from integer values (< 256)
  2167. * @param r defines the red component to read from (value between 0 and 255)
  2168. * @param g defines the green component to read from (value between 0 and 255)
  2169. * @param b defines the blue component to read from (value between 0 and 255)
  2170. * @param a defines the alpha component to read from (value between 0 and 255)
  2171. * @returns a new Color3 object
  2172. */
  2173. Color4.FromInts = function (r, g, b, a) {
  2174. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2175. };
  2176. /**
  2177. * Check the content of a given array and convert it to an array containing RGBA data
  2178. * If the original array was already containing count * 4 values then it is returned directly
  2179. * @param colors defines the array to check
  2180. * @param count defines the number of RGBA data to expect
  2181. * @returns an array containing count * 4 values (RGBA)
  2182. */
  2183. Color4.CheckColors4 = function (colors, count) {
  2184. // Check if color3 was used
  2185. if (colors.length === count * 3) {
  2186. var colors4 = [];
  2187. for (var index = 0; index < colors.length; index += 3) {
  2188. var newIndex = (index / 3) * 4;
  2189. colors4[newIndex] = colors[index];
  2190. colors4[newIndex + 1] = colors[index + 1];
  2191. colors4[newIndex + 2] = colors[index + 2];
  2192. colors4[newIndex + 3] = 1.0;
  2193. }
  2194. return colors4;
  2195. }
  2196. return colors;
  2197. };
  2198. return Color4;
  2199. }());
  2200. BABYLON.Color4 = Color4;
  2201. /**
  2202. * Class representing a vector containing 2 coordinates
  2203. */
  2204. var Vector2 = /** @class */ (function () {
  2205. /**
  2206. * Creates a new Vector2 from the given x and y coordinates
  2207. * @param x defines the first coordinate
  2208. * @param y defines the second coordinate
  2209. */
  2210. function Vector2(
  2211. /** defines the first coordinate */
  2212. x,
  2213. /** defines the second coordinate */
  2214. y) {
  2215. if (x === void 0) { x = 0; }
  2216. if (y === void 0) { y = 0; }
  2217. this.x = x;
  2218. this.y = y;
  2219. }
  2220. /**
  2221. * Gets a string with the Vector2 coordinates
  2222. * @returns a string with the Vector2 coordinates
  2223. */
  2224. Vector2.prototype.toString = function () {
  2225. return "{X: " + this.x + " Y:" + this.y + "}";
  2226. };
  2227. /**
  2228. * Gets class name
  2229. * @returns the string "Vector2"
  2230. */
  2231. Vector2.prototype.getClassName = function () {
  2232. return "Vector2";
  2233. };
  2234. /**
  2235. * Gets current vector hash code
  2236. * @returns the Vector2 hash code as a number
  2237. */
  2238. Vector2.prototype.getHashCode = function () {
  2239. var hash = this.x || 0;
  2240. hash = (hash * 397) ^ (this.y || 0);
  2241. return hash;
  2242. };
  2243. // Operators
  2244. /**
  2245. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2246. * @param array defines the source array
  2247. * @param index defines the offset in source array
  2248. * @returns the current Vector2
  2249. */
  2250. Vector2.prototype.toArray = function (array, index) {
  2251. if (index === void 0) { index = 0; }
  2252. array[index] = this.x;
  2253. array[index + 1] = this.y;
  2254. return this;
  2255. };
  2256. /**
  2257. * Copy the current vector to an array
  2258. * @returns a new array with 2 elements: the Vector2 coordinates.
  2259. */
  2260. Vector2.prototype.asArray = function () {
  2261. var result = new Array();
  2262. this.toArray(result, 0);
  2263. return result;
  2264. };
  2265. /**
  2266. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2267. * @param source defines the source Vector2
  2268. * @returns the current updated Vector2
  2269. */
  2270. Vector2.prototype.copyFrom = function (source) {
  2271. this.x = source.x;
  2272. this.y = source.y;
  2273. return this;
  2274. };
  2275. /**
  2276. * Sets the Vector2 coordinates with the given floats
  2277. * @param x defines the first coordinate
  2278. * @param y defines the second coordinate
  2279. * @returns the current updated Vector2
  2280. */
  2281. Vector2.prototype.copyFromFloats = function (x, y) {
  2282. this.x = x;
  2283. this.y = y;
  2284. return this;
  2285. };
  2286. /**
  2287. * Sets the Vector2 coordinates with the given floats
  2288. * @param x defines the first coordinate
  2289. * @param y defines the second coordinate
  2290. * @returns the current updated Vector2
  2291. */
  2292. Vector2.prototype.set = function (x, y) {
  2293. return this.copyFromFloats(x, y);
  2294. };
  2295. /**
  2296. * Add another vector with the current one
  2297. * @param otherVector defines the other vector
  2298. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2299. */
  2300. Vector2.prototype.add = function (otherVector) {
  2301. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2302. };
  2303. /**
  2304. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2305. * @param otherVector defines the other vector
  2306. * @param result defines the target vector
  2307. * @returns the unmodified current Vector2
  2308. */
  2309. Vector2.prototype.addToRef = function (otherVector, result) {
  2310. result.x = this.x + otherVector.x;
  2311. result.y = this.y + otherVector.y;
  2312. return this;
  2313. };
  2314. /**
  2315. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2316. * @param otherVector defines the other vector
  2317. * @returns the current updated Vector2
  2318. */
  2319. Vector2.prototype.addInPlace = function (otherVector) {
  2320. this.x += otherVector.x;
  2321. this.y += otherVector.y;
  2322. return this;
  2323. };
  2324. /**
  2325. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2326. * @param otherVector defines the other vector
  2327. * @returns a new Vector2
  2328. */
  2329. Vector2.prototype.addVector3 = function (otherVector) {
  2330. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2331. };
  2332. /**
  2333. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2334. * @param otherVector defines the other vector
  2335. * @returns a new Vector2
  2336. */
  2337. Vector2.prototype.subtract = function (otherVector) {
  2338. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2339. };
  2340. /**
  2341. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2342. * @param otherVector defines the other vector
  2343. * @param result defines the target vector
  2344. * @returns the unmodified current Vector2
  2345. */
  2346. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2347. result.x = this.x - otherVector.x;
  2348. result.y = this.y - otherVector.y;
  2349. return this;
  2350. };
  2351. /**
  2352. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2353. * @param otherVector defines the other vector
  2354. * @returns the current updated Vector2
  2355. */
  2356. Vector2.prototype.subtractInPlace = function (otherVector) {
  2357. this.x -= otherVector.x;
  2358. this.y -= otherVector.y;
  2359. return this;
  2360. };
  2361. /**
  2362. * Multiplies in place the current Vector2 coordinates by the given ones
  2363. * @param otherVector defines the other vector
  2364. * @returns the current updated Vector2
  2365. */
  2366. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2367. this.x *= otherVector.x;
  2368. this.y *= otherVector.y;
  2369. return this;
  2370. };
  2371. /**
  2372. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2373. * @param otherVector defines the other vector
  2374. * @returns a new Vector2
  2375. */
  2376. Vector2.prototype.multiply = function (otherVector) {
  2377. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2378. };
  2379. /**
  2380. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2381. * @param otherVector defines the other vector
  2382. * @param result defines the target vector
  2383. * @returns the unmodified current Vector2
  2384. */
  2385. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2386. result.x = this.x * otherVector.x;
  2387. result.y = this.y * otherVector.y;
  2388. return this;
  2389. };
  2390. /**
  2391. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2392. * @param x defines the first coordinate
  2393. * @param y defines the second coordinate
  2394. * @returns a new Vector2
  2395. */
  2396. Vector2.prototype.multiplyByFloats = function (x, y) {
  2397. return new Vector2(this.x * x, this.y * y);
  2398. };
  2399. /**
  2400. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2401. * @param otherVector defines the other vector
  2402. * @returns a new Vector2
  2403. */
  2404. Vector2.prototype.divide = function (otherVector) {
  2405. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2406. };
  2407. /**
  2408. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2409. * @param otherVector defines the other vector
  2410. * @param result defines the target vector
  2411. * @returns the unmodified current Vector2
  2412. */
  2413. Vector2.prototype.divideToRef = function (otherVector, result) {
  2414. result.x = this.x / otherVector.x;
  2415. result.y = this.y / otherVector.y;
  2416. return this;
  2417. };
  2418. /**
  2419. * Divides the current Vector2 coordinates by the given ones
  2420. * @param otherVector defines the other vector
  2421. * @returns the current updated Vector2
  2422. */
  2423. Vector2.prototype.divideInPlace = function (otherVector) {
  2424. return this.divideToRef(otherVector, this);
  2425. };
  2426. /**
  2427. * Gets a new Vector2 with current Vector2 negated coordinates
  2428. * @returns a new Vector2
  2429. */
  2430. Vector2.prototype.negate = function () {
  2431. return new Vector2(-this.x, -this.y);
  2432. };
  2433. /**
  2434. * Multiply the Vector2 coordinates by scale
  2435. * @param scale defines the scaling factor
  2436. * @returns the current updated Vector2
  2437. */
  2438. Vector2.prototype.scaleInPlace = function (scale) {
  2439. this.x *= scale;
  2440. this.y *= scale;
  2441. return this;
  2442. };
  2443. /**
  2444. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2445. * @param scale defines the scaling factor
  2446. * @returns a new Vector2
  2447. */
  2448. Vector2.prototype.scale = function (scale) {
  2449. var result = new Vector2(0, 0);
  2450. this.scaleToRef(scale, result);
  2451. return result;
  2452. };
  2453. /**
  2454. * Scale the current Vector2 values by a factor to a given Vector2
  2455. * @param scale defines the scale factor
  2456. * @param result defines the Vector2 object where to store the result
  2457. * @returns the unmodified current Vector2
  2458. */
  2459. Vector2.prototype.scaleToRef = function (scale, result) {
  2460. result.x = this.x * scale;
  2461. result.y = this.y * scale;
  2462. return this;
  2463. };
  2464. /**
  2465. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2466. * @param scale defines the scale factor
  2467. * @param result defines the Vector2 object where to store the result
  2468. * @returns the unmodified current Vector2
  2469. */
  2470. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2471. result.x += this.x * scale;
  2472. result.y += this.y * scale;
  2473. return this;
  2474. };
  2475. /**
  2476. * Gets a boolean if two vectors are equals
  2477. * @param otherVector defines the other vector
  2478. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2479. */
  2480. Vector2.prototype.equals = function (otherVector) {
  2481. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2482. };
  2483. /**
  2484. * Gets a boolean if two vectors are equals (using an epsilon value)
  2485. * @param otherVector defines the other vector
  2486. * @param epsilon defines the minimal distance to consider equality
  2487. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2488. */
  2489. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2490. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2491. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2492. };
  2493. /**
  2494. * Gets a new Vector2 from current Vector2 floored values
  2495. * @returns a new Vector2
  2496. */
  2497. Vector2.prototype.floor = function () {
  2498. return new Vector2(Math.floor(this.x), Math.floor(this.y));
  2499. };
  2500. /**
  2501. * Gets a new Vector2 from current Vector2 floored values
  2502. * @returns a new Vector2
  2503. */
  2504. Vector2.prototype.fract = function () {
  2505. return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
  2506. };
  2507. // Properties
  2508. /**
  2509. * Gets the length of the vector
  2510. * @returns the vector length (float)
  2511. */
  2512. Vector2.prototype.length = function () {
  2513. return Math.sqrt(this.x * this.x + this.y * this.y);
  2514. };
  2515. /**
  2516. * Gets the vector squared length
  2517. * @returns the vector squared length (float)
  2518. */
  2519. Vector2.prototype.lengthSquared = function () {
  2520. return (this.x * this.x + this.y * this.y);
  2521. };
  2522. // Methods
  2523. /**
  2524. * Normalize the vector
  2525. * @returns the current updated Vector2
  2526. */
  2527. Vector2.prototype.normalize = function () {
  2528. var len = this.length();
  2529. if (len === 0)
  2530. return this;
  2531. var num = 1.0 / len;
  2532. this.x *= num;
  2533. this.y *= num;
  2534. return this;
  2535. };
  2536. /**
  2537. * Gets a new Vector2 copied from the Vector2
  2538. * @returns a new Vector2
  2539. */
  2540. Vector2.prototype.clone = function () {
  2541. return new Vector2(this.x, this.y);
  2542. };
  2543. // Statics
  2544. /**
  2545. * Gets a new Vector2(0, 0)
  2546. * @returns a new Vector2
  2547. */
  2548. Vector2.Zero = function () {
  2549. return new Vector2(0, 0);
  2550. };
  2551. /**
  2552. * Gets a new Vector2(1, 1)
  2553. * @returns a new Vector2
  2554. */
  2555. Vector2.One = function () {
  2556. return new Vector2(1, 1);
  2557. };
  2558. /**
  2559. * Gets a new Vector2 set from the given index element of the given array
  2560. * @param array defines the data source
  2561. * @param offset defines the offset in the data source
  2562. * @returns a new Vector2
  2563. */
  2564. Vector2.FromArray = function (array, offset) {
  2565. if (offset === void 0) { offset = 0; }
  2566. return new Vector2(array[offset], array[offset + 1]);
  2567. };
  2568. /**
  2569. * Sets "result" from the given index element of the given array
  2570. * @param array defines the data source
  2571. * @param offset defines the offset in the data source
  2572. * @param result defines the target vector
  2573. */
  2574. Vector2.FromArrayToRef = function (array, offset, result) {
  2575. result.x = array[offset];
  2576. result.y = array[offset + 1];
  2577. };
  2578. /**
  2579. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2580. * @param value1 defines 1st point of control
  2581. * @param value2 defines 2nd point of control
  2582. * @param value3 defines 3rd point of control
  2583. * @param value4 defines 4th point of control
  2584. * @param amount defines the interpolation factor
  2585. * @returns a new Vector2
  2586. */
  2587. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2588. var squared = amount * amount;
  2589. var cubed = amount * squared;
  2590. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2591. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2592. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2593. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2594. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2595. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2596. return new Vector2(x, y);
  2597. };
  2598. /**
  2599. * 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".
  2600. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2601. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2602. * @param value defines the value to clamp
  2603. * @param min defines the lower limit
  2604. * @param max defines the upper limit
  2605. * @returns a new Vector2
  2606. */
  2607. Vector2.Clamp = function (value, min, max) {
  2608. var x = value.x;
  2609. x = (x > max.x) ? max.x : x;
  2610. x = (x < min.x) ? min.x : x;
  2611. var y = value.y;
  2612. y = (y > max.y) ? max.y : y;
  2613. y = (y < min.y) ? min.y : y;
  2614. return new Vector2(x, y);
  2615. };
  2616. /**
  2617. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2618. * @param value1 defines the 1st control point
  2619. * @param tangent1 defines the outgoing tangent
  2620. * @param value2 defines the 2nd control point
  2621. * @param tangent2 defines the incoming tangent
  2622. * @param amount defines the interpolation factor
  2623. * @returns a new Vector2
  2624. */
  2625. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2626. var squared = amount * amount;
  2627. var cubed = amount * squared;
  2628. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2629. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2630. var part3 = (cubed - (2.0 * squared)) + amount;
  2631. var part4 = cubed - squared;
  2632. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2633. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2634. return new Vector2(x, y);
  2635. };
  2636. /**
  2637. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2638. * @param start defines the start vector
  2639. * @param end defines the end vector
  2640. * @param amount defines the interpolation factor
  2641. * @returns a new Vector2
  2642. */
  2643. Vector2.Lerp = function (start, end, amount) {
  2644. var x = start.x + ((end.x - start.x) * amount);
  2645. var y = start.y + ((end.y - start.y) * amount);
  2646. return new Vector2(x, y);
  2647. };
  2648. /**
  2649. * Gets the dot product of the vector "left" and the vector "right"
  2650. * @param left defines first vector
  2651. * @param right defines second vector
  2652. * @returns the dot product (float)
  2653. */
  2654. Vector2.Dot = function (left, right) {
  2655. return left.x * right.x + left.y * right.y;
  2656. };
  2657. /**
  2658. * Returns a new Vector2 equal to the normalized given vector
  2659. * @param vector defines the vector to normalize
  2660. * @returns a new Vector2
  2661. */
  2662. Vector2.Normalize = function (vector) {
  2663. var newVector = vector.clone();
  2664. newVector.normalize();
  2665. return newVector;
  2666. };
  2667. /**
  2668. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2669. * @param left defines 1st vector
  2670. * @param right defines 2nd vector
  2671. * @returns a new Vector2
  2672. */
  2673. Vector2.Minimize = function (left, right) {
  2674. var x = (left.x < right.x) ? left.x : right.x;
  2675. var y = (left.y < right.y) ? left.y : right.y;
  2676. return new Vector2(x, y);
  2677. };
  2678. /**
  2679. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2680. * @param left defines 1st vector
  2681. * @param right defines 2nd vector
  2682. * @returns a new Vector2
  2683. */
  2684. Vector2.Maximize = function (left, right) {
  2685. var x = (left.x > right.x) ? left.x : right.x;
  2686. var y = (left.y > right.y) ? left.y : right.y;
  2687. return new Vector2(x, y);
  2688. };
  2689. /**
  2690. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2691. * @param vector defines the vector to transform
  2692. * @param transformation defines the matrix to apply
  2693. * @returns a new Vector2
  2694. */
  2695. Vector2.Transform = function (vector, transformation) {
  2696. var r = Vector2.Zero();
  2697. Vector2.TransformToRef(vector, transformation, r);
  2698. return r;
  2699. };
  2700. /**
  2701. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2702. * @param vector defines the vector to transform
  2703. * @param transformation defines the matrix to apply
  2704. * @param result defines the target vector
  2705. */
  2706. Vector2.TransformToRef = function (vector, transformation, result) {
  2707. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2708. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2709. result.x = x;
  2710. result.y = y;
  2711. };
  2712. /**
  2713. * Determines if a given vector is included in a triangle
  2714. * @param p defines the vector to test
  2715. * @param p0 defines 1st triangle point
  2716. * @param p1 defines 2nd triangle point
  2717. * @param p2 defines 3rd triangle point
  2718. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2719. */
  2720. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2721. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2722. var sign = a < 0 ? -1 : 1;
  2723. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2724. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2725. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2726. };
  2727. /**
  2728. * Gets the distance between the vectors "value1" and "value2"
  2729. * @param value1 defines first vector
  2730. * @param value2 defines second vector
  2731. * @returns the distance between vectors
  2732. */
  2733. Vector2.Distance = function (value1, value2) {
  2734. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2735. };
  2736. /**
  2737. * Returns the squared distance between the vectors "value1" and "value2"
  2738. * @param value1 defines first vector
  2739. * @param value2 defines second vector
  2740. * @returns the squared distance between vectors
  2741. */
  2742. Vector2.DistanceSquared = function (value1, value2) {
  2743. var x = value1.x - value2.x;
  2744. var y = value1.y - value2.y;
  2745. return (x * x) + (y * y);
  2746. };
  2747. /**
  2748. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2749. * @param value1 defines first vector
  2750. * @param value2 defines second vector
  2751. * @returns a new Vector2
  2752. */
  2753. Vector2.Center = function (value1, value2) {
  2754. var center = value1.add(value2);
  2755. center.scaleInPlace(0.5);
  2756. return center;
  2757. };
  2758. /**
  2759. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2760. * @param p defines the middle point
  2761. * @param segA defines one point of the segment
  2762. * @param segB defines the other point of the segment
  2763. * @returns the shortest distance
  2764. */
  2765. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2766. var l2 = Vector2.DistanceSquared(segA, segB);
  2767. if (l2 === 0.0) {
  2768. return Vector2.Distance(p, segA);
  2769. }
  2770. var v = segB.subtract(segA);
  2771. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2772. var proj = segA.add(v.multiplyByFloats(t, t));
  2773. return Vector2.Distance(p, proj);
  2774. };
  2775. return Vector2;
  2776. }());
  2777. BABYLON.Vector2 = Vector2;
  2778. /**
  2779. * Classed used to store (x,y,z) vector representation
  2780. * A Vector3 is the main object used in 3D geometry
  2781. * It can represent etiher the coordinates of a point the space, either a direction
  2782. * Reminder: Babylon.js uses a left handed forward facing system
  2783. */
  2784. var Vector3 = /** @class */ (function () {
  2785. /**
  2786. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2787. * @param x defines the first coordinates (on X axis)
  2788. * @param y defines the second coordinates (on Y axis)
  2789. * @param z defines the third coordinates (on Z axis)
  2790. */
  2791. function Vector3(
  2792. /**
  2793. * Defines the first coordinates (on X axis)
  2794. */
  2795. x,
  2796. /**
  2797. * Defines the second coordinates (on Y axis)
  2798. */
  2799. y,
  2800. /**
  2801. * Defines the third coordinates (on Z axis)
  2802. */
  2803. z) {
  2804. if (x === void 0) { x = 0; }
  2805. if (y === void 0) { y = 0; }
  2806. if (z === void 0) { z = 0; }
  2807. this.x = x;
  2808. this.y = y;
  2809. this.z = z;
  2810. }
  2811. /**
  2812. * Creates a string representation of the Vector3
  2813. * @returns a string with the Vector3 coordinates.
  2814. */
  2815. Vector3.prototype.toString = function () {
  2816. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2817. };
  2818. /**
  2819. * Gets the class name
  2820. * @returns the string "Vector3"
  2821. */
  2822. Vector3.prototype.getClassName = function () {
  2823. return "Vector3";
  2824. };
  2825. /**
  2826. * Creates the Vector3 hash code
  2827. * @returns a number which tends to be unique between Vector3 instances
  2828. */
  2829. Vector3.prototype.getHashCode = function () {
  2830. var hash = this.x || 0;
  2831. hash = (hash * 397) ^ (this.y || 0);
  2832. hash = (hash * 397) ^ (this.z || 0);
  2833. return hash;
  2834. };
  2835. // Operators
  2836. /**
  2837. * Creates an array containing three elements : the coordinates of the Vector3
  2838. * @returns a new array of numbers
  2839. */
  2840. Vector3.prototype.asArray = function () {
  2841. var result = [];
  2842. this.toArray(result, 0);
  2843. return result;
  2844. };
  2845. /**
  2846. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2847. * @param array defines the destination array
  2848. * @param index defines the offset in the destination array
  2849. * @returns the current Vector3
  2850. */
  2851. Vector3.prototype.toArray = function (array, index) {
  2852. if (index === void 0) { index = 0; }
  2853. array[index] = this.x;
  2854. array[index + 1] = this.y;
  2855. array[index + 2] = this.z;
  2856. return this;
  2857. };
  2858. /**
  2859. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2860. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2861. */
  2862. Vector3.prototype.toQuaternion = function () {
  2863. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2864. };
  2865. /**
  2866. * Adds the given vector to the current Vector3
  2867. * @param otherVector defines the second operand
  2868. * @returns the current updated Vector3
  2869. */
  2870. Vector3.prototype.addInPlace = function (otherVector) {
  2871. this.x += otherVector.x;
  2872. this.y += otherVector.y;
  2873. this.z += otherVector.z;
  2874. return this;
  2875. };
  2876. /**
  2877. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2878. * @param otherVector defines the second operand
  2879. * @returns the resulting Vector3
  2880. */
  2881. Vector3.prototype.add = function (otherVector) {
  2882. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2883. };
  2884. /**
  2885. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2886. * @param otherVector defines the second operand
  2887. * @param result defines the Vector3 object where to store the result
  2888. * @returns the current Vector3
  2889. */
  2890. Vector3.prototype.addToRef = function (otherVector, result) {
  2891. result.x = this.x + otherVector.x;
  2892. result.y = this.y + otherVector.y;
  2893. result.z = this.z + otherVector.z;
  2894. return this;
  2895. };
  2896. /**
  2897. * Subtract the given vector from the current Vector3
  2898. * @param otherVector defines the second operand
  2899. * @returns the current updated Vector3
  2900. */
  2901. Vector3.prototype.subtractInPlace = function (otherVector) {
  2902. this.x -= otherVector.x;
  2903. this.y -= otherVector.y;
  2904. this.z -= otherVector.z;
  2905. return this;
  2906. };
  2907. /**
  2908. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2909. * @param otherVector defines the second operand
  2910. * @returns the resulting Vector3
  2911. */
  2912. Vector3.prototype.subtract = function (otherVector) {
  2913. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2914. };
  2915. /**
  2916. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2917. * @param otherVector defines the second operand
  2918. * @param result defines the Vector3 object where to store the result
  2919. * @returns the current Vector3
  2920. */
  2921. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2922. result.x = this.x - otherVector.x;
  2923. result.y = this.y - otherVector.y;
  2924. result.z = this.z - otherVector.z;
  2925. return this;
  2926. };
  2927. /**
  2928. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2929. * @param x defines the x coordinate of the operand
  2930. * @param y defines the y coordinate of the operand
  2931. * @param z defines the z coordinate of the operand
  2932. * @returns the resulting Vector3
  2933. */
  2934. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2935. return new Vector3(this.x - x, this.y - y, this.z - z);
  2936. };
  2937. /**
  2938. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2939. * @param x defines the x coordinate of the operand
  2940. * @param y defines the y coordinate of the operand
  2941. * @param z defines the z coordinate of the operand
  2942. * @param result defines the Vector3 object where to store the result
  2943. * @returns the current Vector3
  2944. */
  2945. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2946. result.x = this.x - x;
  2947. result.y = this.y - y;
  2948. result.z = this.z - z;
  2949. return this;
  2950. };
  2951. /**
  2952. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2953. * @returns a new Vector3
  2954. */
  2955. Vector3.prototype.negate = function () {
  2956. return new Vector3(-this.x, -this.y, -this.z);
  2957. };
  2958. /**
  2959. * Multiplies the Vector3 coordinates by the float "scale"
  2960. * @param scale defines the multiplier factor
  2961. * @returns the current updated Vector3
  2962. */
  2963. Vector3.prototype.scaleInPlace = function (scale) {
  2964. this.x *= scale;
  2965. this.y *= scale;
  2966. this.z *= scale;
  2967. return this;
  2968. };
  2969. /**
  2970. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2971. * @param scale defines the multiplier factor
  2972. * @returns a new Vector3
  2973. */
  2974. Vector3.prototype.scale = function (scale) {
  2975. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2976. };
  2977. /**
  2978. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  2979. * @param scale defines the multiplier factor
  2980. * @param result defines the Vector3 object where to store the result
  2981. * @returns the current Vector3
  2982. */
  2983. Vector3.prototype.scaleToRef = function (scale, result) {
  2984. result.x = this.x * scale;
  2985. result.y = this.y * scale;
  2986. result.z = this.z * scale;
  2987. return this;
  2988. };
  2989. /**
  2990. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2991. * @param scale defines the scale factor
  2992. * @param result defines the Vector3 object where to store the result
  2993. * @returns the unmodified current Vector3
  2994. */
  2995. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2996. result.x += this.x * scale;
  2997. result.y += this.y * scale;
  2998. result.z += this.z * scale;
  2999. return this;
  3000. };
  3001. /**
  3002. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3003. * @param otherVector defines the second operand
  3004. * @returns true if both vectors are equals
  3005. */
  3006. Vector3.prototype.equals = function (otherVector) {
  3007. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3008. };
  3009. /**
  3010. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3011. * @param otherVector defines the second operand
  3012. * @param epsilon defines the minimal distance to define values as equals
  3013. * @returns true if both vectors are distant less than epsilon
  3014. */
  3015. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3016. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3017. 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);
  3018. };
  3019. /**
  3020. * Returns true if the current Vector3 coordinates equals the given floats
  3021. * @param x defines the x coordinate of the operand
  3022. * @param y defines the y coordinate of the operand
  3023. * @param z defines the z coordinate of the operand
  3024. * @returns true if both vectors are equals
  3025. */
  3026. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3027. return this.x === x && this.y === y && this.z === z;
  3028. };
  3029. /**
  3030. * Multiplies the current Vector3 coordinates by the given ones
  3031. * @param otherVector defines the second operand
  3032. * @returns the current updated Vector3
  3033. */
  3034. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3035. this.x *= otherVector.x;
  3036. this.y *= otherVector.y;
  3037. this.z *= otherVector.z;
  3038. return this;
  3039. };
  3040. /**
  3041. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3042. * @param otherVector defines the second operand
  3043. * @returns the new Vector3
  3044. */
  3045. Vector3.prototype.multiply = function (otherVector) {
  3046. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3047. };
  3048. /**
  3049. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3050. * @param otherVector defines the second operand
  3051. * @param result defines the Vector3 object where to store the result
  3052. * @returns the current Vector3
  3053. */
  3054. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3055. result.x = this.x * otherVector.x;
  3056. result.y = this.y * otherVector.y;
  3057. result.z = this.z * otherVector.z;
  3058. return this;
  3059. };
  3060. /**
  3061. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3062. * @param x defines the x coordinate of the operand
  3063. * @param y defines the y coordinate of the operand
  3064. * @param z defines the z coordinate of the operand
  3065. * @returns the new Vector3
  3066. */
  3067. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3068. return new Vector3(this.x * x, this.y * y, this.z * z);
  3069. };
  3070. /**
  3071. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3072. * @param otherVector defines the second operand
  3073. * @returns the new Vector3
  3074. */
  3075. Vector3.prototype.divide = function (otherVector) {
  3076. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3077. };
  3078. /**
  3079. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3080. * @param otherVector defines the second operand
  3081. * @param result defines the Vector3 object where to store the result
  3082. * @returns the current Vector3
  3083. */
  3084. Vector3.prototype.divideToRef = function (otherVector, result) {
  3085. result.x = this.x / otherVector.x;
  3086. result.y = this.y / otherVector.y;
  3087. result.z = this.z / otherVector.z;
  3088. return this;
  3089. };
  3090. /**
  3091. * Divides the current Vector3 coordinates by the given ones.
  3092. * @param otherVector defines the second operand
  3093. * @returns the current updated Vector3
  3094. */
  3095. Vector3.prototype.divideInPlace = function (otherVector) {
  3096. return this.divideToRef(otherVector, this);
  3097. };
  3098. /**
  3099. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3100. * @param other defines the second operand
  3101. * @returns the current updated Vector3
  3102. */
  3103. Vector3.prototype.minimizeInPlace = function (other) {
  3104. if (other.x < this.x)
  3105. this.x = other.x;
  3106. if (other.y < this.y)
  3107. this.y = other.y;
  3108. if (other.z < this.z)
  3109. this.z = other.z;
  3110. return this;
  3111. };
  3112. /**
  3113. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3114. * @param other defines the second operand
  3115. * @returns the current updated Vector3
  3116. */
  3117. Vector3.prototype.maximizeInPlace = function (other) {
  3118. if (other.x > this.x)
  3119. this.x = other.x;
  3120. if (other.y > this.y)
  3121. this.y = other.y;
  3122. if (other.z > this.z)
  3123. this.z = other.z;
  3124. return this;
  3125. };
  3126. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3127. /**
  3128. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3129. */
  3130. get: function () {
  3131. var absX = Math.abs(this.x);
  3132. var absY = Math.abs(this.y);
  3133. if (absX !== absY) {
  3134. return true;
  3135. }
  3136. var absZ = Math.abs(this.z);
  3137. if (absX !== absZ) {
  3138. return true;
  3139. }
  3140. if (absY !== absZ) {
  3141. return true;
  3142. }
  3143. return false;
  3144. },
  3145. enumerable: true,
  3146. configurable: true
  3147. });
  3148. /**
  3149. * Gets a new Vector3 from current Vector3 floored values
  3150. * @returns a new Vector3
  3151. */
  3152. Vector3.prototype.floor = function () {
  3153. return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
  3154. };
  3155. /**
  3156. * Gets a new Vector3 from current Vector3 floored values
  3157. * @returns a new Vector3
  3158. */
  3159. Vector3.prototype.fract = function () {
  3160. return new Vector3(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z));
  3161. };
  3162. // Properties
  3163. /**
  3164. * Gets the length of the Vector3
  3165. * @returns the length of the Vecto3
  3166. */
  3167. Vector3.prototype.length = function () {
  3168. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3169. };
  3170. /**
  3171. * Gets the squared length of the Vector3
  3172. * @returns squared length of the Vector3
  3173. */
  3174. Vector3.prototype.lengthSquared = function () {
  3175. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3176. };
  3177. /**
  3178. * Normalize the current Vector3.
  3179. * Please note that this is an in place operation.
  3180. * @returns the current updated Vector3
  3181. */
  3182. Vector3.prototype.normalize = function () {
  3183. var len = this.length();
  3184. if (len === 0 || len === 1.0)
  3185. return this;
  3186. var num = 1.0 / len;
  3187. this.x *= num;
  3188. this.y *= num;
  3189. this.z *= num;
  3190. return this;
  3191. };
  3192. /**
  3193. * Normalize the current Vector3 to a new vector
  3194. * @returns the new Vector3
  3195. */
  3196. Vector3.prototype.normalizeToNew = function () {
  3197. var normalized = new Vector3(0, 0, 0);
  3198. this.normalizeToRef(normalized);
  3199. return normalized;
  3200. };
  3201. /**
  3202. * Normalize the current Vector3 to the reference
  3203. * @param reference define the Vector3 to update
  3204. * @returns the updated Vector3
  3205. */
  3206. Vector3.prototype.normalizeToRef = function (reference) {
  3207. var len = this.length();
  3208. if (len === 0 || len === 1.0) {
  3209. reference.set(this.x, this.y, this.z);
  3210. return reference;
  3211. }
  3212. var scale = 1.0 / len;
  3213. this.scaleToRef(scale, reference);
  3214. return reference;
  3215. };
  3216. /**
  3217. * Creates a new Vector3 copied from the current Vector3
  3218. * @returns the new Vector3
  3219. */
  3220. Vector3.prototype.clone = function () {
  3221. return new Vector3(this.x, this.y, this.z);
  3222. };
  3223. /**
  3224. * Copies the given vector coordinates to the current Vector3 ones
  3225. * @param source defines the source Vector3
  3226. * @returns the current updated Vector3
  3227. */
  3228. Vector3.prototype.copyFrom = function (source) {
  3229. this.x = source.x;
  3230. this.y = source.y;
  3231. this.z = source.z;
  3232. return this;
  3233. };
  3234. /**
  3235. * Copies the given floats to the current Vector3 coordinates
  3236. * @param x defines the x coordinate of the operand
  3237. * @param y defines the y coordinate of the operand
  3238. * @param z defines the z coordinate of the operand
  3239. * @returns the current updated Vector3
  3240. */
  3241. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3242. this.x = x;
  3243. this.y = y;
  3244. this.z = z;
  3245. return this;
  3246. };
  3247. /**
  3248. * Copies the given floats to the current Vector3 coordinates
  3249. * @param x defines the x coordinate of the operand
  3250. * @param y defines the y coordinate of the operand
  3251. * @param z defines the z coordinate of the operand
  3252. * @returns the current updated Vector3
  3253. */
  3254. Vector3.prototype.set = function (x, y, z) {
  3255. return this.copyFromFloats(x, y, z);
  3256. };
  3257. // Statics
  3258. /**
  3259. * Get the clip factor between two vectors
  3260. * @param vector0 defines the first operand
  3261. * @param vector1 defines the second operand
  3262. * @param axis defines the axis to use
  3263. * @param size defines the size along the axis
  3264. * @returns the clip factor
  3265. */
  3266. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3267. var d0 = Vector3.Dot(vector0, axis) - size;
  3268. var d1 = Vector3.Dot(vector1, axis) - size;
  3269. var s = d0 / (d0 - d1);
  3270. return s;
  3271. };
  3272. /**
  3273. * Get angle between two vectors
  3274. * @param vector0 angle between vector0 and vector1
  3275. * @param vector1 angle between vector0 and vector1
  3276. * @param normal direction of the normal
  3277. * @return the angle between vector0 and vector1
  3278. */
  3279. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3280. var v0 = vector0.clone().normalize();
  3281. var v1 = vector1.clone().normalize();
  3282. var dot = Vector3.Dot(v0, v1);
  3283. var n = Vector3.Cross(v0, v1);
  3284. if (Vector3.Dot(n, normal) > 0) {
  3285. return Math.acos(dot);
  3286. }
  3287. return -Math.acos(dot);
  3288. };
  3289. /**
  3290. * Returns a new Vector3 set from the index "offset" of the given array
  3291. * @param array defines the source array
  3292. * @param offset defines the offset in the source array
  3293. * @returns the new Vector3
  3294. */
  3295. Vector3.FromArray = function (array, offset) {
  3296. if (!offset) {
  3297. offset = 0;
  3298. }
  3299. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3300. };
  3301. /**
  3302. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3303. * This function is deprecated. Use FromArray instead
  3304. * @param array defines the source array
  3305. * @param offset defines the offset in the source array
  3306. * @returns the new Vector3
  3307. */
  3308. Vector3.FromFloatArray = function (array, offset) {
  3309. return Vector3.FromArray(array, offset);
  3310. };
  3311. /**
  3312. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3313. * @param array defines the source array
  3314. * @param offset defines the offset in the source array
  3315. * @param result defines the Vector3 where to store the result
  3316. */
  3317. Vector3.FromArrayToRef = function (array, offset, result) {
  3318. result.x = array[offset];
  3319. result.y = array[offset + 1];
  3320. result.z = array[offset + 2];
  3321. };
  3322. /**
  3323. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3324. * This function is deprecated. Use FromArrayToRef instead.
  3325. * @param array defines the source array
  3326. * @param offset defines the offset in the source array
  3327. * @param result defines the Vector3 where to store the result
  3328. */
  3329. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3330. return Vector3.FromArrayToRef(array, offset, result);
  3331. };
  3332. /**
  3333. * Sets the given vector "result" with the given floats.
  3334. * @param x defines the x coordinate of the source
  3335. * @param y defines the y coordinate of the source
  3336. * @param z defines the z coordinate of the source
  3337. * @param result defines the Vector3 where to store the result
  3338. */
  3339. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3340. result.x = x;
  3341. result.y = y;
  3342. result.z = z;
  3343. };
  3344. /**
  3345. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3346. * @returns a new empty Vector3
  3347. */
  3348. Vector3.Zero = function () {
  3349. return new Vector3(0.0, 0.0, 0.0);
  3350. };
  3351. /**
  3352. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3353. * @returns a new unit Vector3
  3354. */
  3355. Vector3.One = function () {
  3356. return new Vector3(1.0, 1.0, 1.0);
  3357. };
  3358. /**
  3359. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3360. * @returns a new up Vector3
  3361. */
  3362. Vector3.Up = function () {
  3363. return new Vector3(0.0, 1.0, 0.0);
  3364. };
  3365. /**
  3366. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3367. * @returns a new down Vector3
  3368. */
  3369. Vector3.Down = function () {
  3370. return new Vector3(0.0, -1.0, 0.0);
  3371. };
  3372. /**
  3373. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3374. * @returns a new forward Vector3
  3375. */
  3376. Vector3.Forward = function () {
  3377. return new Vector3(0.0, 0.0, 1.0);
  3378. };
  3379. /**
  3380. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3381. * @returns a new right Vector3
  3382. */
  3383. Vector3.Right = function () {
  3384. return new Vector3(1.0, 0.0, 0.0);
  3385. };
  3386. /**
  3387. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3388. * @returns a new left Vector3
  3389. */
  3390. Vector3.Left = function () {
  3391. return new Vector3(-1.0, 0.0, 0.0);
  3392. };
  3393. /**
  3394. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3395. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3396. * @param vector defines the Vector3 to transform
  3397. * @param transformation defines the transformation matrix
  3398. * @returns the transformed Vector3
  3399. */
  3400. Vector3.TransformCoordinates = function (vector, transformation) {
  3401. var result = Vector3.Zero();
  3402. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3403. return result;
  3404. };
  3405. /**
  3406. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3407. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3408. * @param vector defines the Vector3 to transform
  3409. * @param transformation defines the transformation matrix
  3410. * @param result defines the Vector3 where to store the result
  3411. */
  3412. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3413. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3414. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3415. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3416. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3417. result.x = x / w;
  3418. result.y = y / w;
  3419. result.z = z / w;
  3420. };
  3421. /**
  3422. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3423. * This method computes tranformed coordinates only, not transformed direction vectors
  3424. * @param x define the x coordinate of the source vector
  3425. * @param y define the y coordinate of the source vector
  3426. * @param z define the z coordinate of the source vector
  3427. * @param transformation defines the transformation matrix
  3428. * @param result defines the Vector3 where to store the result
  3429. */
  3430. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3431. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3432. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3433. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3434. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3435. result.x = rx / rw;
  3436. result.y = ry / rw;
  3437. result.z = rz / rw;
  3438. };
  3439. /**
  3440. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3441. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3442. * @param vector defines the Vector3 to transform
  3443. * @param transformation defines the transformation matrix
  3444. * @returns the new Vector3
  3445. */
  3446. Vector3.TransformNormal = function (vector, transformation) {
  3447. var result = Vector3.Zero();
  3448. Vector3.TransformNormalToRef(vector, transformation, result);
  3449. return result;
  3450. };
  3451. /**
  3452. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3453. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3454. * @param vector defines the Vector3 to transform
  3455. * @param transformation defines the transformation matrix
  3456. * @param result defines the Vector3 where to store the result
  3457. */
  3458. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3459. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3460. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3461. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3462. result.x = x;
  3463. result.y = y;
  3464. result.z = z;
  3465. };
  3466. /**
  3467. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3468. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3469. * @param x define the x coordinate of the source vector
  3470. * @param y define the y coordinate of the source vector
  3471. * @param z define the z coordinate of the source vector
  3472. * @param transformation defines the transformation matrix
  3473. * @param result defines the Vector3 where to store the result
  3474. */
  3475. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3476. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3477. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3478. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3479. };
  3480. /**
  3481. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3482. * @param value1 defines the first control point
  3483. * @param value2 defines the second control point
  3484. * @param value3 defines the third control point
  3485. * @param value4 defines the fourth control point
  3486. * @param amount defines the amount on the spline to use
  3487. * @returns the new Vector3
  3488. */
  3489. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3490. var squared = amount * amount;
  3491. var cubed = amount * squared;
  3492. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3493. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3494. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3495. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3496. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3497. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3498. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3499. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3500. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3501. return new Vector3(x, y, z);
  3502. };
  3503. /**
  3504. * 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"
  3505. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3506. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3507. * @param value defines the current value
  3508. * @param min defines the lower range value
  3509. * @param max defines the upper range value
  3510. * @returns the new Vector3
  3511. */
  3512. Vector3.Clamp = function (value, min, max) {
  3513. var x = value.x;
  3514. x = (x > max.x) ? max.x : x;
  3515. x = (x < min.x) ? min.x : x;
  3516. var y = value.y;
  3517. y = (y > max.y) ? max.y : y;
  3518. y = (y < min.y) ? min.y : y;
  3519. var z = value.z;
  3520. z = (z > max.z) ? max.z : z;
  3521. z = (z < min.z) ? min.z : z;
  3522. return new Vector3(x, y, z);
  3523. };
  3524. /**
  3525. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3526. * @param value1 defines the first control point
  3527. * @param tangent1 defines the first tangent vector
  3528. * @param value2 defines the second control point
  3529. * @param tangent2 defines the second tangent vector
  3530. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3531. * @returns the new Vector3
  3532. */
  3533. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3534. var squared = amount * amount;
  3535. var cubed = amount * squared;
  3536. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3537. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3538. var part3 = (cubed - (2.0 * squared)) + amount;
  3539. var part4 = cubed - squared;
  3540. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3541. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3542. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3543. return new Vector3(x, y, z);
  3544. };
  3545. /**
  3546. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3547. * @param start defines the start value
  3548. * @param end defines the end value
  3549. * @param amount max defines amount between both (between 0 and 1)
  3550. * @returns the new Vector3
  3551. */
  3552. Vector3.Lerp = function (start, end, amount) {
  3553. var result = new Vector3(0, 0, 0);
  3554. Vector3.LerpToRef(start, end, amount, result);
  3555. return result;
  3556. };
  3557. /**
  3558. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3559. * @param start defines the start value
  3560. * @param end defines the end value
  3561. * @param amount max defines amount between both (between 0 and 1)
  3562. * @param result defines the Vector3 where to store the result
  3563. */
  3564. Vector3.LerpToRef = function (start, end, amount, result) {
  3565. result.x = start.x + ((end.x - start.x) * amount);
  3566. result.y = start.y + ((end.y - start.y) * amount);
  3567. result.z = start.z + ((end.z - start.z) * amount);
  3568. };
  3569. /**
  3570. * Returns the dot product (float) between the vectors "left" and "right"
  3571. * @param left defines the left operand
  3572. * @param right defines the right operand
  3573. * @returns the dot product
  3574. */
  3575. Vector3.Dot = function (left, right) {
  3576. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3577. };
  3578. /**
  3579. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3580. * The cross product is then orthogonal to both "left" and "right"
  3581. * @param left defines the left operand
  3582. * @param right defines the right operand
  3583. * @returns the cross product
  3584. */
  3585. Vector3.Cross = function (left, right) {
  3586. var result = Vector3.Zero();
  3587. Vector3.CrossToRef(left, right, result);
  3588. return result;
  3589. };
  3590. /**
  3591. * Sets the given vector "result" with the cross product of "left" and "right"
  3592. * The cross product is then orthogonal to both "left" and "right"
  3593. * @param left defines the left operand
  3594. * @param right defines the right operand
  3595. * @param result defines the Vector3 where to store the result
  3596. */
  3597. Vector3.CrossToRef = function (left, right, result) {
  3598. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3599. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3600. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3601. result.copyFrom(MathTmp.Vector3[0]);
  3602. };
  3603. /**
  3604. * Returns a new Vector3 as the normalization of the given vector
  3605. * @param vector defines the Vector3 to normalize
  3606. * @returns the new Vector3
  3607. */
  3608. Vector3.Normalize = function (vector) {
  3609. var result = Vector3.Zero();
  3610. Vector3.NormalizeToRef(vector, result);
  3611. return result;
  3612. };
  3613. /**
  3614. * Sets the given vector "result" with the normalization of the given first vector
  3615. * @param vector defines the Vector3 to normalize
  3616. * @param result defines the Vector3 where to store the result
  3617. */
  3618. Vector3.NormalizeToRef = function (vector, result) {
  3619. result.copyFrom(vector);
  3620. result.normalize();
  3621. };
  3622. /**
  3623. * Project a Vector3 onto screen space
  3624. * @param vector defines the Vector3 to project
  3625. * @param world defines the world matrix to use
  3626. * @param transform defines the transform (view x projection) matrix to use
  3627. * @param viewport defines the screen viewport to use
  3628. * @returns the new Vector3
  3629. */
  3630. Vector3.Project = function (vector, world, transform, viewport) {
  3631. var cw = viewport.width;
  3632. var ch = viewport.height;
  3633. var cx = viewport.x;
  3634. var cy = viewport.y;
  3635. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3636. 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);
  3637. var matrix = MathTmp.Matrix[0];
  3638. world.multiplyToRef(transform, matrix);
  3639. matrix.multiplyToRef(viewportMatrix, matrix);
  3640. return Vector3.TransformCoordinates(vector, matrix);
  3641. };
  3642. /**
  3643. * Unproject from screen space to object space
  3644. * @param source defines the screen space Vector3 to use
  3645. * @param viewportWidth defines the current width of the viewport
  3646. * @param viewportHeight defines the current height of the viewport
  3647. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3648. * @param transform defines the transform (view x projection) matrix to use
  3649. * @returns the new Vector3
  3650. */
  3651. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3652. var matrix = MathTmp.Matrix[0];
  3653. world.multiplyToRef(transform, matrix);
  3654. matrix.invert();
  3655. source.x = source.x / viewportWidth * 2 - 1;
  3656. source.y = -(source.y / viewportHeight * 2 - 1);
  3657. var vector = Vector3.TransformCoordinates(source, matrix);
  3658. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3659. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3660. vector = vector.scale(1.0 / num);
  3661. }
  3662. return vector;
  3663. };
  3664. /**
  3665. * Unproject from screen space to object space
  3666. * @param source defines the screen space Vector3 to use
  3667. * @param viewportWidth defines the current width of the viewport
  3668. * @param viewportHeight defines the current height of the viewport
  3669. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3670. * @param view defines the view matrix to use
  3671. * @param projection defines the projection matrix to use
  3672. * @returns the new Vector3
  3673. */
  3674. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3675. var result = Vector3.Zero();
  3676. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3677. return result;
  3678. };
  3679. /**
  3680. * Unproject from screen space to object space
  3681. * @param source defines the screen space Vector3 to use
  3682. * @param viewportWidth defines the current width of the viewport
  3683. * @param viewportHeight defines the current height of the viewport
  3684. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3685. * @param view defines the view matrix to use
  3686. * @param projection defines the projection matrix to use
  3687. * @param result defines the Vector3 where to store the result
  3688. */
  3689. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3690. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3691. };
  3692. /**
  3693. * Unproject from screen space to object space
  3694. * @param sourceX defines the screen space x coordinate to use
  3695. * @param sourceY defines the screen space y coordinate to use
  3696. * @param sourceZ defines the screen space z coordinate to use
  3697. * @param viewportWidth defines the current width of the viewport
  3698. * @param viewportHeight defines the current height of the viewport
  3699. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3700. * @param view defines the view matrix to use
  3701. * @param projection defines the projection matrix to use
  3702. * @param result defines the Vector3 where to store the result
  3703. */
  3704. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3705. var matrix = MathTmp.Matrix[0];
  3706. world.multiplyToRef(view, matrix);
  3707. matrix.multiplyToRef(projection, matrix);
  3708. matrix.invert();
  3709. var screenSource = MathTmp.Vector3[0];
  3710. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3711. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3712. screenSource.z = 2 * sourceZ - 1.0;
  3713. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3714. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3715. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3716. result.scaleInPlace(1.0 / num);
  3717. }
  3718. };
  3719. /**
  3720. * Gets the minimal coordinate values between two Vector3
  3721. * @param left defines the first operand
  3722. * @param right defines the second operand
  3723. * @returns the new Vector3
  3724. */
  3725. Vector3.Minimize = function (left, right) {
  3726. var min = left.clone();
  3727. min.minimizeInPlace(right);
  3728. return min;
  3729. };
  3730. /**
  3731. * Gets the maximal coordinate values between two Vector3
  3732. * @param left defines the first operand
  3733. * @param right defines the second operand
  3734. * @returns the new Vector3
  3735. */
  3736. Vector3.Maximize = function (left, right) {
  3737. var max = left.clone();
  3738. max.maximizeInPlace(right);
  3739. return max;
  3740. };
  3741. /**
  3742. * Returns the distance between the vectors "value1" and "value2"
  3743. * @param value1 defines the first operand
  3744. * @param value2 defines the second operand
  3745. * @returns the distance
  3746. */
  3747. Vector3.Distance = function (value1, value2) {
  3748. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3749. };
  3750. /**
  3751. * Returns the squared distance between the vectors "value1" and "value2"
  3752. * @param value1 defines the first operand
  3753. * @param value2 defines the second operand
  3754. * @returns the squared distance
  3755. */
  3756. Vector3.DistanceSquared = function (value1, value2) {
  3757. var x = value1.x - value2.x;
  3758. var y = value1.y - value2.y;
  3759. var z = value1.z - value2.z;
  3760. return (x * x) + (y * y) + (z * z);
  3761. };
  3762. /**
  3763. * Returns a new Vector3 located at the center between "value1" and "value2"
  3764. * @param value1 defines the first operand
  3765. * @param value2 defines the second operand
  3766. * @returns the new Vector3
  3767. */
  3768. Vector3.Center = function (value1, value2) {
  3769. var center = value1.add(value2);
  3770. center.scaleInPlace(0.5);
  3771. return center;
  3772. };
  3773. /**
  3774. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3775. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3776. * to something in order to rotate it from its local system to the given target system
  3777. * Note: axis1, axis2 and axis3 are normalized during this operation
  3778. * @param axis1 defines the first axis
  3779. * @param axis2 defines the second axis
  3780. * @param axis3 defines the third axis
  3781. * @returns a new Vector3
  3782. */
  3783. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3784. var rotation = Vector3.Zero();
  3785. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3786. return rotation;
  3787. };
  3788. /**
  3789. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3790. * @param axis1 defines the first axis
  3791. * @param axis2 defines the second axis
  3792. * @param axis3 defines the third axis
  3793. * @param ref defines the Vector3 where to store the result
  3794. */
  3795. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3796. var quat = MathTmp.Quaternion[0];
  3797. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3798. quat.toEulerAnglesToRef(ref);
  3799. };
  3800. return Vector3;
  3801. }());
  3802. BABYLON.Vector3 = Vector3;
  3803. //Vector4 class created for EulerAngle class conversion to Quaternion
  3804. var Vector4 = /** @class */ (function () {
  3805. /**
  3806. * Creates a Vector4 object from the given floats.
  3807. */
  3808. function Vector4(x, y, z, w) {
  3809. this.x = x;
  3810. this.y = y;
  3811. this.z = z;
  3812. this.w = w;
  3813. }
  3814. /**
  3815. * Returns the string with the Vector4 coordinates.
  3816. */
  3817. Vector4.prototype.toString = function () {
  3818. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3819. };
  3820. /**
  3821. * Returns the string "Vector4".
  3822. */
  3823. Vector4.prototype.getClassName = function () {
  3824. return "Vector4";
  3825. };
  3826. /**
  3827. * Returns the Vector4 hash code.
  3828. */
  3829. Vector4.prototype.getHashCode = function () {
  3830. var hash = this.x || 0;
  3831. hash = (hash * 397) ^ (this.y || 0);
  3832. hash = (hash * 397) ^ (this.z || 0);
  3833. hash = (hash * 397) ^ (this.w || 0);
  3834. return hash;
  3835. };
  3836. // Operators
  3837. /**
  3838. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3839. */
  3840. Vector4.prototype.asArray = function () {
  3841. var result = new Array();
  3842. this.toArray(result, 0);
  3843. return result;
  3844. };
  3845. /**
  3846. * Populates the given array from the given index with the Vector4 coordinates.
  3847. * Returns the Vector4.
  3848. */
  3849. Vector4.prototype.toArray = function (array, index) {
  3850. if (index === undefined) {
  3851. index = 0;
  3852. }
  3853. array[index] = this.x;
  3854. array[index + 1] = this.y;
  3855. array[index + 2] = this.z;
  3856. array[index + 3] = this.w;
  3857. return this;
  3858. };
  3859. /**
  3860. * Adds the given vector to the current Vector4.
  3861. * Returns the updated Vector4.
  3862. */
  3863. Vector4.prototype.addInPlace = function (otherVector) {
  3864. this.x += otherVector.x;
  3865. this.y += otherVector.y;
  3866. this.z += otherVector.z;
  3867. this.w += otherVector.w;
  3868. return this;
  3869. };
  3870. /**
  3871. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3872. */
  3873. Vector4.prototype.add = function (otherVector) {
  3874. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3875. };
  3876. /**
  3877. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3878. * Returns the current Vector4.
  3879. */
  3880. Vector4.prototype.addToRef = function (otherVector, result) {
  3881. result.x = this.x + otherVector.x;
  3882. result.y = this.y + otherVector.y;
  3883. result.z = this.z + otherVector.z;
  3884. result.w = this.w + otherVector.w;
  3885. return this;
  3886. };
  3887. /**
  3888. * Subtract in place the given vector from the current Vector4.
  3889. * Returns the updated Vector4.
  3890. */
  3891. Vector4.prototype.subtractInPlace = function (otherVector) {
  3892. this.x -= otherVector.x;
  3893. this.y -= otherVector.y;
  3894. this.z -= otherVector.z;
  3895. this.w -= otherVector.w;
  3896. return this;
  3897. };
  3898. /**
  3899. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3900. */
  3901. Vector4.prototype.subtract = function (otherVector) {
  3902. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3903. };
  3904. /**
  3905. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3906. * Returns the current Vector4.
  3907. */
  3908. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3909. result.x = this.x - otherVector.x;
  3910. result.y = this.y - otherVector.y;
  3911. result.z = this.z - otherVector.z;
  3912. result.w = this.w - otherVector.w;
  3913. return this;
  3914. };
  3915. /**
  3916. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3917. */
  3918. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3919. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3920. };
  3921. /**
  3922. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3923. * Returns the current Vector4.
  3924. */
  3925. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3926. result.x = this.x - x;
  3927. result.y = this.y - y;
  3928. result.z = this.z - z;
  3929. result.w = this.w - w;
  3930. return this;
  3931. };
  3932. /**
  3933. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3934. */
  3935. Vector4.prototype.negate = function () {
  3936. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3937. };
  3938. /**
  3939. * Multiplies the current Vector4 coordinates by scale (float).
  3940. * Returns the updated Vector4.
  3941. */
  3942. Vector4.prototype.scaleInPlace = function (scale) {
  3943. this.x *= scale;
  3944. this.y *= scale;
  3945. this.z *= scale;
  3946. this.w *= scale;
  3947. return this;
  3948. };
  3949. /**
  3950. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3951. */
  3952. Vector4.prototype.scale = function (scale) {
  3953. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3954. };
  3955. /**
  3956. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3957. * Returns the current Vector4.
  3958. */
  3959. Vector4.prototype.scaleToRef = function (scale, result) {
  3960. result.x = this.x * scale;
  3961. result.y = this.y * scale;
  3962. result.z = this.z * scale;
  3963. result.w = this.w * scale;
  3964. return this;
  3965. };
  3966. /**
  3967. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3968. * @param scale defines the scale factor
  3969. * @param result defines the Vector4 object where to store the result
  3970. * @returns the unmodified current Vector4
  3971. */
  3972. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3973. result.x += this.x * scale;
  3974. result.y += this.y * scale;
  3975. result.z += this.z * scale;
  3976. result.w += this.w * scale;
  3977. return this;
  3978. };
  3979. /**
  3980. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3981. */
  3982. Vector4.prototype.equals = function (otherVector) {
  3983. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3984. };
  3985. /**
  3986. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  3987. */
  3988. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3989. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3990. return otherVector
  3991. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3992. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3993. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3994. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3995. };
  3996. /**
  3997. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  3998. */
  3999. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4000. return this.x === x && this.y === y && this.z === z && this.w === w;
  4001. };
  4002. /**
  4003. * Multiplies in place the current Vector4 by the given one.
  4004. * Returns the updated Vector4.
  4005. */
  4006. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4007. this.x *= otherVector.x;
  4008. this.y *= otherVector.y;
  4009. this.z *= otherVector.z;
  4010. this.w *= otherVector.w;
  4011. return this;
  4012. };
  4013. /**
  4014. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4015. */
  4016. Vector4.prototype.multiply = function (otherVector) {
  4017. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4018. };
  4019. /**
  4020. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4021. * Returns the current Vector4.
  4022. */
  4023. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4024. result.x = this.x * otherVector.x;
  4025. result.y = this.y * otherVector.y;
  4026. result.z = this.z * otherVector.z;
  4027. result.w = this.w * otherVector.w;
  4028. return this;
  4029. };
  4030. /**
  4031. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4032. */
  4033. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4034. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4035. };
  4036. /**
  4037. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4038. */
  4039. Vector4.prototype.divide = function (otherVector) {
  4040. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4041. };
  4042. /**
  4043. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4044. * Returns the current Vector4.
  4045. */
  4046. Vector4.prototype.divideToRef = function (otherVector, result) {
  4047. result.x = this.x / otherVector.x;
  4048. result.y = this.y / otherVector.y;
  4049. result.z = this.z / otherVector.z;
  4050. result.w = this.w / otherVector.w;
  4051. return this;
  4052. };
  4053. /**
  4054. * Divides the current Vector3 coordinates by the given ones.
  4055. * @returns the updated Vector3.
  4056. */
  4057. Vector4.prototype.divideInPlace = function (otherVector) {
  4058. return this.divideToRef(otherVector, this);
  4059. };
  4060. /**
  4061. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4062. * @param other defines the second operand
  4063. * @returns the current updated Vector4
  4064. */
  4065. Vector4.prototype.minimizeInPlace = function (other) {
  4066. if (other.x < this.x)
  4067. this.x = other.x;
  4068. if (other.y < this.y)
  4069. this.y = other.y;
  4070. if (other.z < this.z)
  4071. this.z = other.z;
  4072. if (other.w < this.w)
  4073. this.w = other.w;
  4074. return this;
  4075. };
  4076. /**
  4077. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4078. * @param other defines the second operand
  4079. * @returns the current updated Vector4
  4080. */
  4081. Vector4.prototype.maximizeInPlace = function (other) {
  4082. if (other.x > this.x)
  4083. this.x = other.x;
  4084. if (other.y > this.y)
  4085. this.y = other.y;
  4086. if (other.z > this.z)
  4087. this.z = other.z;
  4088. if (other.w > this.w)
  4089. this.w = other.w;
  4090. return this;
  4091. };
  4092. /**
  4093. * Gets a new Vector4 from current Vector4 floored values
  4094. * @returns a new Vector4
  4095. */
  4096. Vector4.prototype.floor = function () {
  4097. return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
  4098. };
  4099. /**
  4100. * Gets a new Vector4 from current Vector3 floored values
  4101. * @returns a new Vector4
  4102. */
  4103. Vector4.prototype.fract = function () {
  4104. return new Vector4(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z), this.w - Math.floor(this.w));
  4105. };
  4106. // Properties
  4107. /**
  4108. * Returns the Vector4 length (float).
  4109. */
  4110. Vector4.prototype.length = function () {
  4111. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4112. };
  4113. /**
  4114. * Returns the Vector4 squared length (float).
  4115. */
  4116. Vector4.prototype.lengthSquared = function () {
  4117. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4118. };
  4119. // Methods
  4120. /**
  4121. * Normalizes in place the Vector4.
  4122. * Returns the updated Vector4.
  4123. */
  4124. Vector4.prototype.normalize = function () {
  4125. var len = this.length();
  4126. if (len === 0)
  4127. return this;
  4128. var num = 1.0 / len;
  4129. this.x *= num;
  4130. this.y *= num;
  4131. this.z *= num;
  4132. this.w *= num;
  4133. return this;
  4134. };
  4135. /**
  4136. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4137. */
  4138. Vector4.prototype.toVector3 = function () {
  4139. return new Vector3(this.x, this.y, this.z);
  4140. };
  4141. /**
  4142. * Returns a new Vector4 copied from the current one.
  4143. */
  4144. Vector4.prototype.clone = function () {
  4145. return new Vector4(this.x, this.y, this.z, this.w);
  4146. };
  4147. /**
  4148. * Updates the current Vector4 with the given one coordinates.
  4149. * Returns the updated Vector4.
  4150. */
  4151. Vector4.prototype.copyFrom = function (source) {
  4152. this.x = source.x;
  4153. this.y = source.y;
  4154. this.z = source.z;
  4155. this.w = source.w;
  4156. return this;
  4157. };
  4158. /**
  4159. * Updates the current Vector4 coordinates with the given floats.
  4160. * Returns the updated Vector4.
  4161. */
  4162. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4163. this.x = x;
  4164. this.y = y;
  4165. this.z = z;
  4166. this.w = w;
  4167. return this;
  4168. };
  4169. /**
  4170. * Updates the current Vector4 coordinates with the given floats.
  4171. * Returns the updated Vector4.
  4172. */
  4173. Vector4.prototype.set = function (x, y, z, w) {
  4174. return this.copyFromFloats(x, y, z, w);
  4175. };
  4176. // Statics
  4177. /**
  4178. * Returns a new Vector4 set from the starting index of the given array.
  4179. */
  4180. Vector4.FromArray = function (array, offset) {
  4181. if (!offset) {
  4182. offset = 0;
  4183. }
  4184. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4185. };
  4186. /**
  4187. * Updates the given vector "result" from the starting index of the given array.
  4188. */
  4189. Vector4.FromArrayToRef = function (array, offset, result) {
  4190. result.x = array[offset];
  4191. result.y = array[offset + 1];
  4192. result.z = array[offset + 2];
  4193. result.w = array[offset + 3];
  4194. };
  4195. /**
  4196. * Updates the given vector "result" from the starting index of the given Float32Array.
  4197. */
  4198. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4199. Vector4.FromArrayToRef(array, offset, result);
  4200. };
  4201. /**
  4202. * Updates the given vector "result" coordinates from the given floats.
  4203. */
  4204. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4205. result.x = x;
  4206. result.y = y;
  4207. result.z = z;
  4208. result.w = w;
  4209. };
  4210. /**
  4211. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4212. */
  4213. Vector4.Zero = function () {
  4214. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4215. };
  4216. /**
  4217. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4218. */
  4219. Vector4.One = function () {
  4220. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4221. };
  4222. /**
  4223. * Returns a new normalized Vector4 from the given one.
  4224. */
  4225. Vector4.Normalize = function (vector) {
  4226. var result = Vector4.Zero();
  4227. Vector4.NormalizeToRef(vector, result);
  4228. return result;
  4229. };
  4230. /**
  4231. * Updates the given vector "result" from the normalization of the given one.
  4232. */
  4233. Vector4.NormalizeToRef = function (vector, result) {
  4234. result.copyFrom(vector);
  4235. result.normalize();
  4236. };
  4237. Vector4.Minimize = function (left, right) {
  4238. var min = left.clone();
  4239. min.minimizeInPlace(right);
  4240. return min;
  4241. };
  4242. Vector4.Maximize = function (left, right) {
  4243. var max = left.clone();
  4244. max.maximizeInPlace(right);
  4245. return max;
  4246. };
  4247. /**
  4248. * Returns the distance (float) between the vectors "value1" and "value2".
  4249. */
  4250. Vector4.Distance = function (value1, value2) {
  4251. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4252. };
  4253. /**
  4254. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4255. */
  4256. Vector4.DistanceSquared = function (value1, value2) {
  4257. var x = value1.x - value2.x;
  4258. var y = value1.y - value2.y;
  4259. var z = value1.z - value2.z;
  4260. var w = value1.w - value2.w;
  4261. return (x * x) + (y * y) + (z * z) + (w * w);
  4262. };
  4263. /**
  4264. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4265. */
  4266. Vector4.Center = function (value1, value2) {
  4267. var center = value1.add(value2);
  4268. center.scaleInPlace(0.5);
  4269. return center;
  4270. };
  4271. /**
  4272. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4273. * This methods computes transformed normalized direction vectors only.
  4274. */
  4275. Vector4.TransformNormal = function (vector, transformation) {
  4276. var result = Vector4.Zero();
  4277. Vector4.TransformNormalToRef(vector, transformation, result);
  4278. return result;
  4279. };
  4280. /**
  4281. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4282. * This methods computes transformed normalized direction vectors only.
  4283. */
  4284. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4285. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4286. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4287. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4288. result.x = x;
  4289. result.y = y;
  4290. result.z = z;
  4291. result.w = vector.w;
  4292. };
  4293. /**
  4294. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4295. * This methods computes transformed normalized direction vectors only.
  4296. */
  4297. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4298. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4299. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4300. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4301. result.w = w;
  4302. };
  4303. return Vector4;
  4304. }());
  4305. BABYLON.Vector4 = Vector4;
  4306. var Size = /** @class */ (function () {
  4307. /**
  4308. * Creates a Size object from the given width and height (floats).
  4309. */
  4310. function Size(width, height) {
  4311. this.width = width;
  4312. this.height = height;
  4313. }
  4314. // Returns a string with the Size width and height.
  4315. Size.prototype.toString = function () {
  4316. return "{W: " + this.width + ", H: " + this.height + "}";
  4317. };
  4318. /**
  4319. * Returns the string "Size"
  4320. */
  4321. Size.prototype.getClassName = function () {
  4322. return "Size";
  4323. };
  4324. /**
  4325. * Returns the Size hash code.
  4326. */
  4327. Size.prototype.getHashCode = function () {
  4328. var hash = this.width || 0;
  4329. hash = (hash * 397) ^ (this.height || 0);
  4330. return hash;
  4331. };
  4332. /**
  4333. * Updates the current size from the given one.
  4334. * Returns the updated Size.
  4335. */
  4336. Size.prototype.copyFrom = function (src) {
  4337. this.width = src.width;
  4338. this.height = src.height;
  4339. };
  4340. /**
  4341. * Updates in place the current Size from the given floats.
  4342. * Returns the updated Size.
  4343. */
  4344. Size.prototype.copyFromFloats = function (width, height) {
  4345. this.width = width;
  4346. this.height = height;
  4347. return this;
  4348. };
  4349. /**
  4350. * Updates in place the current Size from the given floats.
  4351. * Returns the updated Size.
  4352. */
  4353. Size.prototype.set = function (width, height) {
  4354. return this.copyFromFloats(width, height);
  4355. };
  4356. /**
  4357. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4358. */
  4359. Size.prototype.multiplyByFloats = function (w, h) {
  4360. return new Size(this.width * w, this.height * h);
  4361. };
  4362. /**
  4363. * Returns a new Size copied from the given one.
  4364. */
  4365. Size.prototype.clone = function () {
  4366. return new Size(this.width, this.height);
  4367. };
  4368. /**
  4369. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4370. */
  4371. Size.prototype.equals = function (other) {
  4372. if (!other) {
  4373. return false;
  4374. }
  4375. return (this.width === other.width) && (this.height === other.height);
  4376. };
  4377. Object.defineProperty(Size.prototype, "surface", {
  4378. /**
  4379. * Returns the surface of the Size : width * height (float).
  4380. */
  4381. get: function () {
  4382. return this.width * this.height;
  4383. },
  4384. enumerable: true,
  4385. configurable: true
  4386. });
  4387. /**
  4388. * Returns a new Size set to (0.0, 0.0)
  4389. */
  4390. Size.Zero = function () {
  4391. return new Size(0.0, 0.0);
  4392. };
  4393. /**
  4394. * Returns a new Size set as the addition result of the current Size and the given one.
  4395. */
  4396. Size.prototype.add = function (otherSize) {
  4397. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4398. return r;
  4399. };
  4400. /**
  4401. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4402. */
  4403. Size.prototype.subtract = function (otherSize) {
  4404. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4405. return r;
  4406. };
  4407. /**
  4408. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4409. */
  4410. Size.Lerp = function (start, end, amount) {
  4411. var w = start.width + ((end.width - start.width) * amount);
  4412. var h = start.height + ((end.height - start.height) * amount);
  4413. return new Size(w, h);
  4414. };
  4415. return Size;
  4416. }());
  4417. BABYLON.Size = Size;
  4418. /**
  4419. * Class used to store quaternion data
  4420. * @see https://en.wikipedia.org/wiki/Quaternion
  4421. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4422. */
  4423. var Quaternion = /** @class */ (function () {
  4424. /**
  4425. * Creates a new Quaternion from the given floats
  4426. * @param x defines the first component (0 by default)
  4427. * @param y defines the second component (0 by default)
  4428. * @param z defines the third component (0 by default)
  4429. * @param w defines the fourth component (1.0 by default)
  4430. */
  4431. function Quaternion(
  4432. /** defines the first component (0 by default) */
  4433. x,
  4434. /** defines the second component (0 by default) */
  4435. y,
  4436. /** defines the third component (0 by default) */
  4437. z,
  4438. /** defines the fourth component (1.0 by default) */
  4439. w) {
  4440. if (x === void 0) { x = 0.0; }
  4441. if (y === void 0) { y = 0.0; }
  4442. if (z === void 0) { z = 0.0; }
  4443. if (w === void 0) { w = 1.0; }
  4444. this.x = x;
  4445. this.y = y;
  4446. this.z = z;
  4447. this.w = w;
  4448. }
  4449. /**
  4450. * Gets a string representation for the current quaternion
  4451. * @returns a string with the Quaternion coordinates
  4452. */
  4453. Quaternion.prototype.toString = function () {
  4454. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4455. };
  4456. /**
  4457. * Gets the class name of the quaternion
  4458. * @returns the string "Quaternion"
  4459. */
  4460. Quaternion.prototype.getClassName = function () {
  4461. return "Quaternion";
  4462. };
  4463. /**
  4464. * Gets a hash code for this quaternion
  4465. * @returns the quaternion hash code
  4466. */
  4467. Quaternion.prototype.getHashCode = function () {
  4468. var hash = this.x || 0;
  4469. hash = (hash * 397) ^ (this.y || 0);
  4470. hash = (hash * 397) ^ (this.z || 0);
  4471. hash = (hash * 397) ^ (this.w || 0);
  4472. return hash;
  4473. };
  4474. /**
  4475. * Copy the quaternion to an array
  4476. * @returns a new array populated with 4 elements from the quaternion coordinates
  4477. */
  4478. Quaternion.prototype.asArray = function () {
  4479. return [this.x, this.y, this.z, this.w];
  4480. };
  4481. /**
  4482. * Check if two quaternions are equals
  4483. * @param otherQuaternion defines the second operand
  4484. * @return true if the current quaternion and the given one coordinates are strictly equals
  4485. */
  4486. Quaternion.prototype.equals = function (otherQuaternion) {
  4487. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4488. };
  4489. /**
  4490. * Clone the current quaternion
  4491. * @returns a new quaternion copied from the current one
  4492. */
  4493. Quaternion.prototype.clone = function () {
  4494. return new Quaternion(this.x, this.y, this.z, this.w);
  4495. };
  4496. /**
  4497. * Copy a quaternion to the current one
  4498. * @param other defines the other quaternion
  4499. * @returns the updated current quaternion
  4500. */
  4501. Quaternion.prototype.copyFrom = function (other) {
  4502. this.x = other.x;
  4503. this.y = other.y;
  4504. this.z = other.z;
  4505. this.w = other.w;
  4506. return this;
  4507. };
  4508. /**
  4509. * Updates the current quaternion with the given float coordinates
  4510. * @param x defines the x coordinate
  4511. * @param y defines the y coordinate
  4512. * @param z defines the z coordinate
  4513. * @param w defines the w coordinate
  4514. * @returns the updated current quaternion
  4515. */
  4516. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4517. this.x = x;
  4518. this.y = y;
  4519. this.z = z;
  4520. this.w = w;
  4521. return this;
  4522. };
  4523. /**
  4524. * Updates the current quaternion from the given float coordinates
  4525. * @param x defines the x coordinate
  4526. * @param y defines the y coordinate
  4527. * @param z defines the z coordinate
  4528. * @param w defines the w coordinate
  4529. * @returns the updated current quaternion
  4530. */
  4531. Quaternion.prototype.set = function (x, y, z, w) {
  4532. return this.copyFromFloats(x, y, z, w);
  4533. };
  4534. /**
  4535. * Adds two quaternions
  4536. * @param other defines the second operand
  4537. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4538. */
  4539. Quaternion.prototype.add = function (other) {
  4540. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4541. };
  4542. /**
  4543. * Add a quaternion to the current one
  4544. * @param other defines the quaternion to add
  4545. * @returns the current quaternion
  4546. */
  4547. Quaternion.prototype.addInPlace = function (other) {
  4548. this.x += other.x;
  4549. this.y += other.y;
  4550. this.z += other.z;
  4551. this.w += other.w;
  4552. return this;
  4553. };
  4554. /**
  4555. * Subtract two quaternions
  4556. * @param other defines the second operand
  4557. * @returns a new quaternion as the subtraction result of the given one from the current one
  4558. */
  4559. Quaternion.prototype.subtract = function (other) {
  4560. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4561. };
  4562. /**
  4563. * Multiplies the current quaternion by a scale factor
  4564. * @param value defines the scale factor
  4565. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4566. */
  4567. Quaternion.prototype.scale = function (value) {
  4568. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4569. };
  4570. /**
  4571. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4572. * @param scale defines the scale factor
  4573. * @param result defines the Quaternion object where to store the result
  4574. * @returns the unmodified current quaternion
  4575. */
  4576. Quaternion.prototype.scaleToRef = function (scale, result) {
  4577. result.x = this.x * scale;
  4578. result.y = this.y * scale;
  4579. result.z = this.z * scale;
  4580. result.w = this.w * scale;
  4581. return this;
  4582. };
  4583. /**
  4584. * Multiplies in place the current quaternion by a scale factor
  4585. * @param value defines the scale factor
  4586. * @returns the current modified quaternion
  4587. */
  4588. Quaternion.prototype.scaleInPlace = function (value) {
  4589. this.x *= value;
  4590. this.y *= value;
  4591. this.z *= value;
  4592. this.w *= value;
  4593. return this;
  4594. };
  4595. /**
  4596. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4597. * @param scale defines the scale factor
  4598. * @param result defines the Quaternion object where to store the result
  4599. * @returns the unmodified current quaternion
  4600. */
  4601. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4602. result.x += this.x * scale;
  4603. result.y += this.y * scale;
  4604. result.z += this.z * scale;
  4605. result.w += this.w * scale;
  4606. return this;
  4607. };
  4608. /**
  4609. * Multiplies two quaternions
  4610. * @param q1 defines the second operand
  4611. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4612. */
  4613. Quaternion.prototype.multiply = function (q1) {
  4614. var result = new Quaternion(0, 0, 0, 1.0);
  4615. this.multiplyToRef(q1, result);
  4616. return result;
  4617. };
  4618. /**
  4619. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4620. * @param q1 defines the second operand
  4621. * @param result defines the target quaternion
  4622. * @returns the current quaternion
  4623. */
  4624. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4625. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4626. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4627. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4628. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4629. result.copyFromFloats(x, y, z, w);
  4630. return this;
  4631. };
  4632. /**
  4633. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4634. * @param q1 defines the second operand
  4635. * @returns the currentupdated quaternion
  4636. */
  4637. Quaternion.prototype.multiplyInPlace = function (q1) {
  4638. this.multiplyToRef(q1, this);
  4639. return this;
  4640. };
  4641. /**
  4642. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4643. * @param ref defines the target quaternion
  4644. * @returns the current quaternion
  4645. */
  4646. Quaternion.prototype.conjugateToRef = function (ref) {
  4647. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4648. return this;
  4649. };
  4650. /**
  4651. * Conjugates in place (1-q) the current quaternion
  4652. * @returns the current updated quaternion
  4653. */
  4654. Quaternion.prototype.conjugateInPlace = function () {
  4655. this.x *= -1;
  4656. this.y *= -1;
  4657. this.z *= -1;
  4658. return this;
  4659. };
  4660. /**
  4661. * Conjugates in place (1-q) the current quaternion
  4662. * @returns a new quaternion
  4663. */
  4664. Quaternion.prototype.conjugate = function () {
  4665. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4666. return result;
  4667. };
  4668. /**
  4669. * Gets length of current quaternion
  4670. * @returns the quaternion length (float)
  4671. */
  4672. Quaternion.prototype.length = function () {
  4673. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4674. };
  4675. /**
  4676. * Normalize in place the current quaternion
  4677. * @returns the current updated quaternion
  4678. */
  4679. Quaternion.prototype.normalize = function () {
  4680. var length = 1.0 / this.length();
  4681. this.x *= length;
  4682. this.y *= length;
  4683. this.z *= length;
  4684. this.w *= length;
  4685. return this;
  4686. };
  4687. /**
  4688. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4689. * @param order is a reserved parameter and is ignore for now
  4690. * @returns a new Vector3 containing the Euler angles
  4691. */
  4692. Quaternion.prototype.toEulerAngles = function (order) {
  4693. if (order === void 0) { order = "YZX"; }
  4694. var result = Vector3.Zero();
  4695. this.toEulerAnglesToRef(result, order);
  4696. return result;
  4697. };
  4698. /**
  4699. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4700. * @param result defines the vector which will be filled with the Euler angles
  4701. * @param order is a reserved parameter and is ignore for now
  4702. * @returns the current unchanged quaternion
  4703. */
  4704. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4705. if (order === void 0) { order = "YZX"; }
  4706. var qz = this.z;
  4707. var qx = this.x;
  4708. var qy = this.y;
  4709. var qw = this.w;
  4710. var sqw = qw * qw;
  4711. var sqz = qz * qz;
  4712. var sqx = qx * qx;
  4713. var sqy = qy * qy;
  4714. var zAxisY = qy * qz - qx * qw;
  4715. var limit = .4999999;
  4716. if (zAxisY < -limit) {
  4717. result.y = 2 * Math.atan2(qy, qw);
  4718. result.x = Math.PI / 2;
  4719. result.z = 0;
  4720. }
  4721. else if (zAxisY > limit) {
  4722. result.y = 2 * Math.atan2(qy, qw);
  4723. result.x = -Math.PI / 2;
  4724. result.z = 0;
  4725. }
  4726. else {
  4727. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4728. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4729. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4730. }
  4731. return this;
  4732. };
  4733. /**
  4734. * Updates the given rotation matrix with the current quaternion values
  4735. * @param result defines the target matrix
  4736. * @returns the current unchanged quaternion
  4737. */
  4738. Quaternion.prototype.toRotationMatrix = function (result) {
  4739. var xx = this.x * this.x;
  4740. var yy = this.y * this.y;
  4741. var zz = this.z * this.z;
  4742. var xy = this.x * this.y;
  4743. var zw = this.z * this.w;
  4744. var zx = this.z * this.x;
  4745. var yw = this.y * this.w;
  4746. var yz = this.y * this.z;
  4747. var xw = this.x * this.w;
  4748. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4749. result.m[1] = 2.0 * (xy + zw);
  4750. result.m[2] = 2.0 * (zx - yw);
  4751. result.m[3] = 0;
  4752. result.m[4] = 2.0 * (xy - zw);
  4753. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4754. result.m[6] = 2.0 * (yz + xw);
  4755. result.m[7] = 0;
  4756. result.m[8] = 2.0 * (zx + yw);
  4757. result.m[9] = 2.0 * (yz - xw);
  4758. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4759. result.m[11] = 0;
  4760. result.m[12] = 0;
  4761. result.m[13] = 0;
  4762. result.m[14] = 0;
  4763. result.m[15] = 1.0;
  4764. result._markAsUpdated();
  4765. return this;
  4766. };
  4767. /**
  4768. * Updates the current quaternion from the given rotation matrix values
  4769. * @param matrix defines the source matrix
  4770. * @returns the current updated quaternion
  4771. */
  4772. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4773. Quaternion.FromRotationMatrixToRef(matrix, this);
  4774. return this;
  4775. };
  4776. // Statics
  4777. /**
  4778. * Creates a new quaternion from a rotation matrix
  4779. * @param matrix defines the source matrix
  4780. * @returns a new quaternion created from the given rotation matrix values
  4781. */
  4782. Quaternion.FromRotationMatrix = function (matrix) {
  4783. var result = new Quaternion();
  4784. Quaternion.FromRotationMatrixToRef(matrix, result);
  4785. return result;
  4786. };
  4787. /**
  4788. * Updates the given quaternion with the given rotation matrix values
  4789. * @param matrix defines the source matrix
  4790. * @param result defines the target quaternion
  4791. */
  4792. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4793. var data = matrix.m;
  4794. var m11 = data[0], m12 = data[4], m13 = data[8];
  4795. var m21 = data[1], m22 = data[5], m23 = data[9];
  4796. var m31 = data[2], m32 = data[6], m33 = data[10];
  4797. var trace = m11 + m22 + m33;
  4798. var s;
  4799. if (trace > 0) {
  4800. s = 0.5 / Math.sqrt(trace + 1.0);
  4801. result.w = 0.25 / s;
  4802. result.x = (m32 - m23) * s;
  4803. result.y = (m13 - m31) * s;
  4804. result.z = (m21 - m12) * s;
  4805. }
  4806. else if (m11 > m22 && m11 > m33) {
  4807. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4808. result.w = (m32 - m23) / s;
  4809. result.x = 0.25 * s;
  4810. result.y = (m12 + m21) / s;
  4811. result.z = (m13 + m31) / s;
  4812. }
  4813. else if (m22 > m33) {
  4814. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4815. result.w = (m13 - m31) / s;
  4816. result.x = (m12 + m21) / s;
  4817. result.y = 0.25 * s;
  4818. result.z = (m23 + m32) / s;
  4819. }
  4820. else {
  4821. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4822. result.w = (m21 - m12) / s;
  4823. result.x = (m13 + m31) / s;
  4824. result.y = (m23 + m32) / s;
  4825. result.z = 0.25 * s;
  4826. }
  4827. };
  4828. /**
  4829. * Returns the dot product (float) between the quaternions "left" and "right"
  4830. * @param left defines the left operand
  4831. * @param right defines the right operand
  4832. * @returns the dot product
  4833. */
  4834. Quaternion.Dot = function (left, right) {
  4835. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4836. };
  4837. /**
  4838. * Checks if the two quaternions are close to each other
  4839. * @param quat0 defines the first quaternion to check
  4840. * @param quat1 defines the second quaternion to check
  4841. * @returns true if the two quaternions are close to each other
  4842. */
  4843. Quaternion.AreClose = function (quat0, quat1) {
  4844. var dot = Quaternion.Dot(quat0, quat1);
  4845. return dot >= 0;
  4846. };
  4847. /**
  4848. * Creates an empty quaternion
  4849. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4850. */
  4851. Quaternion.Zero = function () {
  4852. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4853. };
  4854. /**
  4855. * Inverse a given quaternion
  4856. * @param q defines the source quaternion
  4857. * @returns a new quaternion as the inverted current quaternion
  4858. */
  4859. Quaternion.Inverse = function (q) {
  4860. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4861. };
  4862. /**
  4863. * Creates an identity quaternion
  4864. * @returns the identity quaternion
  4865. */
  4866. Quaternion.Identity = function () {
  4867. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4868. };
  4869. /**
  4870. * Gets a boolean indicating if the given quaternion is identity
  4871. * @param quaternion defines the quaternion to check
  4872. * @returns true if the quaternion is identity
  4873. */
  4874. Quaternion.IsIdentity = function (quaternion) {
  4875. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4876. };
  4877. /**
  4878. * Creates a quaternion from a rotation around an axis
  4879. * @param axis defines the axis to use
  4880. * @param angle defines the angle to use
  4881. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4882. */
  4883. Quaternion.RotationAxis = function (axis, angle) {
  4884. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4885. };
  4886. /**
  4887. * Creates a rotation around an axis and stores it into the given quaternion
  4888. * @param axis defines the axis to use
  4889. * @param angle defines the angle to use
  4890. * @param result defines the target quaternion
  4891. * @returns the target quaternion
  4892. */
  4893. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4894. var sin = Math.sin(angle / 2);
  4895. axis.normalize();
  4896. result.w = Math.cos(angle / 2);
  4897. result.x = axis.x * sin;
  4898. result.y = axis.y * sin;
  4899. result.z = axis.z * sin;
  4900. return result;
  4901. };
  4902. /**
  4903. * Creates a new quaternion from data stored into an array
  4904. * @param array defines the data source
  4905. * @param offset defines the offset in the source array where the data starts
  4906. * @returns a new quaternion
  4907. */
  4908. Quaternion.FromArray = function (array, offset) {
  4909. if (!offset) {
  4910. offset = 0;
  4911. }
  4912. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4913. };
  4914. /**
  4915. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4916. * @param yaw defines the rotation around Y axis
  4917. * @param pitch defines the rotation around X axis
  4918. * @param roll defines the rotation around Z axis
  4919. * @returns the new quaternion
  4920. */
  4921. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4922. var q = new Quaternion();
  4923. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4924. return q;
  4925. };
  4926. /**
  4927. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4928. * @param yaw defines the rotation around Y axis
  4929. * @param pitch defines the rotation around X axis
  4930. * @param roll defines the rotation around Z axis
  4931. * @param result defines the target quaternion
  4932. */
  4933. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4934. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4935. var halfRoll = roll * 0.5;
  4936. var halfPitch = pitch * 0.5;
  4937. var halfYaw = yaw * 0.5;
  4938. var sinRoll = Math.sin(halfRoll);
  4939. var cosRoll = Math.cos(halfRoll);
  4940. var sinPitch = Math.sin(halfPitch);
  4941. var cosPitch = Math.cos(halfPitch);
  4942. var sinYaw = Math.sin(halfYaw);
  4943. var cosYaw = Math.cos(halfYaw);
  4944. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4945. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4946. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4947. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4948. };
  4949. /**
  4950. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4951. * @param alpha defines the rotation around first axis
  4952. * @param beta defines the rotation around second axis
  4953. * @param gamma defines the rotation around third axis
  4954. * @returns the new quaternion
  4955. */
  4956. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4957. var result = new Quaternion();
  4958. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4959. return result;
  4960. };
  4961. /**
  4962. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4963. * @param alpha defines the rotation around first axis
  4964. * @param beta defines the rotation around second axis
  4965. * @param gamma defines the rotation around third axis
  4966. * @param result defines the target quaternion
  4967. */
  4968. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4969. // Produces a quaternion from Euler angles in the z-x-z orientation
  4970. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4971. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4972. var halfBeta = beta * 0.5;
  4973. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4974. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4975. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4976. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4977. };
  4978. /**
  4979. * 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)
  4980. * @param axis1 defines the first axis
  4981. * @param axis2 defines the second axis
  4982. * @param axis3 defines the third axis
  4983. * @returns the new quaternion
  4984. */
  4985. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4986. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4987. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4988. return quat;
  4989. };
  4990. /**
  4991. * 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
  4992. * @param axis1 defines the first axis
  4993. * @param axis2 defines the second axis
  4994. * @param axis3 defines the third axis
  4995. * @param ref defines the target quaternion
  4996. */
  4997. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4998. var rotMat = MathTmp.Matrix[0];
  4999. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5000. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5001. };
  5002. /**
  5003. * Interpolates between two quaternions
  5004. * @param left defines first quaternion
  5005. * @param right defines second quaternion
  5006. * @param amount defines the gradient to use
  5007. * @returns the new interpolated quaternion
  5008. */
  5009. Quaternion.Slerp = function (left, right, amount) {
  5010. var result = Quaternion.Identity();
  5011. Quaternion.SlerpToRef(left, right, amount, result);
  5012. return result;
  5013. };
  5014. /**
  5015. * Interpolates between two quaternions and stores it into a target quaternion
  5016. * @param left defines first quaternion
  5017. * @param right defines second quaternion
  5018. * @param amount defines the gradient to use
  5019. * @param result defines the target quaternion
  5020. */
  5021. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5022. var num2;
  5023. var num3;
  5024. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5025. var flag = false;
  5026. if (num4 < 0) {
  5027. flag = true;
  5028. num4 = -num4;
  5029. }
  5030. if (num4 > 0.999999) {
  5031. num3 = 1 - amount;
  5032. num2 = flag ? -amount : amount;
  5033. }
  5034. else {
  5035. var num5 = Math.acos(num4);
  5036. var num6 = (1.0 / Math.sin(num5));
  5037. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5038. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5039. }
  5040. result.x = (num3 * left.x) + (num2 * right.x);
  5041. result.y = (num3 * left.y) + (num2 * right.y);
  5042. result.z = (num3 * left.z) + (num2 * right.z);
  5043. result.w = (num3 * left.w) + (num2 * right.w);
  5044. };
  5045. /**
  5046. * Interpolate between two quaternions using Hermite interpolation
  5047. * @param value1 defines first quaternion
  5048. * @param tangent1 defines the incoming tangent
  5049. * @param value2 defines second quaternion
  5050. * @param tangent2 defines the outgoing tangent
  5051. * @param amount defines the target quaternion
  5052. * @returns the new interpolated quaternion
  5053. */
  5054. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5055. var squared = amount * amount;
  5056. var cubed = amount * squared;
  5057. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5058. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5059. var part3 = (cubed - (2.0 * squared)) + amount;
  5060. var part4 = cubed - squared;
  5061. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5062. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5063. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5064. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5065. return new Quaternion(x, y, z, w);
  5066. };
  5067. return Quaternion;
  5068. }());
  5069. BABYLON.Quaternion = Quaternion;
  5070. /**
  5071. * Class used to store matrix data (4x4)
  5072. */
  5073. var Matrix = /** @class */ (function () {
  5074. /**
  5075. * Creates an empty matrix (filled with zeros)
  5076. */
  5077. function Matrix() {
  5078. this._isIdentity = false;
  5079. this._isIdentityDirty = true;
  5080. /**
  5081. * Gets or sets the internal data of the matrix
  5082. */
  5083. this.m = new Float32Array(16);
  5084. this._markAsUpdated();
  5085. }
  5086. /** @hidden */
  5087. Matrix.prototype._markAsUpdated = function () {
  5088. this.updateFlag = Matrix._updateFlagSeed++;
  5089. this._isIdentityDirty = true;
  5090. };
  5091. // Properties
  5092. /**
  5093. * Check if the current matrix is indentity
  5094. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5095. * @returns true is the matrix is the identity matrix
  5096. */
  5097. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5098. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5099. if (this._isIdentityDirty) {
  5100. this._isIdentityDirty = false;
  5101. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5102. this._isIdentity = false;
  5103. }
  5104. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5105. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5106. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5107. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5108. this._isIdentity = false;
  5109. }
  5110. else {
  5111. this._isIdentity = true;
  5112. }
  5113. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5114. this._isIdentity = false;
  5115. }
  5116. }
  5117. return this._isIdentity;
  5118. };
  5119. /**
  5120. * Gets the determinant of the matrix
  5121. * @returns the matrix determinant
  5122. */
  5123. Matrix.prototype.determinant = function () {
  5124. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5125. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5126. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5127. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5128. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5129. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5130. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5131. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5132. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5133. };
  5134. // Methods
  5135. /**
  5136. * Returns the matrix as a Float32Array
  5137. * @returns the matrix underlying array
  5138. */
  5139. Matrix.prototype.toArray = function () {
  5140. return this.m;
  5141. };
  5142. /**
  5143. * Returns the matrix as a Float32Array
  5144. * @returns the matrix underlying array.
  5145. */
  5146. Matrix.prototype.asArray = function () {
  5147. return this.toArray();
  5148. };
  5149. /**
  5150. * Inverts the current matrix in place
  5151. * @returns the current inverted matrix
  5152. */
  5153. Matrix.prototype.invert = function () {
  5154. this.invertToRef(this);
  5155. return this;
  5156. };
  5157. /**
  5158. * Sets all the matrix elements to zero
  5159. * @returns the current matrix
  5160. */
  5161. Matrix.prototype.reset = function () {
  5162. for (var index = 0; index < 16; index++) {
  5163. this.m[index] = 0.0;
  5164. }
  5165. this._markAsUpdated();
  5166. return this;
  5167. };
  5168. /**
  5169. * Adds the current matrix with a second one
  5170. * @param other defines the matrix to add
  5171. * @returns a new matrix as the addition of the current matrix and the given one
  5172. */
  5173. Matrix.prototype.add = function (other) {
  5174. var result = new Matrix();
  5175. this.addToRef(other, result);
  5176. return result;
  5177. };
  5178. /**
  5179. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5180. * @param other defines the matrix to add
  5181. * @param result defines the target matrix
  5182. * @returns the current matrix
  5183. */
  5184. Matrix.prototype.addToRef = function (other, result) {
  5185. for (var index = 0; index < 16; index++) {
  5186. result.m[index] = this.m[index] + other.m[index];
  5187. }
  5188. result._markAsUpdated();
  5189. return this;
  5190. };
  5191. /**
  5192. * Adds in place the given matrix to the current matrix
  5193. * @param other defines the second operand
  5194. * @returns the current updated matrix
  5195. */
  5196. Matrix.prototype.addToSelf = function (other) {
  5197. for (var index = 0; index < 16; index++) {
  5198. this.m[index] += other.m[index];
  5199. }
  5200. this._markAsUpdated();
  5201. return this;
  5202. };
  5203. /**
  5204. * Sets the given matrix to the current inverted Matrix
  5205. * @param other defines the target matrix
  5206. * @returns the unmodified current matrix
  5207. */
  5208. Matrix.prototype.invertToRef = function (other) {
  5209. var l1 = this.m[0];
  5210. var l2 = this.m[1];
  5211. var l3 = this.m[2];
  5212. var l4 = this.m[3];
  5213. var l5 = this.m[4];
  5214. var l6 = this.m[5];
  5215. var l7 = this.m[6];
  5216. var l8 = this.m[7];
  5217. var l9 = this.m[8];
  5218. var l10 = this.m[9];
  5219. var l11 = this.m[10];
  5220. var l12 = this.m[11];
  5221. var l13 = this.m[12];
  5222. var l14 = this.m[13];
  5223. var l15 = this.m[14];
  5224. var l16 = this.m[15];
  5225. var l17 = (l11 * l16) - (l12 * l15);
  5226. var l18 = (l10 * l16) - (l12 * l14);
  5227. var l19 = (l10 * l15) - (l11 * l14);
  5228. var l20 = (l9 * l16) - (l12 * l13);
  5229. var l21 = (l9 * l15) - (l11 * l13);
  5230. var l22 = (l9 * l14) - (l10 * l13);
  5231. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5232. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5233. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5234. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5235. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5236. var l28 = (l7 * l16) - (l8 * l15);
  5237. var l29 = (l6 * l16) - (l8 * l14);
  5238. var l30 = (l6 * l15) - (l7 * l14);
  5239. var l31 = (l5 * l16) - (l8 * l13);
  5240. var l32 = (l5 * l15) - (l7 * l13);
  5241. var l33 = (l5 * l14) - (l6 * l13);
  5242. var l34 = (l7 * l12) - (l8 * l11);
  5243. var l35 = (l6 * l12) - (l8 * l10);
  5244. var l36 = (l6 * l11) - (l7 * l10);
  5245. var l37 = (l5 * l12) - (l8 * l9);
  5246. var l38 = (l5 * l11) - (l7 * l9);
  5247. var l39 = (l5 * l10) - (l6 * l9);
  5248. other.m[0] = l23 * l27;
  5249. other.m[4] = l24 * l27;
  5250. other.m[8] = l25 * l27;
  5251. other.m[12] = l26 * l27;
  5252. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5253. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5254. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5255. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5256. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5257. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5258. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5259. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5260. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5261. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5262. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5263. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5264. other._markAsUpdated();
  5265. return this;
  5266. };
  5267. /**
  5268. * Inserts the translation vector (using 3 floats) in the current matrix
  5269. * @param x defines the 1st component of the translation
  5270. * @param y defines the 2nd component of the translation
  5271. * @param z defines the 3rd component of the translation
  5272. * @returns the current updated matrix
  5273. */
  5274. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5275. this.m[12] = x;
  5276. this.m[13] = y;
  5277. this.m[14] = z;
  5278. this._markAsUpdated();
  5279. return this;
  5280. };
  5281. /**
  5282. * Inserts the translation vector in the current matrix
  5283. * @param vector3 defines the translation to insert
  5284. * @returns the current updated matrix
  5285. */
  5286. Matrix.prototype.setTranslation = function (vector3) {
  5287. this.m[12] = vector3.x;
  5288. this.m[13] = vector3.y;
  5289. this.m[14] = vector3.z;
  5290. this._markAsUpdated();
  5291. return this;
  5292. };
  5293. /**
  5294. * Gets the translation value of the current matrix
  5295. * @returns a new Vector3 as the extracted translation from the matrix
  5296. */
  5297. Matrix.prototype.getTranslation = function () {
  5298. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5299. };
  5300. /**
  5301. * Fill a Vector3 with the extracted translation from the matrix
  5302. * @param result defines the Vector3 where to store the translation
  5303. * @returns the current matrix
  5304. */
  5305. Matrix.prototype.getTranslationToRef = function (result) {
  5306. result.x = this.m[12];
  5307. result.y = this.m[13];
  5308. result.z = this.m[14];
  5309. return this;
  5310. };
  5311. /**
  5312. * Remove rotation and scaling part from the matrix
  5313. * @returns the updated matrix
  5314. */
  5315. Matrix.prototype.removeRotationAndScaling = function () {
  5316. this.setRowFromFloats(0, 1, 0, 0, 0);
  5317. this.setRowFromFloats(1, 0, 1, 0, 0);
  5318. this.setRowFromFloats(2, 0, 0, 1, 0);
  5319. return this;
  5320. };
  5321. /**
  5322. * Multiply two matrices
  5323. * @param other defines the second operand
  5324. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5325. */
  5326. Matrix.prototype.multiply = function (other) {
  5327. var result = new Matrix();
  5328. this.multiplyToRef(other, result);
  5329. return result;
  5330. };
  5331. /**
  5332. * Copy the current matrix from the given one
  5333. * @param other defines the source matrix
  5334. * @returns the current updated matrix
  5335. */
  5336. Matrix.prototype.copyFrom = function (other) {
  5337. for (var index = 0; index < 16; index++) {
  5338. this.m[index] = other.m[index];
  5339. }
  5340. this._markAsUpdated();
  5341. return this;
  5342. };
  5343. /**
  5344. * Populates the given array from the starting index with the current matrix values
  5345. * @param array defines the target array
  5346. * @param offset defines the offset in the target array where to start storing values
  5347. * @returns the current matrix
  5348. */
  5349. Matrix.prototype.copyToArray = function (array, offset) {
  5350. if (offset === void 0) { offset = 0; }
  5351. for (var index = 0; index < 16; index++) {
  5352. array[offset + index] = this.m[index];
  5353. }
  5354. return this;
  5355. };
  5356. /**
  5357. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5358. * @param other defines the second operand
  5359. * @param result defines the matrix where to store the multiplication
  5360. * @returns the current matrix
  5361. */
  5362. Matrix.prototype.multiplyToRef = function (other, result) {
  5363. this.multiplyToArray(other, result.m, 0);
  5364. result._markAsUpdated();
  5365. return this;
  5366. };
  5367. /**
  5368. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5369. * @param other defines the second operand
  5370. * @param result defines the array where to store the multiplication
  5371. * @param offset defines the offset in the target array where to start storing values
  5372. * @returns the current matrix
  5373. */
  5374. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5375. var tm0 = this.m[0];
  5376. var tm1 = this.m[1];
  5377. var tm2 = this.m[2];
  5378. var tm3 = this.m[3];
  5379. var tm4 = this.m[4];
  5380. var tm5 = this.m[5];
  5381. var tm6 = this.m[6];
  5382. var tm7 = this.m[7];
  5383. var tm8 = this.m[8];
  5384. var tm9 = this.m[9];
  5385. var tm10 = this.m[10];
  5386. var tm11 = this.m[11];
  5387. var tm12 = this.m[12];
  5388. var tm13 = this.m[13];
  5389. var tm14 = this.m[14];
  5390. var tm15 = this.m[15];
  5391. var om0 = other.m[0];
  5392. var om1 = other.m[1];
  5393. var om2 = other.m[2];
  5394. var om3 = other.m[3];
  5395. var om4 = other.m[4];
  5396. var om5 = other.m[5];
  5397. var om6 = other.m[6];
  5398. var om7 = other.m[7];
  5399. var om8 = other.m[8];
  5400. var om9 = other.m[9];
  5401. var om10 = other.m[10];
  5402. var om11 = other.m[11];
  5403. var om12 = other.m[12];
  5404. var om13 = other.m[13];
  5405. var om14 = other.m[14];
  5406. var om15 = other.m[15];
  5407. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5408. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5409. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5410. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5411. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5412. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5413. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5414. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5415. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5416. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5417. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5418. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5419. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5420. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5421. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5422. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5423. return this;
  5424. };
  5425. /**
  5426. * Check equality between this matrix and a second one
  5427. * @param value defines the second matrix to compare
  5428. * @returns true is the current matrix and the given one values are strictly equal
  5429. */
  5430. Matrix.prototype.equals = function (value) {
  5431. return value &&
  5432. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5433. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5434. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5435. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5436. };
  5437. /**
  5438. * Clone the current matrix
  5439. * @returns a new matrix from the current matrix
  5440. */
  5441. Matrix.prototype.clone = function () {
  5442. 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]);
  5443. };
  5444. /**
  5445. * Returns the name of the current matrix class
  5446. * @returns the string "Matrix"
  5447. */
  5448. Matrix.prototype.getClassName = function () {
  5449. return "Matrix";
  5450. };
  5451. /**
  5452. * Gets the hash code of the current matrix
  5453. * @returns the hash code
  5454. */
  5455. Matrix.prototype.getHashCode = function () {
  5456. var hash = this.m[0] || 0;
  5457. for (var i = 1; i < 16; i++) {
  5458. hash = (hash * 397) ^ (this.m[i] || 0);
  5459. }
  5460. return hash;
  5461. };
  5462. /**
  5463. * Decomposes the current Matrix into a translation, rotation and scaling components
  5464. * @param scale defines the scale vector3 given as a reference to update
  5465. * @param rotation defines the rotation quaternion given as a reference to update
  5466. * @param translation defines the translation vector3 given as a reference to update
  5467. * @returns true if operation was successful
  5468. */
  5469. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5470. if (translation) {
  5471. translation.x = this.m[12];
  5472. translation.y = this.m[13];
  5473. translation.z = this.m[14];
  5474. }
  5475. scale = scale || MathTmp.Vector3[0];
  5476. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5477. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5478. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5479. if (this.determinant() <= 0) {
  5480. scale.y *= -1;
  5481. }
  5482. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5483. if (rotation) {
  5484. rotation.x = 0;
  5485. rotation.y = 0;
  5486. rotation.z = 0;
  5487. rotation.w = 1;
  5488. }
  5489. return false;
  5490. }
  5491. if (rotation) {
  5492. 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]);
  5493. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5494. }
  5495. return true;
  5496. };
  5497. /**
  5498. * Gets specific row of the matrix
  5499. * @param index defines the number of the row to get
  5500. * @returns the index-th row of the current matrix as a new Vector4
  5501. */
  5502. Matrix.prototype.getRow = function (index) {
  5503. if (index < 0 || index > 3) {
  5504. return null;
  5505. }
  5506. var i = index * 4;
  5507. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5508. };
  5509. /**
  5510. * Sets the index-th row of the current matrix to the vector4 values
  5511. * @param index defines the number of the row to set
  5512. * @param row defines the target vector4
  5513. * @returns the updated current matrix
  5514. */
  5515. Matrix.prototype.setRow = function (index, row) {
  5516. if (index < 0 || index > 3) {
  5517. return this;
  5518. }
  5519. var i = index * 4;
  5520. this.m[i + 0] = row.x;
  5521. this.m[i + 1] = row.y;
  5522. this.m[i + 2] = row.z;
  5523. this.m[i + 3] = row.w;
  5524. this._markAsUpdated();
  5525. return this;
  5526. };
  5527. /**
  5528. * Compute the transpose of the matrix
  5529. * @returns the new transposed matrix
  5530. */
  5531. Matrix.prototype.transpose = function () {
  5532. return Matrix.Transpose(this);
  5533. };
  5534. /**
  5535. * Compute the transpose of the matrix and store it in a given matrix
  5536. * @param result defines the target matrix
  5537. * @returns the current matrix
  5538. */
  5539. Matrix.prototype.transposeToRef = function (result) {
  5540. Matrix.TransposeToRef(this, result);
  5541. return this;
  5542. };
  5543. /**
  5544. * Sets the index-th row of the current matrix with the given 4 x float values
  5545. * @param index defines the row index
  5546. * @param x defines the x component to set
  5547. * @param y defines the y component to set
  5548. * @param z defines the z component to set
  5549. * @param w defines the w component to set
  5550. * @returns the updated current matrix
  5551. */
  5552. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5553. if (index < 0 || index > 3) {
  5554. return this;
  5555. }
  5556. var i = index * 4;
  5557. this.m[i + 0] = x;
  5558. this.m[i + 1] = y;
  5559. this.m[i + 2] = z;
  5560. this.m[i + 3] = w;
  5561. this._markAsUpdated();
  5562. return this;
  5563. };
  5564. /**
  5565. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5566. * @param scale defines the scale factor
  5567. * @returns a new matrix
  5568. */
  5569. Matrix.prototype.scale = function (scale) {
  5570. var result = new Matrix();
  5571. this.scaleToRef(scale, result);
  5572. return result;
  5573. };
  5574. /**
  5575. * Scale the current matrix values by a factor to a given result matrix
  5576. * @param scale defines the scale factor
  5577. * @param result defines the matrix to store the result
  5578. * @returns the current matrix
  5579. */
  5580. Matrix.prototype.scaleToRef = function (scale, result) {
  5581. for (var index = 0; index < 16; index++) {
  5582. result.m[index] = this.m[index] * scale;
  5583. }
  5584. result._markAsUpdated();
  5585. return this;
  5586. };
  5587. /**
  5588. * Scale the current matrix values by a factor and add the result to a given matrix
  5589. * @param scale defines the scale factor
  5590. * @param result defines the Matrix to store the result
  5591. * @returns the current matrix
  5592. */
  5593. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5594. for (var index = 0; index < 16; index++) {
  5595. result.m[index] += this.m[index] * scale;
  5596. }
  5597. result._markAsUpdated();
  5598. return this;
  5599. };
  5600. /**
  5601. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5602. * @param ref matrix to store the result
  5603. */
  5604. Matrix.prototype.toNormalMatrix = function (ref) {
  5605. this.invertToRef(ref);
  5606. ref.transpose();
  5607. var m = ref.m;
  5608. 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);
  5609. };
  5610. /**
  5611. * Gets only rotation part of the current matrix
  5612. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5613. */
  5614. Matrix.prototype.getRotationMatrix = function () {
  5615. var result = Matrix.Identity();
  5616. this.getRotationMatrixToRef(result);
  5617. return result;
  5618. };
  5619. /**
  5620. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5621. * @param result defines the target matrix to store data to
  5622. * @returns the current matrix
  5623. */
  5624. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5625. var m = this.m;
  5626. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5627. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5628. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5629. if (this.determinant() <= 0) {
  5630. sy *= -1;
  5631. }
  5632. if (sx === 0 || sy === 0 || sz === 0) {
  5633. Matrix.IdentityToRef(result);
  5634. }
  5635. else {
  5636. 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);
  5637. }
  5638. return this;
  5639. };
  5640. // Statics
  5641. /**
  5642. * Creates a matrix from an array
  5643. * @param array defines the source array
  5644. * @param offset defines an offset in the source array
  5645. * @returns a new Matrix set from the starting index of the given array
  5646. */
  5647. Matrix.FromArray = function (array, offset) {
  5648. var result = new Matrix();
  5649. if (!offset) {
  5650. offset = 0;
  5651. }
  5652. Matrix.FromArrayToRef(array, offset, result);
  5653. return result;
  5654. };
  5655. /**
  5656. * Copy the content of an array into a given matrix
  5657. * @param array defines the source array
  5658. * @param offset defines an offset in the source array
  5659. * @param result defines the target matrix
  5660. */
  5661. Matrix.FromArrayToRef = function (array, offset, result) {
  5662. for (var index = 0; index < 16; index++) {
  5663. result.m[index] = array[index + offset];
  5664. }
  5665. result._markAsUpdated();
  5666. };
  5667. /**
  5668. * Stores an array into a matrix after having multiplied each component by a given factor
  5669. * @param array defines the source array
  5670. * @param offset defines the offset in the source array
  5671. * @param scale defines the scaling factor
  5672. * @param result defines the target matrix
  5673. */
  5674. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5675. for (var index = 0; index < 16; index++) {
  5676. result.m[index] = array[index + offset] * scale;
  5677. }
  5678. result._markAsUpdated();
  5679. };
  5680. /**
  5681. * Stores a list of values (16) inside a given matrix
  5682. * @param initialM11 defines 1st value of 1st row
  5683. * @param initialM12 defines 2nd value of 1st row
  5684. * @param initialM13 defines 3rd value of 1st row
  5685. * @param initialM14 defines 4th value of 1st row
  5686. * @param initialM21 defines 1st value of 2nd row
  5687. * @param initialM22 defines 2nd value of 2nd row
  5688. * @param initialM23 defines 3rd value of 2nd row
  5689. * @param initialM24 defines 4th value of 2nd row
  5690. * @param initialM31 defines 1st value of 3rd row
  5691. * @param initialM32 defines 2nd value of 3rd row
  5692. * @param initialM33 defines 3rd value of 3rd row
  5693. * @param initialM34 defines 4th value of 3rd row
  5694. * @param initialM41 defines 1st value of 4th row
  5695. * @param initialM42 defines 2nd value of 4th row
  5696. * @param initialM43 defines 3rd value of 4th row
  5697. * @param initialM44 defines 4th value of 4th row
  5698. * @param result defines the target matrix
  5699. */
  5700. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5701. result.m[0] = initialM11;
  5702. result.m[1] = initialM12;
  5703. result.m[2] = initialM13;
  5704. result.m[3] = initialM14;
  5705. result.m[4] = initialM21;
  5706. result.m[5] = initialM22;
  5707. result.m[6] = initialM23;
  5708. result.m[7] = initialM24;
  5709. result.m[8] = initialM31;
  5710. result.m[9] = initialM32;
  5711. result.m[10] = initialM33;
  5712. result.m[11] = initialM34;
  5713. result.m[12] = initialM41;
  5714. result.m[13] = initialM42;
  5715. result.m[14] = initialM43;
  5716. result.m[15] = initialM44;
  5717. result._markAsUpdated();
  5718. };
  5719. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5720. /**
  5721. * Gets an identity matrix that must not be updated
  5722. */
  5723. get: function () {
  5724. return Matrix._identityReadOnly;
  5725. },
  5726. enumerable: true,
  5727. configurable: true
  5728. });
  5729. /**
  5730. * Creates new matrix from a list of values (16)
  5731. * @param initialM11 defines 1st value of 1st row
  5732. * @param initialM12 defines 2nd value of 1st row
  5733. * @param initialM13 defines 3rd value of 1st row
  5734. * @param initialM14 defines 4th value of 1st row
  5735. * @param initialM21 defines 1st value of 2nd row
  5736. * @param initialM22 defines 2nd value of 2nd row
  5737. * @param initialM23 defines 3rd value of 2nd row
  5738. * @param initialM24 defines 4th value of 2nd row
  5739. * @param initialM31 defines 1st value of 3rd row
  5740. * @param initialM32 defines 2nd value of 3rd row
  5741. * @param initialM33 defines 3rd value of 3rd row
  5742. * @param initialM34 defines 4th value of 3rd row
  5743. * @param initialM41 defines 1st value of 4th row
  5744. * @param initialM42 defines 2nd value of 4th row
  5745. * @param initialM43 defines 3rd value of 4th row
  5746. * @param initialM44 defines 4th value of 4th row
  5747. * @returns the new matrix
  5748. */
  5749. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5750. var result = new Matrix();
  5751. result.m[0] = initialM11;
  5752. result.m[1] = initialM12;
  5753. result.m[2] = initialM13;
  5754. result.m[3] = initialM14;
  5755. result.m[4] = initialM21;
  5756. result.m[5] = initialM22;
  5757. result.m[6] = initialM23;
  5758. result.m[7] = initialM24;
  5759. result.m[8] = initialM31;
  5760. result.m[9] = initialM32;
  5761. result.m[10] = initialM33;
  5762. result.m[11] = initialM34;
  5763. result.m[12] = initialM41;
  5764. result.m[13] = initialM42;
  5765. result.m[14] = initialM43;
  5766. result.m[15] = initialM44;
  5767. return result;
  5768. };
  5769. /**
  5770. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5771. * @param scale defines the scale vector3
  5772. * @param rotation defines the rotation quaternion
  5773. * @param translation defines the translation vector3
  5774. * @returns a new matrix
  5775. */
  5776. Matrix.Compose = function (scale, rotation, translation) {
  5777. var result = Matrix.Identity();
  5778. Matrix.ComposeToRef(scale, rotation, translation, result);
  5779. return result;
  5780. };
  5781. /**
  5782. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5783. * @param scale defines the scale vector3
  5784. * @param rotation defines the rotation quaternion
  5785. * @param translation defines the translation vector3
  5786. * @param result defines the target matrix
  5787. */
  5788. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5789. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5790. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5791. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5792. result.setTranslation(translation);
  5793. };
  5794. /**
  5795. * Creates a new identity matrix
  5796. * @returns a new identity matrix
  5797. */
  5798. Matrix.Identity = function () {
  5799. 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);
  5800. };
  5801. /**
  5802. * Creates a new identity matrix and stores the result in a given matrix
  5803. * @param result defines the target matrix
  5804. */
  5805. Matrix.IdentityToRef = function (result) {
  5806. 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);
  5807. };
  5808. /**
  5809. * Creates a new zero matrix
  5810. * @returns a new zero matrix
  5811. */
  5812. Matrix.Zero = function () {
  5813. 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);
  5814. };
  5815. /**
  5816. * Creates a new rotation matrix for "angle" radians around the X axis
  5817. * @param angle defines the angle (in radians) to use
  5818. * @return the new matrix
  5819. */
  5820. Matrix.RotationX = function (angle) {
  5821. var result = new Matrix();
  5822. Matrix.RotationXToRef(angle, result);
  5823. return result;
  5824. };
  5825. /**
  5826. * Creates a new matrix as the invert of a given matrix
  5827. * @param source defines the source matrix
  5828. * @returns the new matrix
  5829. */
  5830. Matrix.Invert = function (source) {
  5831. var result = new Matrix();
  5832. source.invertToRef(result);
  5833. return result;
  5834. };
  5835. /**
  5836. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5837. * @param angle defines the angle (in radians) to use
  5838. * @param result defines the target matrix
  5839. */
  5840. Matrix.RotationXToRef = function (angle, result) {
  5841. var s = Math.sin(angle);
  5842. var c = Math.cos(angle);
  5843. result.m[0] = 1.0;
  5844. result.m[15] = 1.0;
  5845. result.m[5] = c;
  5846. result.m[10] = c;
  5847. result.m[9] = -s;
  5848. result.m[6] = s;
  5849. result.m[1] = 0.0;
  5850. result.m[2] = 0.0;
  5851. result.m[3] = 0.0;
  5852. result.m[4] = 0.0;
  5853. result.m[7] = 0.0;
  5854. result.m[8] = 0.0;
  5855. result.m[11] = 0.0;
  5856. result.m[12] = 0.0;
  5857. result.m[13] = 0.0;
  5858. result.m[14] = 0.0;
  5859. result._markAsUpdated();
  5860. };
  5861. /**
  5862. * Creates a new rotation matrix for "angle" radians around the Y axis
  5863. * @param angle defines the angle (in radians) to use
  5864. * @return the new matrix
  5865. */
  5866. Matrix.RotationY = function (angle) {
  5867. var result = new Matrix();
  5868. Matrix.RotationYToRef(angle, result);
  5869. return result;
  5870. };
  5871. /**
  5872. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5873. * @param angle defines the angle (in radians) to use
  5874. * @param result defines the target matrix
  5875. */
  5876. Matrix.RotationYToRef = function (angle, result) {
  5877. var s = Math.sin(angle);
  5878. var c = Math.cos(angle);
  5879. result.m[5] = 1.0;
  5880. result.m[15] = 1.0;
  5881. result.m[0] = c;
  5882. result.m[2] = -s;
  5883. result.m[8] = s;
  5884. result.m[10] = c;
  5885. result.m[1] = 0.0;
  5886. result.m[3] = 0.0;
  5887. result.m[4] = 0.0;
  5888. result.m[6] = 0.0;
  5889. result.m[7] = 0.0;
  5890. result.m[9] = 0.0;
  5891. result.m[11] = 0.0;
  5892. result.m[12] = 0.0;
  5893. result.m[13] = 0.0;
  5894. result.m[14] = 0.0;
  5895. result._markAsUpdated();
  5896. };
  5897. /**
  5898. * Creates a new rotation matrix for "angle" radians around the Z axis
  5899. * @param angle defines the angle (in radians) to use
  5900. * @return the new matrix
  5901. */
  5902. Matrix.RotationZ = function (angle) {
  5903. var result = new Matrix();
  5904. Matrix.RotationZToRef(angle, result);
  5905. return result;
  5906. };
  5907. /**
  5908. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5909. * @param angle defines the angle (in radians) to use
  5910. * @param result defines the target matrix
  5911. */
  5912. Matrix.RotationZToRef = function (angle, result) {
  5913. var s = Math.sin(angle);
  5914. var c = Math.cos(angle);
  5915. result.m[10] = 1.0;
  5916. result.m[15] = 1.0;
  5917. result.m[0] = c;
  5918. result.m[1] = s;
  5919. result.m[4] = -s;
  5920. result.m[5] = c;
  5921. result.m[2] = 0.0;
  5922. result.m[3] = 0.0;
  5923. result.m[6] = 0.0;
  5924. result.m[7] = 0.0;
  5925. result.m[8] = 0.0;
  5926. result.m[9] = 0.0;
  5927. result.m[11] = 0.0;
  5928. result.m[12] = 0.0;
  5929. result.m[13] = 0.0;
  5930. result.m[14] = 0.0;
  5931. result._markAsUpdated();
  5932. };
  5933. /**
  5934. * Creates a new rotation matrix for "angle" radians around the given axis
  5935. * @param axis defines the axis to use
  5936. * @param angle defines the angle (in radians) to use
  5937. * @return the new matrix
  5938. */
  5939. Matrix.RotationAxis = function (axis, angle) {
  5940. var result = Matrix.Zero();
  5941. Matrix.RotationAxisToRef(axis, angle, result);
  5942. return result;
  5943. };
  5944. /**
  5945. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5946. * @param axis defines the axis to use
  5947. * @param angle defines the angle (in radians) to use
  5948. * @param result defines the target matrix
  5949. */
  5950. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5951. var s = Math.sin(-angle);
  5952. var c = Math.cos(-angle);
  5953. var c1 = 1 - c;
  5954. axis.normalize();
  5955. result.m[0] = (axis.x * axis.x) * c1 + c;
  5956. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5957. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5958. result.m[3] = 0.0;
  5959. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5960. result.m[5] = (axis.y * axis.y) * c1 + c;
  5961. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5962. result.m[7] = 0.0;
  5963. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5964. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5965. result.m[10] = (axis.z * axis.z) * c1 + c;
  5966. result.m[11] = 0.0;
  5967. result.m[15] = 1.0;
  5968. result._markAsUpdated();
  5969. };
  5970. /**
  5971. * Creates a rotation matrix
  5972. * @param yaw defines the yaw angle in radians (Y axis)
  5973. * @param pitch defines the pitch angle in radians (X axis)
  5974. * @param roll defines the roll angle in radians (X axis)
  5975. * @returns the new rotation matrix
  5976. */
  5977. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5978. var result = new Matrix();
  5979. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5980. return result;
  5981. };
  5982. /**
  5983. * Creates a rotation matrix and stores it in a given matrix
  5984. * @param yaw defines the yaw angle in radians (Y axis)
  5985. * @param pitch defines the pitch angle in radians (X axis)
  5986. * @param roll defines the roll angle in radians (X axis)
  5987. * @param result defines the target matrix
  5988. */
  5989. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5990. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5991. this._tempQuaternion.toRotationMatrix(result);
  5992. };
  5993. /**
  5994. * Creates a scaling matrix
  5995. * @param x defines the scale factor on X axis
  5996. * @param y defines the scale factor on Y axis
  5997. * @param z defines the scale factor on Z axis
  5998. * @returns the new matrix
  5999. */
  6000. Matrix.Scaling = function (x, y, z) {
  6001. var result = Matrix.Zero();
  6002. Matrix.ScalingToRef(x, y, z, result);
  6003. return result;
  6004. };
  6005. /**
  6006. * Creates a scaling matrix and stores it in a given matrix
  6007. * @param x defines the scale factor on X axis
  6008. * @param y defines the scale factor on Y axis
  6009. * @param z defines the scale factor on Z axis
  6010. * @param result defines the target matrix
  6011. */
  6012. Matrix.ScalingToRef = function (x, y, z, result) {
  6013. result.m[0] = x;
  6014. result.m[1] = 0.0;
  6015. result.m[2] = 0.0;
  6016. result.m[3] = 0.0;
  6017. result.m[4] = 0.0;
  6018. result.m[5] = y;
  6019. result.m[6] = 0.0;
  6020. result.m[7] = 0.0;
  6021. result.m[8] = 0.0;
  6022. result.m[9] = 0.0;
  6023. result.m[10] = z;
  6024. result.m[11] = 0.0;
  6025. result.m[12] = 0.0;
  6026. result.m[13] = 0.0;
  6027. result.m[14] = 0.0;
  6028. result.m[15] = 1.0;
  6029. result._markAsUpdated();
  6030. };
  6031. /**
  6032. * Creates a translation matrix
  6033. * @param x defines the translation on X axis
  6034. * @param y defines the translation on Y axis
  6035. * @param z defines the translationon Z axis
  6036. * @returns the new matrix
  6037. */
  6038. Matrix.Translation = function (x, y, z) {
  6039. var result = Matrix.Identity();
  6040. Matrix.TranslationToRef(x, y, z, result);
  6041. return result;
  6042. };
  6043. /**
  6044. * Creates a translation matrix and stores it in a given matrix
  6045. * @param x defines the translation on X axis
  6046. * @param y defines the translation on Y axis
  6047. * @param z defines the translationon Z axis
  6048. * @param result defines the target matrix
  6049. */
  6050. Matrix.TranslationToRef = function (x, y, z, result) {
  6051. 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);
  6052. };
  6053. /**
  6054. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6055. * @param startValue defines the start value
  6056. * @param endValue defines the end value
  6057. * @param gradient defines the gradient factor
  6058. * @returns the new matrix
  6059. */
  6060. Matrix.Lerp = function (startValue, endValue, gradient) {
  6061. var result = Matrix.Zero();
  6062. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6063. return result;
  6064. };
  6065. /**
  6066. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6067. * @param startValue defines the start value
  6068. * @param endValue defines the end value
  6069. * @param gradient defines the gradient factor
  6070. * @param result defines the Matrix object where to store data
  6071. */
  6072. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6073. for (var index = 0; index < 16; index++) {
  6074. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6075. }
  6076. result._markAsUpdated();
  6077. };
  6078. /**
  6079. * Builds a new matrix whose values are computed by:
  6080. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6081. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6082. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6083. * @param startValue defines the first matrix
  6084. * @param endValue defines the second matrix
  6085. * @param gradient defines the gradient between the two matrices
  6086. * @returns the new matrix
  6087. */
  6088. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6089. var result = Matrix.Zero();
  6090. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6091. return result;
  6092. };
  6093. /**
  6094. * Update a matrix to values which are computed by:
  6095. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6096. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6097. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6098. * @param startValue defines the first matrix
  6099. * @param endValue defines the second matrix
  6100. * @param gradient defines the gradient between the two matrices
  6101. * @param result defines the target matrix
  6102. */
  6103. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6104. var startScale = MathTmp.Vector3[0];
  6105. var startRotation = MathTmp.Quaternion[0];
  6106. var startTranslation = MathTmp.Vector3[1];
  6107. startValue.decompose(startScale, startRotation, startTranslation);
  6108. var endScale = MathTmp.Vector3[2];
  6109. var endRotation = MathTmp.Quaternion[1];
  6110. var endTranslation = MathTmp.Vector3[3];
  6111. endValue.decompose(endScale, endRotation, endTranslation);
  6112. var resultScale = MathTmp.Vector3[4];
  6113. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6114. var resultRotation = MathTmp.Quaternion[2];
  6115. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6116. var resultTranslation = MathTmp.Vector3[5];
  6117. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6118. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6119. };
  6120. /**
  6121. * 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"
  6122. * This function works in left handed mode
  6123. * @param eye defines the final position of the entity
  6124. * @param target defines where the entity should look at
  6125. * @param up defines the up vector for the entity
  6126. * @returns the new matrix
  6127. */
  6128. Matrix.LookAtLH = function (eye, target, up) {
  6129. var result = Matrix.Zero();
  6130. Matrix.LookAtLHToRef(eye, target, up, result);
  6131. return result;
  6132. };
  6133. /**
  6134. * 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".
  6135. * This function works in left handed mode
  6136. * @param eye defines the final position of the entity
  6137. * @param target defines where the entity should look at
  6138. * @param up defines the up vector for the entity
  6139. * @param result defines the target matrix
  6140. */
  6141. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6142. // Z axis
  6143. target.subtractToRef(eye, this._zAxis);
  6144. this._zAxis.normalize();
  6145. // X axis
  6146. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6147. if (this._xAxis.lengthSquared() === 0) {
  6148. this._xAxis.x = 1.0;
  6149. }
  6150. else {
  6151. this._xAxis.normalize();
  6152. }
  6153. // Y axis
  6154. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6155. this._yAxis.normalize();
  6156. // Eye angles
  6157. var ex = -Vector3.Dot(this._xAxis, eye);
  6158. var ey = -Vector3.Dot(this._yAxis, eye);
  6159. var ez = -Vector3.Dot(this._zAxis, eye);
  6160. 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);
  6161. };
  6162. /**
  6163. * 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"
  6164. * This function works in right handed mode
  6165. * @param eye defines the final position of the entity
  6166. * @param target defines where the entity should look at
  6167. * @param up defines the up vector for the entity
  6168. * @returns the new matrix
  6169. */
  6170. Matrix.LookAtRH = function (eye, target, up) {
  6171. var result = Matrix.Zero();
  6172. Matrix.LookAtRHToRef(eye, target, up, result);
  6173. return result;
  6174. };
  6175. /**
  6176. * 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".
  6177. * This function works in right handed mode
  6178. * @param eye defines the final position of the entity
  6179. * @param target defines where the entity should look at
  6180. * @param up defines the up vector for the entity
  6181. * @param result defines the target matrix
  6182. */
  6183. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6184. // Z axis
  6185. eye.subtractToRef(target, this._zAxis);
  6186. this._zAxis.normalize();
  6187. // X axis
  6188. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6189. if (this._xAxis.lengthSquared() === 0) {
  6190. this._xAxis.x = 1.0;
  6191. }
  6192. else {
  6193. this._xAxis.normalize();
  6194. }
  6195. // Y axis
  6196. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6197. this._yAxis.normalize();
  6198. // Eye angles
  6199. var ex = -Vector3.Dot(this._xAxis, eye);
  6200. var ey = -Vector3.Dot(this._yAxis, eye);
  6201. var ez = -Vector3.Dot(this._zAxis, eye);
  6202. 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);
  6203. };
  6204. /**
  6205. * Create a left-handed orthographic projection matrix
  6206. * @param width defines the viewport width
  6207. * @param height defines the viewport height
  6208. * @param znear defines the near clip plane
  6209. * @param zfar defines the far clip plane
  6210. * @returns a new matrix as a left-handed orthographic projection matrix
  6211. */
  6212. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6213. var matrix = Matrix.Zero();
  6214. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6215. return matrix;
  6216. };
  6217. /**
  6218. * Store a left-handed orthographic projection to a given matrix
  6219. * @param width defines the viewport width
  6220. * @param height defines the viewport height
  6221. * @param znear defines the near clip plane
  6222. * @param zfar defines the far clip plane
  6223. * @param result defines the target matrix
  6224. */
  6225. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6226. var n = znear;
  6227. var f = zfar;
  6228. var a = 2.0 / width;
  6229. var b = 2.0 / height;
  6230. var c = 2.0 / (f - n);
  6231. var d = -(f + n) / (f - n);
  6232. 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);
  6233. };
  6234. /**
  6235. * Create a left-handed orthographic projection matrix
  6236. * @param left defines the viewport left coordinate
  6237. * @param right defines the viewport right coordinate
  6238. * @param bottom defines the viewport bottom coordinate
  6239. * @param top defines the viewport top coordinate
  6240. * @param znear defines the near clip plane
  6241. * @param zfar defines the far clip plane
  6242. * @returns a new matrix as a left-handed orthographic projection matrix
  6243. */
  6244. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6245. var matrix = Matrix.Zero();
  6246. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6247. return matrix;
  6248. };
  6249. /**
  6250. * Stores a left-handed orthographic projection into a given matrix
  6251. * @param left defines the viewport left coordinate
  6252. * @param right defines the viewport right coordinate
  6253. * @param bottom defines the viewport bottom coordinate
  6254. * @param top defines the viewport top coordinate
  6255. * @param znear defines the near clip plane
  6256. * @param zfar defines the far clip plane
  6257. * @param result defines the target matrix
  6258. */
  6259. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6260. var n = znear;
  6261. var f = zfar;
  6262. var a = 2.0 / (right - left);
  6263. var b = 2.0 / (top - bottom);
  6264. var c = 2.0 / (f - n);
  6265. var d = -(f + n) / (f - n);
  6266. var i0 = (left + right) / (left - right);
  6267. var i1 = (top + bottom) / (bottom - top);
  6268. 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);
  6269. };
  6270. /**
  6271. * Creates a right-handed orthographic projection matrix
  6272. * @param left defines the viewport left coordinate
  6273. * @param right defines the viewport right coordinate
  6274. * @param bottom defines the viewport bottom coordinate
  6275. * @param top defines the viewport top coordinate
  6276. * @param znear defines the near clip plane
  6277. * @param zfar defines the far clip plane
  6278. * @returns a new matrix as a right-handed orthographic projection matrix
  6279. */
  6280. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6281. var matrix = Matrix.Zero();
  6282. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6283. return matrix;
  6284. };
  6285. /**
  6286. * Stores a right-handed orthographic projection into a given matrix
  6287. * @param left defines the viewport left coordinate
  6288. * @param right defines the viewport right coordinate
  6289. * @param bottom defines the viewport bottom coordinate
  6290. * @param top defines the viewport top coordinate
  6291. * @param znear defines the near clip plane
  6292. * @param zfar defines the far clip plane
  6293. * @param result defines the target matrix
  6294. */
  6295. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6296. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6297. result.m[10] *= -1.0;
  6298. };
  6299. /**
  6300. * Creates a left-handed perspective projection matrix
  6301. * @param width defines the viewport width
  6302. * @param height defines the viewport height
  6303. * @param znear defines the near clip plane
  6304. * @param zfar defines the far clip plane
  6305. * @returns a new matrix as a left-handed perspective projection matrix
  6306. */
  6307. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6308. var matrix = Matrix.Zero();
  6309. var n = znear;
  6310. var f = zfar;
  6311. var a = 2.0 * n / width;
  6312. var b = 2.0 * n / height;
  6313. var c = (f + n) / (f - n);
  6314. var d = -2.0 * f * n / (f - n);
  6315. 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);
  6316. return matrix;
  6317. };
  6318. /**
  6319. * Creates a left-handed perspective projection matrix
  6320. * @param fov defines the horizontal field of view
  6321. * @param aspect defines the aspect ratio
  6322. * @param znear defines the near clip plane
  6323. * @param zfar defines the far clip plane
  6324. * @returns a new matrix as a left-handed perspective projection matrix
  6325. */
  6326. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6327. var matrix = Matrix.Zero();
  6328. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6329. return matrix;
  6330. };
  6331. /**
  6332. * Stores a left-handed perspective projection into a given matrix
  6333. * @param fov defines the horizontal field of view
  6334. * @param aspect defines the aspect ratio
  6335. * @param znear defines the near clip plane
  6336. * @param zfar defines the far clip plane
  6337. * @param result defines the target matrix
  6338. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6339. */
  6340. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6341. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6342. var n = znear;
  6343. var f = zfar;
  6344. var t = 1.0 / (Math.tan(fov * 0.5));
  6345. var a = isVerticalFovFixed ? (t / aspect) : t;
  6346. var b = isVerticalFovFixed ? t : (t * aspect);
  6347. var c = (f + n) / (f - n);
  6348. var d = -2.0 * f * n / (f - n);
  6349. 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);
  6350. };
  6351. /**
  6352. * Creates a right-handed perspective projection matrix
  6353. * @param fov defines the horizontal field of view
  6354. * @param aspect defines the aspect ratio
  6355. * @param znear defines the near clip plane
  6356. * @param zfar defines the far clip plane
  6357. * @returns a new matrix as a right-handed perspective projection matrix
  6358. */
  6359. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6360. var matrix = Matrix.Zero();
  6361. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6362. return matrix;
  6363. };
  6364. /**
  6365. * Stores a right-handed perspective projection into a given matrix
  6366. * @param fov defines the horizontal field of view
  6367. * @param aspect defines the aspect ratio
  6368. * @param znear defines the near clip plane
  6369. * @param zfar defines the far clip plane
  6370. * @param result defines the target matrix
  6371. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6372. */
  6373. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6374. //alternatively this could be expressed as:
  6375. // m = PerspectiveFovLHToRef
  6376. // m[10] *= -1.0;
  6377. // m[11] *= -1.0;
  6378. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6379. var n = znear;
  6380. var f = zfar;
  6381. var t = 1.0 / (Math.tan(fov * 0.5));
  6382. var a = isVerticalFovFixed ? (t / aspect) : t;
  6383. var b = isVerticalFovFixed ? t : (t * aspect);
  6384. var c = -(f + n) / (f - n);
  6385. var d = -2 * f * n / (f - n);
  6386. 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);
  6387. };
  6388. /**
  6389. * Stores a perspective projection for WebVR info a given matrix
  6390. * @param fov defines the field of view
  6391. * @param znear defines the near clip plane
  6392. * @param zfar defines the far clip plane
  6393. * @param result defines the target matrix
  6394. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6395. */
  6396. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6397. if (rightHanded === void 0) { rightHanded = false; }
  6398. var rightHandedFactor = rightHanded ? -1 : 1;
  6399. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6400. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6401. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6402. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6403. var xScale = 2.0 / (leftTan + rightTan);
  6404. var yScale = 2.0 / (upTan + downTan);
  6405. result.m[0] = xScale;
  6406. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6407. result.m[5] = yScale;
  6408. result.m[6] = result.m[7] = 0.0;
  6409. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6410. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6411. result.m[10] = -zfar / (znear - zfar);
  6412. result.m[11] = 1.0 * rightHandedFactor;
  6413. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6414. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6415. result._markAsUpdated();
  6416. };
  6417. /**
  6418. * Computes a complete transformation matrix
  6419. * @param viewport defines the viewport to use
  6420. * @param world defines the world matrix
  6421. * @param view defines the view matrix
  6422. * @param projection defines the projection matrix
  6423. * @param zmin defines the near clip plane
  6424. * @param zmax defines the far clip plane
  6425. * @returns the transformation matrix
  6426. */
  6427. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6428. var cw = viewport.width;
  6429. var ch = viewport.height;
  6430. var cx = viewport.x;
  6431. var cy = viewport.y;
  6432. 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);
  6433. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6434. };
  6435. /**
  6436. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6437. * @param matrix defines the matrix to use
  6438. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6439. */
  6440. Matrix.GetAsMatrix2x2 = function (matrix) {
  6441. return new Float32Array([
  6442. matrix.m[0], matrix.m[1],
  6443. matrix.m[4], matrix.m[5]
  6444. ]);
  6445. };
  6446. /**
  6447. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6448. * @param matrix defines the matrix to use
  6449. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6450. */
  6451. Matrix.GetAsMatrix3x3 = function (matrix) {
  6452. return new Float32Array([
  6453. matrix.m[0], matrix.m[1], matrix.m[2],
  6454. matrix.m[4], matrix.m[5], matrix.m[6],
  6455. matrix.m[8], matrix.m[9], matrix.m[10]
  6456. ]);
  6457. };
  6458. /**
  6459. * Compute the transpose of a given matrix
  6460. * @param matrix defines the matrix to transpose
  6461. * @returns the new matrix
  6462. */
  6463. Matrix.Transpose = function (matrix) {
  6464. var result = new Matrix();
  6465. Matrix.TransposeToRef(matrix, result);
  6466. return result;
  6467. };
  6468. /**
  6469. * Compute the transpose of a matrix and store it in a target matrix
  6470. * @param matrix defines the matrix to transpose
  6471. * @param result defines the target matrix
  6472. */
  6473. Matrix.TransposeToRef = function (matrix, result) {
  6474. result.m[0] = matrix.m[0];
  6475. result.m[1] = matrix.m[4];
  6476. result.m[2] = matrix.m[8];
  6477. result.m[3] = matrix.m[12];
  6478. result.m[4] = matrix.m[1];
  6479. result.m[5] = matrix.m[5];
  6480. result.m[6] = matrix.m[9];
  6481. result.m[7] = matrix.m[13];
  6482. result.m[8] = matrix.m[2];
  6483. result.m[9] = matrix.m[6];
  6484. result.m[10] = matrix.m[10];
  6485. result.m[11] = matrix.m[14];
  6486. result.m[12] = matrix.m[3];
  6487. result.m[13] = matrix.m[7];
  6488. result.m[14] = matrix.m[11];
  6489. result.m[15] = matrix.m[15];
  6490. };
  6491. /**
  6492. * Computes a reflection matrix from a plane
  6493. * @param plane defines the reflection plane
  6494. * @returns a new matrix
  6495. */
  6496. Matrix.Reflection = function (plane) {
  6497. var matrix = new Matrix();
  6498. Matrix.ReflectionToRef(plane, matrix);
  6499. return matrix;
  6500. };
  6501. /**
  6502. * Computes a reflection matrix from a plane
  6503. * @param plane defines the reflection plane
  6504. * @param result defines the target matrix
  6505. */
  6506. Matrix.ReflectionToRef = function (plane, result) {
  6507. plane.normalize();
  6508. var x = plane.normal.x;
  6509. var y = plane.normal.y;
  6510. var z = plane.normal.z;
  6511. var temp = -2 * x;
  6512. var temp2 = -2 * y;
  6513. var temp3 = -2 * z;
  6514. result.m[0] = (temp * x) + 1;
  6515. result.m[1] = temp2 * x;
  6516. result.m[2] = temp3 * x;
  6517. result.m[3] = 0.0;
  6518. result.m[4] = temp * y;
  6519. result.m[5] = (temp2 * y) + 1;
  6520. result.m[6] = temp3 * y;
  6521. result.m[7] = 0.0;
  6522. result.m[8] = temp * z;
  6523. result.m[9] = temp2 * z;
  6524. result.m[10] = (temp3 * z) + 1;
  6525. result.m[11] = 0.0;
  6526. result.m[12] = temp * plane.d;
  6527. result.m[13] = temp2 * plane.d;
  6528. result.m[14] = temp3 * plane.d;
  6529. result.m[15] = 1.0;
  6530. result._markAsUpdated();
  6531. };
  6532. /**
  6533. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6534. * @param xaxis defines the value of the 1st axis
  6535. * @param yaxis defines the value of the 2nd axis
  6536. * @param zaxis defines the value of the 3rd axis
  6537. * @param result defines the target matrix
  6538. */
  6539. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6540. result.m[0] = xaxis.x;
  6541. result.m[1] = xaxis.y;
  6542. result.m[2] = xaxis.z;
  6543. result.m[3] = 0.0;
  6544. result.m[4] = yaxis.x;
  6545. result.m[5] = yaxis.y;
  6546. result.m[6] = yaxis.z;
  6547. result.m[7] = 0.0;
  6548. result.m[8] = zaxis.x;
  6549. result.m[9] = zaxis.y;
  6550. result.m[10] = zaxis.z;
  6551. result.m[11] = 0.0;
  6552. result.m[12] = 0.0;
  6553. result.m[13] = 0.0;
  6554. result.m[14] = 0.0;
  6555. result.m[15] = 1.0;
  6556. result._markAsUpdated();
  6557. };
  6558. /**
  6559. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6560. * @param quat defines the quaternion to use
  6561. * @param result defines the target matrix
  6562. */
  6563. Matrix.FromQuaternionToRef = function (quat, result) {
  6564. var xx = quat.x * quat.x;
  6565. var yy = quat.y * quat.y;
  6566. var zz = quat.z * quat.z;
  6567. var xy = quat.x * quat.y;
  6568. var zw = quat.z * quat.w;
  6569. var zx = quat.z * quat.x;
  6570. var yw = quat.y * quat.w;
  6571. var yz = quat.y * quat.z;
  6572. var xw = quat.x * quat.w;
  6573. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6574. result.m[1] = 2.0 * (xy + zw);
  6575. result.m[2] = 2.0 * (zx - yw);
  6576. result.m[3] = 0.0;
  6577. result.m[4] = 2.0 * (xy - zw);
  6578. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6579. result.m[6] = 2.0 * (yz + xw);
  6580. result.m[7] = 0.0;
  6581. result.m[8] = 2.0 * (zx + yw);
  6582. result.m[9] = 2.0 * (yz - xw);
  6583. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6584. result.m[11] = 0.0;
  6585. result.m[12] = 0.0;
  6586. result.m[13] = 0.0;
  6587. result.m[14] = 0.0;
  6588. result.m[15] = 1.0;
  6589. result._markAsUpdated();
  6590. };
  6591. Matrix._tempQuaternion = new Quaternion();
  6592. Matrix._xAxis = Vector3.Zero();
  6593. Matrix._yAxis = Vector3.Zero();
  6594. Matrix._zAxis = Vector3.Zero();
  6595. Matrix._updateFlagSeed = 0;
  6596. Matrix._identityReadOnly = Matrix.Identity();
  6597. return Matrix;
  6598. }());
  6599. BABYLON.Matrix = Matrix;
  6600. var Plane = /** @class */ (function () {
  6601. /**
  6602. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6603. */
  6604. function Plane(a, b, c, d) {
  6605. this.normal = new Vector3(a, b, c);
  6606. this.d = d;
  6607. }
  6608. /**
  6609. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6610. */
  6611. Plane.prototype.asArray = function () {
  6612. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6613. };
  6614. // Methods
  6615. /**
  6616. * Returns a new plane copied from the current Plane.
  6617. */
  6618. Plane.prototype.clone = function () {
  6619. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6620. };
  6621. /**
  6622. * Returns the string "Plane".
  6623. */
  6624. Plane.prototype.getClassName = function () {
  6625. return "Plane";
  6626. };
  6627. /**
  6628. * Returns the Plane hash code.
  6629. */
  6630. Plane.prototype.getHashCode = function () {
  6631. var hash = this.normal.getHashCode();
  6632. hash = (hash * 397) ^ (this.d || 0);
  6633. return hash;
  6634. };
  6635. /**
  6636. * Normalize the current Plane in place.
  6637. * Returns the updated Plane.
  6638. */
  6639. Plane.prototype.normalize = function () {
  6640. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6641. var magnitude = 0.0;
  6642. if (norm !== 0) {
  6643. magnitude = 1.0 / norm;
  6644. }
  6645. this.normal.x *= magnitude;
  6646. this.normal.y *= magnitude;
  6647. this.normal.z *= magnitude;
  6648. this.d *= magnitude;
  6649. return this;
  6650. };
  6651. /**
  6652. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6653. */
  6654. Plane.prototype.transform = function (transformation) {
  6655. var transposedMatrix = Matrix.Transpose(transformation);
  6656. var x = this.normal.x;
  6657. var y = this.normal.y;
  6658. var z = this.normal.z;
  6659. var d = this.d;
  6660. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6661. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6662. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6663. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6664. return new Plane(normalX, normalY, normalZ, finalD);
  6665. };
  6666. /**
  6667. * Returns the dot product (float) of the point coordinates and the plane normal.
  6668. */
  6669. Plane.prototype.dotCoordinate = function (point) {
  6670. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6671. };
  6672. /**
  6673. * Updates the current Plane from the plane defined by the three given points.
  6674. * Returns the updated Plane.
  6675. */
  6676. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6677. var x1 = point2.x - point1.x;
  6678. var y1 = point2.y - point1.y;
  6679. var z1 = point2.z - point1.z;
  6680. var x2 = point3.x - point1.x;
  6681. var y2 = point3.y - point1.y;
  6682. var z2 = point3.z - point1.z;
  6683. var yz = (y1 * z2) - (z1 * y2);
  6684. var xz = (z1 * x2) - (x1 * z2);
  6685. var xy = (x1 * y2) - (y1 * x2);
  6686. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6687. var invPyth;
  6688. if (pyth !== 0) {
  6689. invPyth = 1.0 / pyth;
  6690. }
  6691. else {
  6692. invPyth = 0.0;
  6693. }
  6694. this.normal.x = yz * invPyth;
  6695. this.normal.y = xz * invPyth;
  6696. this.normal.z = xy * invPyth;
  6697. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6698. return this;
  6699. };
  6700. /**
  6701. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6702. */
  6703. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6704. var dot = Vector3.Dot(this.normal, direction);
  6705. return (dot <= epsilon);
  6706. };
  6707. /**
  6708. * Returns the signed distance (float) from the given point to the Plane.
  6709. */
  6710. Plane.prototype.signedDistanceTo = function (point) {
  6711. return Vector3.Dot(point, this.normal) + this.d;
  6712. };
  6713. // Statics
  6714. /**
  6715. * Returns a new Plane from the given array.
  6716. */
  6717. Plane.FromArray = function (array) {
  6718. return new Plane(array[0], array[1], array[2], array[3]);
  6719. };
  6720. /**
  6721. * Returns a new Plane defined by the three given points.
  6722. */
  6723. Plane.FromPoints = function (point1, point2, point3) {
  6724. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6725. result.copyFromPoints(point1, point2, point3);
  6726. return result;
  6727. };
  6728. /**
  6729. * Returns a new Plane the normal vector to this plane at the given origin point.
  6730. * Note : the vector "normal" is updated because normalized.
  6731. */
  6732. Plane.FromPositionAndNormal = function (origin, normal) {
  6733. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6734. normal.normalize();
  6735. result.normal = normal;
  6736. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6737. return result;
  6738. };
  6739. /**
  6740. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6741. */
  6742. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6743. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6744. return Vector3.Dot(point, normal) + d;
  6745. };
  6746. return Plane;
  6747. }());
  6748. BABYLON.Plane = Plane;
  6749. var Viewport = /** @class */ (function () {
  6750. /**
  6751. * Creates a Viewport object located at (x, y) and sized (width, height).
  6752. */
  6753. function Viewport(x, y, width, height) {
  6754. this.x = x;
  6755. this.y = y;
  6756. this.width = width;
  6757. this.height = height;
  6758. }
  6759. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6760. if (renderWidthOrEngine.getRenderWidth) {
  6761. var engine = renderWidthOrEngine;
  6762. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6763. }
  6764. var renderWidth = renderWidthOrEngine;
  6765. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6766. };
  6767. /**
  6768. * Returns a new Viewport copied from the current one.
  6769. */
  6770. Viewport.prototype.clone = function () {
  6771. return new Viewport(this.x, this.y, this.width, this.height);
  6772. };
  6773. return Viewport;
  6774. }());
  6775. BABYLON.Viewport = Viewport;
  6776. var Frustum = /** @class */ (function () {
  6777. function Frustum() {
  6778. }
  6779. /**
  6780. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6781. */
  6782. Frustum.GetPlanes = function (transform) {
  6783. var frustumPlanes = [];
  6784. for (var index = 0; index < 6; index++) {
  6785. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6786. }
  6787. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6788. return frustumPlanes;
  6789. };
  6790. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6791. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6792. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6793. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6794. frustumPlane.d = transform.m[15] + transform.m[14];
  6795. frustumPlane.normalize();
  6796. };
  6797. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6798. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6799. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6800. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6801. frustumPlane.d = transform.m[15] - transform.m[14];
  6802. frustumPlane.normalize();
  6803. };
  6804. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6805. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6806. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6807. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6808. frustumPlane.d = transform.m[15] + transform.m[12];
  6809. frustumPlane.normalize();
  6810. };
  6811. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6812. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6813. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6814. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6815. frustumPlane.d = transform.m[15] - transform.m[12];
  6816. frustumPlane.normalize();
  6817. };
  6818. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6819. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6820. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6821. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6822. frustumPlane.d = transform.m[15] - transform.m[13];
  6823. frustumPlane.normalize();
  6824. };
  6825. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6826. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6827. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6828. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6829. frustumPlane.d = transform.m[15] + transform.m[13];
  6830. frustumPlane.normalize();
  6831. };
  6832. /**
  6833. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6834. */
  6835. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6836. // Near
  6837. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6838. // Far
  6839. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6840. // Left
  6841. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6842. // Right
  6843. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6844. // Top
  6845. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6846. // Bottom
  6847. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6848. };
  6849. return Frustum;
  6850. }());
  6851. BABYLON.Frustum = Frustum;
  6852. /** Defines supported spaces */
  6853. var Space;
  6854. (function (Space) {
  6855. /** Local (object) space */
  6856. Space[Space["LOCAL"] = 0] = "LOCAL";
  6857. /** World space */
  6858. Space[Space["WORLD"] = 1] = "WORLD";
  6859. /** Bone space */
  6860. Space[Space["BONE"] = 2] = "BONE";
  6861. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6862. /** Defines the 3 main axes */
  6863. var Axis = /** @class */ (function () {
  6864. function Axis() {
  6865. }
  6866. /** X axis */
  6867. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6868. /** Y axis */
  6869. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6870. /** Z axis */
  6871. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6872. return Axis;
  6873. }());
  6874. BABYLON.Axis = Axis;
  6875. ;
  6876. var BezierCurve = /** @class */ (function () {
  6877. function BezierCurve() {
  6878. }
  6879. /**
  6880. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6881. */
  6882. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6883. // Extract X (which is equal to time here)
  6884. var f0 = 1 - 3 * x2 + 3 * x1;
  6885. var f1 = 3 * x2 - 6 * x1;
  6886. var f2 = 3 * x1;
  6887. var refinedT = t;
  6888. for (var i = 0; i < 5; i++) {
  6889. var refinedT2 = refinedT * refinedT;
  6890. var refinedT3 = refinedT2 * refinedT;
  6891. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6892. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6893. refinedT -= (x - t) * slope;
  6894. refinedT = Math.min(1, Math.max(0, refinedT));
  6895. }
  6896. // Resolve cubic bezier for the given x
  6897. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6898. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6899. Math.pow(refinedT, 3);
  6900. };
  6901. return BezierCurve;
  6902. }());
  6903. BABYLON.BezierCurve = BezierCurve;
  6904. /**
  6905. * Defines potential orientation for back face culling
  6906. */
  6907. var Orientation;
  6908. (function (Orientation) {
  6909. /**
  6910. * Clockwise
  6911. */
  6912. Orientation[Orientation["CW"] = 0] = "CW";
  6913. /** Counter clockwise */
  6914. Orientation[Orientation["CCW"] = 1] = "CCW";
  6915. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6916. /**
  6917. * Defines angle representation
  6918. */
  6919. var Angle = /** @class */ (function () {
  6920. /**
  6921. * Creates an Angle object of "radians" radians (float).
  6922. */
  6923. function Angle(radians) {
  6924. this._radians = radians;
  6925. if (this._radians < 0.0)
  6926. this._radians += (2.0 * Math.PI);
  6927. }
  6928. /**
  6929. * Get value in degrees
  6930. * @returns the Angle value in degrees (float)
  6931. */
  6932. Angle.prototype.degrees = function () {
  6933. return this._radians * 180.0 / Math.PI;
  6934. };
  6935. /**
  6936. * Get value in radians
  6937. * @returns the Angle value in radians (float)
  6938. */
  6939. Angle.prototype.radians = function () {
  6940. return this._radians;
  6941. };
  6942. /**
  6943. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6944. * @param a defines first vector
  6945. * @param b defines second vector
  6946. * @returns a new Angle
  6947. */
  6948. Angle.BetweenTwoPoints = function (a, b) {
  6949. var delta = b.subtract(a);
  6950. var theta = Math.atan2(delta.y, delta.x);
  6951. return new Angle(theta);
  6952. };
  6953. /**
  6954. * Gets a new Angle object from the given float in radians
  6955. * @param radians defines the angle value in radians
  6956. * @returns a new Angle
  6957. */
  6958. Angle.FromRadians = function (radians) {
  6959. return new Angle(radians);
  6960. };
  6961. /**
  6962. * Gets a new Angle object from the given float in degrees
  6963. * @param degrees defines the angle value in degrees
  6964. * @returns a new Angle
  6965. */
  6966. Angle.FromDegrees = function (degrees) {
  6967. return new Angle(degrees * Math.PI / 180.0);
  6968. };
  6969. return Angle;
  6970. }());
  6971. BABYLON.Angle = Angle;
  6972. var Arc2 = /** @class */ (function () {
  6973. /**
  6974. * Creates an Arc object from the three given points : start, middle and end.
  6975. */
  6976. function Arc2(startPoint, midPoint, endPoint) {
  6977. this.startPoint = startPoint;
  6978. this.midPoint = midPoint;
  6979. this.endPoint = endPoint;
  6980. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6981. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6982. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6983. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6984. 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);
  6985. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6986. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6987. var a1 = this.startAngle.degrees();
  6988. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6989. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6990. // angles correction
  6991. if (a2 - a1 > +180.0)
  6992. a2 -= 360.0;
  6993. if (a2 - a1 < -180.0)
  6994. a2 += 360.0;
  6995. if (a3 - a2 > +180.0)
  6996. a3 -= 360.0;
  6997. if (a3 - a2 < -180.0)
  6998. a3 += 360.0;
  6999. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7000. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7001. }
  7002. return Arc2;
  7003. }());
  7004. BABYLON.Arc2 = Arc2;
  7005. var Path2 = /** @class */ (function () {
  7006. /**
  7007. * Creates a Path2 object from the starting 2D coordinates x and y.
  7008. */
  7009. function Path2(x, y) {
  7010. this._points = new Array();
  7011. this._length = 0.0;
  7012. this.closed = false;
  7013. this._points.push(new Vector2(x, y));
  7014. }
  7015. /**
  7016. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7017. * Returns the updated Path2.
  7018. */
  7019. Path2.prototype.addLineTo = function (x, y) {
  7020. if (this.closed) {
  7021. return this;
  7022. }
  7023. var newPoint = new Vector2(x, y);
  7024. var previousPoint = this._points[this._points.length - 1];
  7025. this._points.push(newPoint);
  7026. this._length += newPoint.subtract(previousPoint).length();
  7027. return this;
  7028. };
  7029. /**
  7030. * 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.
  7031. * Returns the updated Path2.
  7032. */
  7033. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7034. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7035. if (this.closed) {
  7036. return this;
  7037. }
  7038. var startPoint = this._points[this._points.length - 1];
  7039. var midPoint = new Vector2(midX, midY);
  7040. var endPoint = new Vector2(endX, endY);
  7041. var arc = new Arc2(startPoint, midPoint, endPoint);
  7042. var increment = arc.angle.radians() / numberOfSegments;
  7043. if (arc.orientation === Orientation.CW)
  7044. increment *= -1;
  7045. var currentAngle = arc.startAngle.radians() + increment;
  7046. for (var i = 0; i < numberOfSegments; i++) {
  7047. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7048. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7049. this.addLineTo(x, y);
  7050. currentAngle += increment;
  7051. }
  7052. return this;
  7053. };
  7054. /**
  7055. * Closes the Path2.
  7056. * Returns the Path2.
  7057. */
  7058. Path2.prototype.close = function () {
  7059. this.closed = true;
  7060. return this;
  7061. };
  7062. /**
  7063. * Returns the Path2 total length (float).
  7064. */
  7065. Path2.prototype.length = function () {
  7066. var result = this._length;
  7067. if (!this.closed) {
  7068. var lastPoint = this._points[this._points.length - 1];
  7069. var firstPoint = this._points[0];
  7070. result += (firstPoint.subtract(lastPoint).length());
  7071. }
  7072. return result;
  7073. };
  7074. /**
  7075. * Returns the Path2 internal array of points.
  7076. */
  7077. Path2.prototype.getPoints = function () {
  7078. return this._points;
  7079. };
  7080. /**
  7081. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7082. */
  7083. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7084. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7085. return Vector2.Zero();
  7086. }
  7087. var lengthPosition = normalizedLengthPosition * this.length();
  7088. var previousOffset = 0;
  7089. for (var i = 0; i < this._points.length; i++) {
  7090. var j = (i + 1) % this._points.length;
  7091. var a = this._points[i];
  7092. var b = this._points[j];
  7093. var bToA = b.subtract(a);
  7094. var nextOffset = (bToA.length() + previousOffset);
  7095. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7096. var dir = bToA.normalize();
  7097. var localOffset = lengthPosition - previousOffset;
  7098. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7099. }
  7100. previousOffset = nextOffset;
  7101. }
  7102. return Vector2.Zero();
  7103. };
  7104. /**
  7105. * Returns a new Path2 starting at the coordinates (x, y).
  7106. */
  7107. Path2.StartingAt = function (x, y) {
  7108. return new Path2(x, y);
  7109. };
  7110. return Path2;
  7111. }());
  7112. BABYLON.Path2 = Path2;
  7113. var Path3D = /** @class */ (function () {
  7114. /**
  7115. * new Path3D(path, normal, raw)
  7116. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7117. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7118. * path : an array of Vector3, the curve axis of the Path3D
  7119. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7120. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7121. */
  7122. function Path3D(path, firstNormal, raw) {
  7123. if (firstNormal === void 0) { firstNormal = null; }
  7124. this.path = path;
  7125. this._curve = new Array();
  7126. this._distances = new Array();
  7127. this._tangents = new Array();
  7128. this._normals = new Array();
  7129. this._binormals = new Array();
  7130. for (var p = 0; p < path.length; p++) {
  7131. this._curve[p] = path[p].clone(); // hard copy
  7132. }
  7133. this._raw = raw || false;
  7134. this._compute(firstNormal);
  7135. }
  7136. /**
  7137. * Returns the Path3D array of successive Vector3 designing its curve.
  7138. */
  7139. Path3D.prototype.getCurve = function () {
  7140. return this._curve;
  7141. };
  7142. /**
  7143. * Returns an array populated with tangent vectors on each Path3D curve point.
  7144. */
  7145. Path3D.prototype.getTangents = function () {
  7146. return this._tangents;
  7147. };
  7148. /**
  7149. * Returns an array populated with normal vectors on each Path3D curve point.
  7150. */
  7151. Path3D.prototype.getNormals = function () {
  7152. return this._normals;
  7153. };
  7154. /**
  7155. * Returns an array populated with binormal vectors on each Path3D curve point.
  7156. */
  7157. Path3D.prototype.getBinormals = function () {
  7158. return this._binormals;
  7159. };
  7160. /**
  7161. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7162. */
  7163. Path3D.prototype.getDistances = function () {
  7164. return this._distances;
  7165. };
  7166. /**
  7167. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7168. * Returns the same object updated.
  7169. */
  7170. Path3D.prototype.update = function (path, firstNormal) {
  7171. if (firstNormal === void 0) { firstNormal = null; }
  7172. for (var p = 0; p < path.length; p++) {
  7173. this._curve[p].x = path[p].x;
  7174. this._curve[p].y = path[p].y;
  7175. this._curve[p].z = path[p].z;
  7176. }
  7177. this._compute(firstNormal);
  7178. return this;
  7179. };
  7180. // private function compute() : computes tangents, normals and binormals
  7181. Path3D.prototype._compute = function (firstNormal) {
  7182. var l = this._curve.length;
  7183. // first and last tangents
  7184. this._tangents[0] = this._getFirstNonNullVector(0);
  7185. if (!this._raw) {
  7186. this._tangents[0].normalize();
  7187. }
  7188. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7189. if (!this._raw) {
  7190. this._tangents[l - 1].normalize();
  7191. }
  7192. // normals and binormals at first point : arbitrary vector with _normalVector()
  7193. var tg0 = this._tangents[0];
  7194. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7195. this._normals[0] = pp0;
  7196. if (!this._raw) {
  7197. this._normals[0].normalize();
  7198. }
  7199. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7200. if (!this._raw) {
  7201. this._binormals[0].normalize();
  7202. }
  7203. this._distances[0] = 0.0;
  7204. // normals and binormals : next points
  7205. var prev; // previous vector (segment)
  7206. var cur; // current vector (segment)
  7207. var curTang; // current tangent
  7208. // previous normal
  7209. var prevBinor; // previous binormal
  7210. for (var i = 1; i < l; i++) {
  7211. // tangents
  7212. prev = this._getLastNonNullVector(i);
  7213. if (i < l - 1) {
  7214. cur = this._getFirstNonNullVector(i);
  7215. this._tangents[i] = prev.add(cur);
  7216. this._tangents[i].normalize();
  7217. }
  7218. this._distances[i] = this._distances[i - 1] + prev.length();
  7219. // normals and binormals
  7220. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7221. curTang = this._tangents[i];
  7222. prevBinor = this._binormals[i - 1];
  7223. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7224. if (!this._raw) {
  7225. this._normals[i].normalize();
  7226. }
  7227. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7228. if (!this._raw) {
  7229. this._binormals[i].normalize();
  7230. }
  7231. }
  7232. };
  7233. // private function getFirstNonNullVector(index)
  7234. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7235. Path3D.prototype._getFirstNonNullVector = function (index) {
  7236. var i = 1;
  7237. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7238. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7239. i++;
  7240. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7241. }
  7242. return nNVector;
  7243. };
  7244. // private function getLastNonNullVector(index)
  7245. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7246. Path3D.prototype._getLastNonNullVector = function (index) {
  7247. var i = 1;
  7248. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7249. while (nLVector.length() === 0 && index > i + 1) {
  7250. i++;
  7251. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7252. }
  7253. return nLVector;
  7254. };
  7255. // private function normalVector(v0, vt, va) :
  7256. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7257. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7258. Path3D.prototype._normalVector = function (v0, vt, va) {
  7259. var normal0;
  7260. var tgl = vt.length();
  7261. if (tgl === 0.0) {
  7262. tgl = 1.0;
  7263. }
  7264. if (va === undefined || va === null) {
  7265. var point;
  7266. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7267. point = new Vector3(0.0, -1.0, 0.0);
  7268. }
  7269. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7270. point = new Vector3(1.0, 0.0, 0.0);
  7271. }
  7272. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7273. point = new Vector3(0.0, 0.0, 1.0);
  7274. }
  7275. else {
  7276. point = Vector3.Zero();
  7277. }
  7278. normal0 = Vector3.Cross(vt, point);
  7279. }
  7280. else {
  7281. normal0 = Vector3.Cross(vt, va);
  7282. Vector3.CrossToRef(normal0, vt, normal0);
  7283. }
  7284. normal0.normalize();
  7285. return normal0;
  7286. };
  7287. return Path3D;
  7288. }());
  7289. BABYLON.Path3D = Path3D;
  7290. var Curve3 = /** @class */ (function () {
  7291. /**
  7292. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7293. * A Curve3 is designed from a series of successive Vector3.
  7294. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7295. */
  7296. function Curve3(points) {
  7297. this._length = 0.0;
  7298. this._points = points;
  7299. this._length = this._computeLength(points);
  7300. }
  7301. /**
  7302. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7303. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7304. * @param v1 (Vector3) the control point
  7305. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7306. * @param nbPoints (integer) the wanted number of points in the curve
  7307. */
  7308. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7309. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7310. var bez = new Array();
  7311. var equation = function (t, val0, val1, val2) {
  7312. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7313. return res;
  7314. };
  7315. for (var i = 0; i <= nbPoints; i++) {
  7316. 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)));
  7317. }
  7318. return new Curve3(bez);
  7319. };
  7320. /**
  7321. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7322. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7323. * @param v1 (Vector3) the first control point
  7324. * @param v2 (Vector3) the second control point
  7325. * @param v3 (Vector3) the end point of the Cubic Bezier
  7326. * @param nbPoints (integer) the wanted number of points in the curve
  7327. */
  7328. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7329. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7330. var bez = new Array();
  7331. var equation = function (t, val0, val1, val2, val3) {
  7332. 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;
  7333. return res;
  7334. };
  7335. for (var i = 0; i <= nbPoints; i++) {
  7336. 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)));
  7337. }
  7338. return new Curve3(bez);
  7339. };
  7340. /**
  7341. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7342. * @param p1 (Vector3) the origin point of the Hermite Spline
  7343. * @param t1 (Vector3) the tangent vector at the origin point
  7344. * @param p2 (Vector3) the end point of the Hermite Spline
  7345. * @param t2 (Vector3) the tangent vector at the end point
  7346. * @param nbPoints (integer) the wanted number of points in the curve
  7347. */
  7348. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7349. var hermite = new Array();
  7350. var step = 1.0 / nbPoints;
  7351. for (var i = 0; i <= nbPoints; i++) {
  7352. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7353. }
  7354. return new Curve3(hermite);
  7355. };
  7356. /**
  7357. * Returns a Curve3 object along a CatmullRom Spline curve :
  7358. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7359. * @param nbPoints (integer) the wanted number of points between each curve control points
  7360. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7361. */
  7362. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7363. var catmullRom = new Array();
  7364. var step = 1.0 / nbPoints;
  7365. var amount = 0.0;
  7366. if (closed) {
  7367. var pointsCount = points.length;
  7368. for (var i = 0; i < pointsCount; i++) {
  7369. amount = 0;
  7370. for (var c = 0; c < nbPoints; c++) {
  7371. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7372. amount += step;
  7373. }
  7374. }
  7375. catmullRom.push(catmullRom[0]);
  7376. }
  7377. else {
  7378. var totalPoints = new Array();
  7379. totalPoints.push(points[0].clone());
  7380. Array.prototype.push.apply(totalPoints, points);
  7381. totalPoints.push(points[points.length - 1].clone());
  7382. for (var i = 0; i < totalPoints.length - 3; i++) {
  7383. amount = 0;
  7384. for (var c = 0; c < nbPoints; c++) {
  7385. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7386. amount += step;
  7387. }
  7388. }
  7389. i--;
  7390. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7391. }
  7392. return new Curve3(catmullRom);
  7393. };
  7394. /**
  7395. * Returns the Curve3 stored array of successive Vector3
  7396. */
  7397. Curve3.prototype.getPoints = function () {
  7398. return this._points;
  7399. };
  7400. /**
  7401. * Returns the computed length (float) of the curve.
  7402. */
  7403. Curve3.prototype.length = function () {
  7404. return this._length;
  7405. };
  7406. /**
  7407. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7408. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7409. * curveA and curveB keep unchanged.
  7410. */
  7411. Curve3.prototype.continue = function (curve) {
  7412. var lastPoint = this._points[this._points.length - 1];
  7413. var continuedPoints = this._points.slice();
  7414. var curvePoints = curve.getPoints();
  7415. for (var i = 1; i < curvePoints.length; i++) {
  7416. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7417. }
  7418. var continuedCurve = new Curve3(continuedPoints);
  7419. return continuedCurve;
  7420. };
  7421. Curve3.prototype._computeLength = function (path) {
  7422. var l = 0;
  7423. for (var i = 1; i < path.length; i++) {
  7424. l += (path[i].subtract(path[i - 1])).length();
  7425. }
  7426. return l;
  7427. };
  7428. return Curve3;
  7429. }());
  7430. BABYLON.Curve3 = Curve3;
  7431. // Vertex formats
  7432. var PositionNormalVertex = /** @class */ (function () {
  7433. function PositionNormalVertex(position, normal) {
  7434. if (position === void 0) { position = Vector3.Zero(); }
  7435. if (normal === void 0) { normal = Vector3.Up(); }
  7436. this.position = position;
  7437. this.normal = normal;
  7438. }
  7439. PositionNormalVertex.prototype.clone = function () {
  7440. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7441. };
  7442. return PositionNormalVertex;
  7443. }());
  7444. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7445. var PositionNormalTextureVertex = /** @class */ (function () {
  7446. function PositionNormalTextureVertex(position, normal, uv) {
  7447. if (position === void 0) { position = Vector3.Zero(); }
  7448. if (normal === void 0) { normal = Vector3.Up(); }
  7449. if (uv === void 0) { uv = Vector2.Zero(); }
  7450. this.position = position;
  7451. this.normal = normal;
  7452. this.uv = uv;
  7453. }
  7454. PositionNormalTextureVertex.prototype.clone = function () {
  7455. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7456. };
  7457. return PositionNormalTextureVertex;
  7458. }());
  7459. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7460. // Temporary pre-allocated objects for engine internal use
  7461. // usage in any internal function :
  7462. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7463. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7464. var Tmp = /** @class */ (function () {
  7465. function Tmp() {
  7466. }
  7467. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7468. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7469. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7470. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7471. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7472. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7473. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7474. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7475. Matrix.Zero(), Matrix.Zero(),
  7476. Matrix.Zero(), Matrix.Zero(),
  7477. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7478. return Tmp;
  7479. }());
  7480. BABYLON.Tmp = Tmp;
  7481. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7482. var MathTmp = /** @class */ (function () {
  7483. function MathTmp() {
  7484. }
  7485. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7486. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7487. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7488. return MathTmp;
  7489. }());
  7490. })(BABYLON || (BABYLON = {}));
  7491. //# sourceMappingURL=babylon.math.js.map
  7492. var BABYLON;
  7493. (function (BABYLON) {
  7494. var Scalar = /** @class */ (function () {
  7495. function Scalar() {
  7496. }
  7497. /**
  7498. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7499. */
  7500. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7501. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7502. var num = a - b;
  7503. return -epsilon <= num && num <= epsilon;
  7504. };
  7505. /**
  7506. * Returns a string : the upper case translation of the number i to hexadecimal.
  7507. */
  7508. Scalar.ToHex = function (i) {
  7509. var str = i.toString(16);
  7510. if (i <= 15) {
  7511. return ("0" + str).toUpperCase();
  7512. }
  7513. return str.toUpperCase();
  7514. };
  7515. /**
  7516. * Returns -1 if value is negative and +1 is value is positive.
  7517. * Returns the value itself if it's equal to zero.
  7518. */
  7519. Scalar.Sign = function (value) {
  7520. value = +value; // convert to a number
  7521. if (value === 0 || isNaN(value))
  7522. return value;
  7523. return value > 0 ? 1 : -1;
  7524. };
  7525. /**
  7526. * Returns the value itself if it's between min and max.
  7527. * Returns min if the value is lower than min.
  7528. * Returns max if the value is greater than max.
  7529. */
  7530. Scalar.Clamp = function (value, min, max) {
  7531. if (min === void 0) { min = 0; }
  7532. if (max === void 0) { max = 1; }
  7533. return Math.min(max, Math.max(min, value));
  7534. };
  7535. /**
  7536. * Returns the log2 of value.
  7537. */
  7538. Scalar.Log2 = function (value) {
  7539. return Math.log(value) * Math.LOG2E;
  7540. };
  7541. /**
  7542. * Loops the value, so that it is never larger than length and never smaller than 0.
  7543. *
  7544. * This is similar to the modulo operator but it works with floating point numbers.
  7545. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7546. * With t = 5 and length = 2.5, the result would be 0.0.
  7547. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7548. */
  7549. Scalar.Repeat = function (value, length) {
  7550. return value - Math.floor(value / length) * length;
  7551. };
  7552. /**
  7553. * Normalize the value between 0.0 and 1.0 using min and max values
  7554. */
  7555. Scalar.Normalize = function (value, min, max) {
  7556. return (value - min) / (max - min);
  7557. };
  7558. /**
  7559. * Denormalize the value from 0.0 and 1.0 using min and max values
  7560. */
  7561. Scalar.Denormalize = function (normalized, min, max) {
  7562. return (normalized * (max - min) + min);
  7563. };
  7564. /**
  7565. * Calculates the shortest difference between two given angles given in degrees.
  7566. */
  7567. Scalar.DeltaAngle = function (current, target) {
  7568. var num = Scalar.Repeat(target - current, 360.0);
  7569. if (num > 180.0) {
  7570. num -= 360.0;
  7571. }
  7572. return num;
  7573. };
  7574. /**
  7575. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7576. *
  7577. * The returned value will move back and forth between 0 and length
  7578. */
  7579. Scalar.PingPong = function (tx, length) {
  7580. var t = Scalar.Repeat(tx, length * 2.0);
  7581. return length - Math.abs(t - length);
  7582. };
  7583. /**
  7584. * Interpolates between min and max with smoothing at the limits.
  7585. *
  7586. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7587. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7588. */
  7589. Scalar.SmoothStep = function (from, to, tx) {
  7590. var t = Scalar.Clamp(tx);
  7591. t = -2.0 * t * t * t + 3.0 * t * t;
  7592. return to * t + from * (1.0 - t);
  7593. };
  7594. /**
  7595. * Moves a value current towards target.
  7596. *
  7597. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7598. * Negative values of maxDelta pushes the value away from target.
  7599. */
  7600. Scalar.MoveTowards = function (current, target, maxDelta) {
  7601. var result = 0;
  7602. if (Math.abs(target - current) <= maxDelta) {
  7603. result = target;
  7604. }
  7605. else {
  7606. result = current + Scalar.Sign(target - current) * maxDelta;
  7607. }
  7608. return result;
  7609. };
  7610. /**
  7611. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7612. *
  7613. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7614. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7615. */
  7616. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7617. var num = Scalar.DeltaAngle(current, target);
  7618. var result = 0;
  7619. if (-maxDelta < num && num < maxDelta) {
  7620. result = target;
  7621. }
  7622. else {
  7623. target = current + num;
  7624. result = Scalar.MoveTowards(current, target, maxDelta);
  7625. }
  7626. return result;
  7627. };
  7628. /**
  7629. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7630. */
  7631. Scalar.Lerp = function (start, end, amount) {
  7632. return start + ((end - start) * amount);
  7633. };
  7634. /**
  7635. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7636. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7637. */
  7638. Scalar.LerpAngle = function (start, end, amount) {
  7639. var num = Scalar.Repeat(end - start, 360.0);
  7640. if (num > 180.0) {
  7641. num -= 360.0;
  7642. }
  7643. return start + num * Scalar.Clamp(amount);
  7644. };
  7645. /**
  7646. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7647. */
  7648. Scalar.InverseLerp = function (a, b, value) {
  7649. var result = 0;
  7650. if (a != b) {
  7651. result = Scalar.Clamp((value - a) / (b - a));
  7652. }
  7653. else {
  7654. result = 0.0;
  7655. }
  7656. return result;
  7657. };
  7658. /**
  7659. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7660. */
  7661. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7662. var squared = amount * amount;
  7663. var cubed = amount * squared;
  7664. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7665. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7666. var part3 = (cubed - (2.0 * squared)) + amount;
  7667. var part4 = cubed - squared;
  7668. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7669. };
  7670. /**
  7671. * Returns a random float number between and min and max values
  7672. */
  7673. Scalar.RandomRange = function (min, max) {
  7674. if (min === max)
  7675. return min;
  7676. return ((Math.random() * (max - min)) + min);
  7677. };
  7678. /**
  7679. * This function returns percentage of a number in a given range.
  7680. *
  7681. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7682. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7683. */
  7684. Scalar.RangeToPercent = function (number, min, max) {
  7685. return ((number - min) / (max - min));
  7686. };
  7687. /**
  7688. * This function returns number that corresponds to the percentage in a given range.
  7689. *
  7690. * PercentToRange(0.34,0,100) will return 34.
  7691. */
  7692. Scalar.PercentToRange = function (percent, min, max) {
  7693. return ((max - min) * percent + min);
  7694. };
  7695. /**
  7696. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7697. * @param angle The angle to normalize in radian.
  7698. * @return The converted angle.
  7699. */
  7700. Scalar.NormalizeRadians = function (angle) {
  7701. // More precise but slower version kept for reference.
  7702. // angle = angle % Tools.TwoPi;
  7703. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7704. //if (angle > Math.PI) {
  7705. // angle -= Tools.TwoPi;
  7706. //}
  7707. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7708. return angle;
  7709. };
  7710. /**
  7711. * Two pi constants convenient for computation.
  7712. */
  7713. Scalar.TwoPi = Math.PI * 2;
  7714. return Scalar;
  7715. }());
  7716. BABYLON.Scalar = Scalar;
  7717. })(BABYLON || (BABYLON = {}));
  7718. //# sourceMappingURL=babylon.math.scalar.js.map
  7719. //# sourceMappingURL=babylon.mixins.js.map
  7720. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7721. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7722. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7723. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7724. //# sourceMappingURL=babylon.webgl2.js.map
  7725. var BABYLON;
  7726. (function (BABYLON) {
  7727. var __decoratorInitialStore = {};
  7728. var __mergedStore = {};
  7729. var _copySource = function (creationFunction, source, instanciate) {
  7730. var destination = creationFunction();
  7731. // Tags
  7732. if (BABYLON.Tags) {
  7733. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7734. }
  7735. var classStore = getMergedStore(destination);
  7736. // Properties
  7737. for (var property in classStore) {
  7738. var propertyDescriptor = classStore[property];
  7739. var sourceProperty = source[property];
  7740. var propertyType = propertyDescriptor.type;
  7741. if (sourceProperty !== undefined && sourceProperty !== null) {
  7742. switch (propertyType) {
  7743. case 0: // Value
  7744. case 6: // Mesh reference
  7745. case 11: // Camera reference
  7746. destination[property] = sourceProperty;
  7747. break;
  7748. case 1: // Texture
  7749. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7750. break;
  7751. case 2: // Color3
  7752. case 3: // FresnelParameters
  7753. case 4: // Vector2
  7754. case 5: // Vector3
  7755. case 7: // Color Curves
  7756. case 10: // Quaternion
  7757. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7758. break;
  7759. }
  7760. }
  7761. }
  7762. return destination;
  7763. };
  7764. function getDirectStore(target) {
  7765. var classKey = target.getClassName();
  7766. if (!__decoratorInitialStore[classKey]) {
  7767. __decoratorInitialStore[classKey] = {};
  7768. }
  7769. return __decoratorInitialStore[classKey];
  7770. }
  7771. /**
  7772. * Return the list of properties flagged as serializable
  7773. * @param target: host object
  7774. */
  7775. function getMergedStore(target) {
  7776. var classKey = target.getClassName();
  7777. if (__mergedStore[classKey]) {
  7778. return __mergedStore[classKey];
  7779. }
  7780. __mergedStore[classKey] = {};
  7781. var store = __mergedStore[classKey];
  7782. var currentTarget = target;
  7783. var currentKey = classKey;
  7784. while (currentKey) {
  7785. var initialStore = __decoratorInitialStore[currentKey];
  7786. for (var property in initialStore) {
  7787. store[property] = initialStore[property];
  7788. }
  7789. var parent_1 = void 0;
  7790. var done = false;
  7791. do {
  7792. parent_1 = Object.getPrototypeOf(currentTarget);
  7793. if (!parent_1.getClassName) {
  7794. done = true;
  7795. break;
  7796. }
  7797. if (parent_1.getClassName() !== currentKey) {
  7798. break;
  7799. }
  7800. currentTarget = parent_1;
  7801. } while (parent_1);
  7802. if (done) {
  7803. break;
  7804. }
  7805. currentKey = parent_1.getClassName();
  7806. currentTarget = parent_1;
  7807. }
  7808. return store;
  7809. }
  7810. function generateSerializableMember(type, sourceName) {
  7811. return function (target, propertyKey) {
  7812. var classStore = getDirectStore(target);
  7813. if (!classStore[propertyKey]) {
  7814. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7815. }
  7816. };
  7817. }
  7818. function generateExpandMember(setCallback, targetKey) {
  7819. if (targetKey === void 0) { targetKey = null; }
  7820. return function (target, propertyKey) {
  7821. var key = targetKey || ("_" + propertyKey);
  7822. Object.defineProperty(target, propertyKey, {
  7823. get: function () {
  7824. return this[key];
  7825. },
  7826. set: function (value) {
  7827. if (this[key] === value) {
  7828. return;
  7829. }
  7830. this[key] = value;
  7831. target[setCallback].apply(this);
  7832. },
  7833. enumerable: true,
  7834. configurable: true
  7835. });
  7836. };
  7837. }
  7838. function expandToProperty(callback, targetKey) {
  7839. if (targetKey === void 0) { targetKey = null; }
  7840. return generateExpandMember(callback, targetKey);
  7841. }
  7842. BABYLON.expandToProperty = expandToProperty;
  7843. function serialize(sourceName) {
  7844. return generateSerializableMember(0, sourceName); // value member
  7845. }
  7846. BABYLON.serialize = serialize;
  7847. function serializeAsTexture(sourceName) {
  7848. return generateSerializableMember(1, sourceName); // texture member
  7849. }
  7850. BABYLON.serializeAsTexture = serializeAsTexture;
  7851. function serializeAsColor3(sourceName) {
  7852. return generateSerializableMember(2, sourceName); // color3 member
  7853. }
  7854. BABYLON.serializeAsColor3 = serializeAsColor3;
  7855. function serializeAsFresnelParameters(sourceName) {
  7856. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7857. }
  7858. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7859. function serializeAsVector2(sourceName) {
  7860. return generateSerializableMember(4, sourceName); // vector2 member
  7861. }
  7862. BABYLON.serializeAsVector2 = serializeAsVector2;
  7863. function serializeAsVector3(sourceName) {
  7864. return generateSerializableMember(5, sourceName); // vector3 member
  7865. }
  7866. BABYLON.serializeAsVector3 = serializeAsVector3;
  7867. function serializeAsMeshReference(sourceName) {
  7868. return generateSerializableMember(6, sourceName); // mesh reference member
  7869. }
  7870. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7871. function serializeAsColorCurves(sourceName) {
  7872. return generateSerializableMember(7, sourceName); // color curves
  7873. }
  7874. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7875. function serializeAsColor4(sourceName) {
  7876. return generateSerializableMember(8, sourceName); // color 4
  7877. }
  7878. BABYLON.serializeAsColor4 = serializeAsColor4;
  7879. function serializeAsImageProcessingConfiguration(sourceName) {
  7880. return generateSerializableMember(9, sourceName); // image processing
  7881. }
  7882. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7883. function serializeAsQuaternion(sourceName) {
  7884. return generateSerializableMember(10, sourceName); // quaternion member
  7885. }
  7886. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7887. /**
  7888. * Decorator used to define property that can be serialized as reference to a camera
  7889. * @param sourceName defines the name of the property to decorate
  7890. */
  7891. function serializeAsCameraReference(sourceName) {
  7892. return generateSerializableMember(11, sourceName); // camera reference member
  7893. }
  7894. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7895. var SerializationHelper = /** @class */ (function () {
  7896. function SerializationHelper() {
  7897. }
  7898. SerializationHelper.Serialize = function (entity, serializationObject) {
  7899. if (!serializationObject) {
  7900. serializationObject = {};
  7901. }
  7902. // Tags
  7903. if (BABYLON.Tags) {
  7904. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7905. }
  7906. var serializedProperties = getMergedStore(entity);
  7907. // Properties
  7908. for (var property in serializedProperties) {
  7909. var propertyDescriptor = serializedProperties[property];
  7910. var targetPropertyName = propertyDescriptor.sourceName || property;
  7911. var propertyType = propertyDescriptor.type;
  7912. var sourceProperty = entity[property];
  7913. if (sourceProperty !== undefined && sourceProperty !== null) {
  7914. switch (propertyType) {
  7915. case 0: // Value
  7916. serializationObject[targetPropertyName] = sourceProperty;
  7917. break;
  7918. case 1: // Texture
  7919. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7920. break;
  7921. case 2: // Color3
  7922. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7923. break;
  7924. case 3: // FresnelParameters
  7925. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7926. break;
  7927. case 4: // Vector2
  7928. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7929. break;
  7930. case 5: // Vector3
  7931. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7932. break;
  7933. case 6: // Mesh reference
  7934. serializationObject[targetPropertyName] = sourceProperty.id;
  7935. break;
  7936. case 7: // Color Curves
  7937. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7938. break;
  7939. case 8: // Color 4
  7940. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7941. break;
  7942. case 9: // Image Processing
  7943. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7944. break;
  7945. case 10: // Quaternion
  7946. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7947. break;
  7948. case 11: // Camera reference
  7949. serializationObject[targetPropertyName] = sourceProperty.id;
  7950. break;
  7951. }
  7952. }
  7953. }
  7954. return serializationObject;
  7955. };
  7956. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7957. if (rootUrl === void 0) { rootUrl = null; }
  7958. var destination = creationFunction();
  7959. if (!rootUrl) {
  7960. rootUrl = "";
  7961. }
  7962. // Tags
  7963. if (BABYLON.Tags) {
  7964. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7965. }
  7966. var classStore = getMergedStore(destination);
  7967. // Properties
  7968. for (var property in classStore) {
  7969. var propertyDescriptor = classStore[property];
  7970. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7971. var propertyType = propertyDescriptor.type;
  7972. if (sourceProperty !== undefined && sourceProperty !== null) {
  7973. var dest = destination;
  7974. switch (propertyType) {
  7975. case 0: // Value
  7976. dest[property] = sourceProperty;
  7977. break;
  7978. case 1: // Texture
  7979. if (scene) {
  7980. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7981. }
  7982. break;
  7983. case 2: // Color3
  7984. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7985. break;
  7986. case 3: // FresnelParameters
  7987. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7988. break;
  7989. case 4: // Vector2
  7990. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7991. break;
  7992. case 5: // Vector3
  7993. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7994. break;
  7995. case 6: // Mesh reference
  7996. if (scene) {
  7997. dest[property] = scene.getLastMeshByID(sourceProperty);
  7998. }
  7999. break;
  8000. case 7: // Color Curves
  8001. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8002. break;
  8003. case 8: // Color 4
  8004. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8005. break;
  8006. case 9: // Image Processing
  8007. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8008. break;
  8009. case 10: // Quaternion
  8010. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8011. break;
  8012. case 11: // Camera reference
  8013. if (scene) {
  8014. dest[property] = scene.getCameraByID(sourceProperty);
  8015. }
  8016. break;
  8017. }
  8018. }
  8019. }
  8020. return destination;
  8021. };
  8022. SerializationHelper.Clone = function (creationFunction, source) {
  8023. return _copySource(creationFunction, source, false);
  8024. };
  8025. SerializationHelper.Instanciate = function (creationFunction, source) {
  8026. return _copySource(creationFunction, source, true);
  8027. };
  8028. return SerializationHelper;
  8029. }());
  8030. BABYLON.SerializationHelper = SerializationHelper;
  8031. })(BABYLON || (BABYLON = {}));
  8032. //# sourceMappingURL=babylon.decorators.js.map
  8033. var BABYLON;
  8034. (function (BABYLON) {
  8035. /**
  8036. * Wrapper class for promise with external resolve and reject.
  8037. */
  8038. var Deferred = /** @class */ (function () {
  8039. /**
  8040. * Constructor for this deferred object.
  8041. */
  8042. function Deferred() {
  8043. var _this = this;
  8044. this.promise = new Promise(function (resolve, reject) {
  8045. _this._resolve = resolve;
  8046. _this._reject = reject;
  8047. });
  8048. }
  8049. Object.defineProperty(Deferred.prototype, "resolve", {
  8050. /**
  8051. * The resolve method of the promise associated with this deferred object.
  8052. */
  8053. get: function () {
  8054. return this._resolve;
  8055. },
  8056. enumerable: true,
  8057. configurable: true
  8058. });
  8059. Object.defineProperty(Deferred.prototype, "reject", {
  8060. /**
  8061. * The reject method of the promise associated with this deferred object.
  8062. */
  8063. get: function () {
  8064. return this._reject;
  8065. },
  8066. enumerable: true,
  8067. configurable: true
  8068. });
  8069. return Deferred;
  8070. }());
  8071. BABYLON.Deferred = Deferred;
  8072. })(BABYLON || (BABYLON = {}));
  8073. //# sourceMappingURL=babylon.deferred.js.map
  8074. var BABYLON;
  8075. (function (BABYLON) {
  8076. /**
  8077. * A class serves as a medium between the observable and its observers
  8078. */
  8079. var EventState = /** @class */ (function () {
  8080. /**
  8081. * Create a new EventState
  8082. * @param mask defines the mask associated with this state
  8083. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8084. * @param target defines the original target of the state
  8085. * @param currentTarget defines the current target of the state
  8086. */
  8087. function EventState(mask, skipNextObservers, target, currentTarget) {
  8088. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8089. this.initalize(mask, skipNextObservers, target, currentTarget);
  8090. }
  8091. /**
  8092. * Initialize the current event state
  8093. * @param mask defines the mask associated with this state
  8094. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8095. * @param target defines the original target of the state
  8096. * @param currentTarget defines the current target of the state
  8097. * @returns the current event state
  8098. */
  8099. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8100. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8101. this.mask = mask;
  8102. this.skipNextObservers = skipNextObservers;
  8103. this.target = target;
  8104. this.currentTarget = currentTarget;
  8105. return this;
  8106. };
  8107. return EventState;
  8108. }());
  8109. BABYLON.EventState = EventState;
  8110. /**
  8111. * Represent an Observer registered to a given Observable object.
  8112. */
  8113. var Observer = /** @class */ (function () {
  8114. /**
  8115. * Creates a new observer
  8116. * @param callback defines the callback to call when the observer is notified
  8117. * @param mask defines the mask of the observer (used to filter notifications)
  8118. * @param scope defines the current scope used to restore the JS context
  8119. */
  8120. function Observer(
  8121. /**
  8122. * Defines the callback to call when the observer is notified
  8123. */
  8124. callback,
  8125. /**
  8126. * Defines the mask of the observer (used to filter notifications)
  8127. */
  8128. mask,
  8129. /**
  8130. * Defines the current scope used to restore the JS context
  8131. */
  8132. scope) {
  8133. if (scope === void 0) { scope = null; }
  8134. this.callback = callback;
  8135. this.mask = mask;
  8136. this.scope = scope;
  8137. /** @hidden */
  8138. this._willBeUnregistered = false;
  8139. /**
  8140. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8141. */
  8142. this.unregisterOnNextCall = false;
  8143. }
  8144. return Observer;
  8145. }());
  8146. BABYLON.Observer = Observer;
  8147. /**
  8148. * Represent a list of observers registered to multiple Observables object.
  8149. */
  8150. var MultiObserver = /** @class */ (function () {
  8151. function MultiObserver() {
  8152. }
  8153. /**
  8154. * Release associated resources
  8155. */
  8156. MultiObserver.prototype.dispose = function () {
  8157. if (this._observers && this._observables) {
  8158. for (var index = 0; index < this._observers.length; index++) {
  8159. this._observables[index].remove(this._observers[index]);
  8160. }
  8161. }
  8162. this._observers = null;
  8163. this._observables = null;
  8164. };
  8165. /**
  8166. * Raise a callback when one of the observable will notify
  8167. * @param observables defines a list of observables to watch
  8168. * @param callback defines the callback to call on notification
  8169. * @param mask defines the mask used to filter notifications
  8170. * @param scope defines the current scope used to restore the JS context
  8171. * @returns the new MultiObserver
  8172. */
  8173. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8174. if (mask === void 0) { mask = -1; }
  8175. if (scope === void 0) { scope = null; }
  8176. var result = new MultiObserver();
  8177. result._observers = new Array();
  8178. result._observables = observables;
  8179. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8180. var observable = observables_1[_i];
  8181. var observer = observable.add(callback, mask, false, scope);
  8182. if (observer) {
  8183. result._observers.push(observer);
  8184. }
  8185. }
  8186. return result;
  8187. };
  8188. return MultiObserver;
  8189. }());
  8190. BABYLON.MultiObserver = MultiObserver;
  8191. /**
  8192. * The Observable class is a simple implementation of the Observable pattern.
  8193. *
  8194. * 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.
  8195. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8196. * 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).
  8197. * 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.
  8198. */
  8199. var Observable = /** @class */ (function () {
  8200. /**
  8201. * Creates a new observable
  8202. * @param onObserverAdded defines a callback to call when a new observer is added
  8203. */
  8204. function Observable(onObserverAdded) {
  8205. this._observers = new Array();
  8206. this._eventState = new EventState(0);
  8207. if (onObserverAdded) {
  8208. this._onObserverAdded = onObserverAdded;
  8209. }
  8210. }
  8211. /**
  8212. * Create a new Observer with the specified callback
  8213. * @param callback the callback that will be executed for that Observer
  8214. * @param mask the mask used to filter observers
  8215. * @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.
  8216. * @param scope optional scope for the callback to be called from
  8217. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8218. * @returns the new observer created for the callback
  8219. */
  8220. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8221. if (mask === void 0) { mask = -1; }
  8222. if (insertFirst === void 0) { insertFirst = false; }
  8223. if (scope === void 0) { scope = null; }
  8224. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8225. if (!callback) {
  8226. return null;
  8227. }
  8228. var observer = new Observer(callback, mask, scope);
  8229. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8230. if (insertFirst) {
  8231. this._observers.unshift(observer);
  8232. }
  8233. else {
  8234. this._observers.push(observer);
  8235. }
  8236. if (this._onObserverAdded) {
  8237. this._onObserverAdded(observer);
  8238. }
  8239. return observer;
  8240. };
  8241. /**
  8242. * Create a new Observer with the specified callback and unregisters after the next notification
  8243. * @param callback the callback that will be executed for that Observer
  8244. * @returns the new observer created for the callback
  8245. */
  8246. Observable.prototype.addOnce = function (callback) {
  8247. return this.add(callback, undefined, undefined, undefined, true);
  8248. };
  8249. /**
  8250. * Remove an Observer from the Observable object
  8251. * @param observer the instance of the Observer to remove
  8252. * @returns false if it doesn't belong to this Observable
  8253. */
  8254. Observable.prototype.remove = function (observer) {
  8255. if (!observer) {
  8256. return false;
  8257. }
  8258. var index = this._observers.indexOf(observer);
  8259. if (index !== -1) {
  8260. this._deferUnregister(observer);
  8261. return true;
  8262. }
  8263. return false;
  8264. };
  8265. /**
  8266. * Remove a callback from the Observable object
  8267. * @param callback the callback to remove
  8268. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8269. * @returns false if it doesn't belong to this Observable
  8270. */
  8271. Observable.prototype.removeCallback = function (callback, scope) {
  8272. for (var index = 0; index < this._observers.length; index++) {
  8273. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8274. this._deferUnregister(this._observers[index]);
  8275. return true;
  8276. }
  8277. }
  8278. return false;
  8279. };
  8280. Observable.prototype._deferUnregister = function (observer) {
  8281. var _this = this;
  8282. observer.unregisterOnNextCall = false;
  8283. observer._willBeUnregistered = true;
  8284. BABYLON.Tools.SetImmediate(function () {
  8285. _this._remove(observer);
  8286. });
  8287. };
  8288. // This should only be called when not iterating over _observers to avoid callback skipping.
  8289. // Removes an observer from the _observer Array.
  8290. Observable.prototype._remove = function (observer) {
  8291. if (!observer) {
  8292. return false;
  8293. }
  8294. var index = this._observers.indexOf(observer);
  8295. if (index !== -1) {
  8296. this._observers.splice(index, 1);
  8297. return true;
  8298. }
  8299. return false;
  8300. };
  8301. /**
  8302. * Notify all Observers by calling their respective callback with the given data
  8303. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8304. * @param eventData defines the data to send to all observers
  8305. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8306. * @param target defines the original target of the state
  8307. * @param currentTarget defines the current target of the state
  8308. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8309. */
  8310. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8311. if (mask === void 0) { mask = -1; }
  8312. if (!this._observers.length) {
  8313. return true;
  8314. }
  8315. var state = this._eventState;
  8316. state.mask = mask;
  8317. state.target = target;
  8318. state.currentTarget = currentTarget;
  8319. state.skipNextObservers = false;
  8320. state.lastReturnValue = eventData;
  8321. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8322. var obs = _a[_i];
  8323. if (obs._willBeUnregistered) {
  8324. continue;
  8325. }
  8326. if (obs.mask & mask) {
  8327. if (obs.scope) {
  8328. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8329. }
  8330. else {
  8331. state.lastReturnValue = obs.callback(eventData, state);
  8332. }
  8333. if (obs.unregisterOnNextCall) {
  8334. this._deferUnregister(obs);
  8335. }
  8336. }
  8337. if (state.skipNextObservers) {
  8338. return false;
  8339. }
  8340. }
  8341. return true;
  8342. };
  8343. /**
  8344. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8345. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8346. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8347. * and it is crucial that all callbacks will be executed.
  8348. * The order of the callbacks is kept, callbacks are not executed parallel.
  8349. *
  8350. * @param eventData The data to be sent to each callback
  8351. * @param mask is used to filter observers defaults to -1
  8352. * @param target defines the callback target (see EventState)
  8353. * @param currentTarget defines he current object in the bubbling phase
  8354. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8355. */
  8356. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8357. var _this = this;
  8358. if (mask === void 0) { mask = -1; }
  8359. // create an empty promise
  8360. var p = Promise.resolve(eventData);
  8361. // no observers? return this promise.
  8362. if (!this._observers.length) {
  8363. return p;
  8364. }
  8365. var state = this._eventState;
  8366. state.mask = mask;
  8367. state.target = target;
  8368. state.currentTarget = currentTarget;
  8369. state.skipNextObservers = false;
  8370. // execute one callback after another (not using Promise.all, the order is important)
  8371. this._observers.forEach(function (obs) {
  8372. if (state.skipNextObservers) {
  8373. return;
  8374. }
  8375. if (obs._willBeUnregistered) {
  8376. return;
  8377. }
  8378. if (obs.mask & mask) {
  8379. if (obs.scope) {
  8380. p = p.then(function (lastReturnedValue) {
  8381. state.lastReturnValue = lastReturnedValue;
  8382. return obs.callback.apply(obs.scope, [eventData, state]);
  8383. });
  8384. }
  8385. else {
  8386. p = p.then(function (lastReturnedValue) {
  8387. state.lastReturnValue = lastReturnedValue;
  8388. return obs.callback(eventData, state);
  8389. });
  8390. }
  8391. if (obs.unregisterOnNextCall) {
  8392. _this._deferUnregister(obs);
  8393. }
  8394. }
  8395. });
  8396. // return the eventData
  8397. return p.then(function () { return eventData; });
  8398. };
  8399. /**
  8400. * Notify a specific observer
  8401. * @param observer defines the observer to notify
  8402. * @param eventData defines the data to be sent to each callback
  8403. * @param mask is used to filter observers defaults to -1
  8404. */
  8405. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8406. if (mask === void 0) { mask = -1; }
  8407. var state = this._eventState;
  8408. state.mask = mask;
  8409. state.skipNextObservers = false;
  8410. observer.callback(eventData, state);
  8411. };
  8412. /**
  8413. * Gets a boolean indicating if the observable has at least one observer
  8414. * @returns true is the Observable has at least one Observer registered
  8415. */
  8416. Observable.prototype.hasObservers = function () {
  8417. return this._observers.length > 0;
  8418. };
  8419. /**
  8420. * Clear the list of observers
  8421. */
  8422. Observable.prototype.clear = function () {
  8423. this._observers = new Array();
  8424. this._onObserverAdded = null;
  8425. };
  8426. /**
  8427. * Clone the current observable
  8428. * @returns a new observable
  8429. */
  8430. Observable.prototype.clone = function () {
  8431. var result = new Observable();
  8432. result._observers = this._observers.slice(0);
  8433. return result;
  8434. };
  8435. /**
  8436. * Does this observable handles observer registered with a given mask
  8437. * @param mask defines the mask to be tested
  8438. * @return whether or not one observer registered with the given mask is handeled
  8439. **/
  8440. Observable.prototype.hasSpecificMask = function (mask) {
  8441. if (mask === void 0) { mask = -1; }
  8442. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8443. var obs = _a[_i];
  8444. if (obs.mask & mask || obs.mask === mask) {
  8445. return true;
  8446. }
  8447. }
  8448. return false;
  8449. };
  8450. return Observable;
  8451. }());
  8452. BABYLON.Observable = Observable;
  8453. })(BABYLON || (BABYLON = {}));
  8454. //# sourceMappingURL=babylon.observable.js.map
  8455. var BABYLON;
  8456. (function (BABYLON) {
  8457. var SmartArray = /** @class */ (function () {
  8458. function SmartArray(capacity) {
  8459. this.length = 0;
  8460. this.data = new Array(capacity);
  8461. this._id = SmartArray._GlobalId++;
  8462. }
  8463. SmartArray.prototype.push = function (value) {
  8464. this.data[this.length++] = value;
  8465. if (this.length > this.data.length) {
  8466. this.data.length *= 2;
  8467. }
  8468. };
  8469. SmartArray.prototype.forEach = function (func) {
  8470. for (var index = 0; index < this.length; index++) {
  8471. func(this.data[index]);
  8472. }
  8473. };
  8474. SmartArray.prototype.sort = function (compareFn) {
  8475. this.data.sort(compareFn);
  8476. };
  8477. SmartArray.prototype.reset = function () {
  8478. this.length = 0;
  8479. };
  8480. SmartArray.prototype.dispose = function () {
  8481. this.reset();
  8482. if (this.data) {
  8483. this.data.length = 0;
  8484. this.data = [];
  8485. }
  8486. };
  8487. SmartArray.prototype.concat = function (array) {
  8488. if (array.length === 0) {
  8489. return;
  8490. }
  8491. if (this.length + array.length > this.data.length) {
  8492. this.data.length = (this.length + array.length) * 2;
  8493. }
  8494. for (var index = 0; index < array.length; index++) {
  8495. this.data[this.length++] = (array.data || array)[index];
  8496. }
  8497. };
  8498. SmartArray.prototype.indexOf = function (value) {
  8499. var position = this.data.indexOf(value);
  8500. if (position >= this.length) {
  8501. return -1;
  8502. }
  8503. return position;
  8504. };
  8505. SmartArray.prototype.contains = function (value) {
  8506. return this.data.indexOf(value) !== -1;
  8507. };
  8508. // Statics
  8509. SmartArray._GlobalId = 0;
  8510. return SmartArray;
  8511. }());
  8512. BABYLON.SmartArray = SmartArray;
  8513. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8514. __extends(SmartArrayNoDuplicate, _super);
  8515. function SmartArrayNoDuplicate() {
  8516. var _this = _super !== null && _super.apply(this, arguments) || this;
  8517. _this._duplicateId = 0;
  8518. return _this;
  8519. }
  8520. SmartArrayNoDuplicate.prototype.push = function (value) {
  8521. _super.prototype.push.call(this, value);
  8522. if (!value.__smartArrayFlags) {
  8523. value.__smartArrayFlags = {};
  8524. }
  8525. value.__smartArrayFlags[this._id] = this._duplicateId;
  8526. };
  8527. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8528. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8529. return false;
  8530. }
  8531. this.push(value);
  8532. return true;
  8533. };
  8534. SmartArrayNoDuplicate.prototype.reset = function () {
  8535. _super.prototype.reset.call(this);
  8536. this._duplicateId++;
  8537. };
  8538. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8539. if (array.length === 0) {
  8540. return;
  8541. }
  8542. if (this.length + array.length > this.data.length) {
  8543. this.data.length = (this.length + array.length) * 2;
  8544. }
  8545. for (var index = 0; index < array.length; index++) {
  8546. var item = (array.data || array)[index];
  8547. this.pushNoDuplicate(item);
  8548. }
  8549. };
  8550. return SmartArrayNoDuplicate;
  8551. }(SmartArray));
  8552. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8553. })(BABYLON || (BABYLON = {}));
  8554. //# sourceMappingURL=babylon.smartArray.js.map
  8555. var BABYLON;
  8556. (function (BABYLON) {
  8557. /** Class used to store color gradient */
  8558. var ColorGradient = /** @class */ (function () {
  8559. function ColorGradient() {
  8560. }
  8561. /**
  8562. * Will get a color picked randomly between color1 and color2.
  8563. * If color2 is undefined then color1 will be used
  8564. * @param result defines the target Color4 to store the result in
  8565. */
  8566. ColorGradient.prototype.getColorToRef = function (result) {
  8567. if (!this.color2) {
  8568. result.copyFrom(this.color1);
  8569. return;
  8570. }
  8571. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  8572. };
  8573. return ColorGradient;
  8574. }());
  8575. BABYLON.ColorGradient = ColorGradient;
  8576. /** Class used to store factor gradient */
  8577. var FactorGradient = /** @class */ (function () {
  8578. function FactorGradient() {
  8579. }
  8580. /**
  8581. * Will get a number picked randomly between factor1 and factor2.
  8582. * If factor2 is undefined then factor1 will be used
  8583. * @returns the picked number
  8584. */
  8585. FactorGradient.prototype.getFactor = function () {
  8586. if (this.factor2 === undefined) {
  8587. return this.factor1;
  8588. }
  8589. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  8590. };
  8591. return FactorGradient;
  8592. }());
  8593. BABYLON.FactorGradient = FactorGradient;
  8594. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8595. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8596. var LoadFileError = /** @class */ (function (_super) {
  8597. __extends(LoadFileError, _super);
  8598. function LoadFileError(message, request) {
  8599. var _this = _super.call(this, message) || this;
  8600. _this.request = request;
  8601. _this.name = "LoadFileError";
  8602. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8603. return _this;
  8604. }
  8605. // Polyfill for Object.setPrototypeOf if necessary.
  8606. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8607. return LoadFileError;
  8608. }(Error));
  8609. BABYLON.LoadFileError = LoadFileError;
  8610. var RetryStrategy = /** @class */ (function () {
  8611. function RetryStrategy() {
  8612. }
  8613. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8614. if (maxRetries === void 0) { maxRetries = 3; }
  8615. if (baseInterval === void 0) { baseInterval = 500; }
  8616. return function (url, request, retryIndex) {
  8617. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8618. return -1;
  8619. }
  8620. return Math.pow(2, retryIndex) * baseInterval;
  8621. };
  8622. };
  8623. return RetryStrategy;
  8624. }());
  8625. BABYLON.RetryStrategy = RetryStrategy;
  8626. // Screenshots
  8627. var screenshotCanvas;
  8628. var cloneValue = function (source, destinationObject) {
  8629. if (!source)
  8630. return null;
  8631. if (source instanceof BABYLON.Mesh) {
  8632. return null;
  8633. }
  8634. if (source instanceof BABYLON.SubMesh) {
  8635. return source.clone(destinationObject);
  8636. }
  8637. else if (source.clone) {
  8638. return source.clone();
  8639. }
  8640. return null;
  8641. };
  8642. var Tools = /** @class */ (function () {
  8643. function Tools() {
  8644. }
  8645. /**
  8646. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  8647. * @param u defines the coordinate on X axis
  8648. * @param v defines the coordinate on Y axis
  8649. * @param width defines the width of the source data
  8650. * @param height defines the height of the source data
  8651. * @param pixels defines the source byte array
  8652. * @param color defines the output color
  8653. */
  8654. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  8655. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  8656. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  8657. var position = (wrappedU + wrappedV * width) * 4;
  8658. color.r = pixels[position] / 255;
  8659. color.g = pixels[position + 1] / 255;
  8660. color.b = pixels[position + 2] / 255;
  8661. color.a = pixels[position + 3] / 255;
  8662. };
  8663. /**
  8664. * Interpolates between a and b via alpha
  8665. * @param a The lower value (returned when alpha = 0)
  8666. * @param b The upper value (returned when alpha = 1)
  8667. * @param alpha The interpolation-factor
  8668. * @return The mixed value
  8669. */
  8670. Tools.Mix = function (a, b, alpha) {
  8671. return a * (1 - alpha) + b * alpha;
  8672. };
  8673. Tools.Instantiate = function (className) {
  8674. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8675. return Tools.RegisteredExternalClasses[className];
  8676. }
  8677. var arr = className.split(".");
  8678. var fn = (window || this);
  8679. for (var i = 0, len = arr.length; i < len; i++) {
  8680. fn = fn[arr[i]];
  8681. }
  8682. if (typeof fn !== "function") {
  8683. return null;
  8684. }
  8685. return fn;
  8686. };
  8687. /**
  8688. * Provides a slice function that will work even on IE
  8689. * @param data defines the array to slice
  8690. * @param start defines the start of the data (optional)
  8691. * @param end defines the end of the data (optional)
  8692. * @returns the new sliced array
  8693. */
  8694. Tools.Slice = function (data, start, end) {
  8695. if (data.slice) {
  8696. return data.slice(start, end);
  8697. }
  8698. return Array.prototype.slice.call(data, start, end);
  8699. };
  8700. Tools.SetImmediate = function (action) {
  8701. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  8702. window.setImmediate(action);
  8703. }
  8704. else {
  8705. setTimeout(action, 1);
  8706. }
  8707. };
  8708. Tools.IsExponentOfTwo = function (value) {
  8709. var count = 1;
  8710. do {
  8711. count *= 2;
  8712. } while (count < value);
  8713. return count === value;
  8714. };
  8715. /**
  8716. * Returns the nearest 32-bit single precision float representation of a Number
  8717. * @param value A Number. If the parameter is of a different type, it will get converted
  8718. * to a number or to NaN if it cannot be converted
  8719. * @returns number
  8720. */
  8721. Tools.FloatRound = function (value) {
  8722. if (Math.fround) {
  8723. return Math.fround(value);
  8724. }
  8725. return (Tools._tmpFloatArray[0] = value);
  8726. };
  8727. /**
  8728. * Find the next highest power of two.
  8729. * @param x Number to start search from.
  8730. * @return Next highest power of two.
  8731. */
  8732. Tools.CeilingPOT = function (x) {
  8733. x--;
  8734. x |= x >> 1;
  8735. x |= x >> 2;
  8736. x |= x >> 4;
  8737. x |= x >> 8;
  8738. x |= x >> 16;
  8739. x++;
  8740. return x;
  8741. };
  8742. /**
  8743. * Find the next lowest power of two.
  8744. * @param x Number to start search from.
  8745. * @return Next lowest power of two.
  8746. */
  8747. Tools.FloorPOT = function (x) {
  8748. x = x | (x >> 1);
  8749. x = x | (x >> 2);
  8750. x = x | (x >> 4);
  8751. x = x | (x >> 8);
  8752. x = x | (x >> 16);
  8753. return x - (x >> 1);
  8754. };
  8755. /**
  8756. * Find the nearest power of two.
  8757. * @param x Number to start search from.
  8758. * @return Next nearest power of two.
  8759. */
  8760. Tools.NearestPOT = function (x) {
  8761. var c = Tools.CeilingPOT(x);
  8762. var f = Tools.FloorPOT(x);
  8763. return (c - x) > (x - f) ? f : c;
  8764. };
  8765. Tools.GetExponentOfTwo = function (value, max, mode) {
  8766. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8767. var pot;
  8768. switch (mode) {
  8769. case BABYLON.Engine.SCALEMODE_FLOOR:
  8770. pot = Tools.FloorPOT(value);
  8771. break;
  8772. case BABYLON.Engine.SCALEMODE_NEAREST:
  8773. pot = Tools.NearestPOT(value);
  8774. break;
  8775. case BABYLON.Engine.SCALEMODE_CEILING:
  8776. default:
  8777. pot = Tools.CeilingPOT(value);
  8778. break;
  8779. }
  8780. return Math.min(pot, max);
  8781. };
  8782. Tools.GetFilename = function (path) {
  8783. var index = path.lastIndexOf("/");
  8784. if (index < 0)
  8785. return path;
  8786. return path.substring(index + 1);
  8787. };
  8788. /**
  8789. * Extracts the "folder" part of a path (everything before the filename).
  8790. * @param uri The URI to extract the info from
  8791. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8792. * @returns The "folder" part of the path
  8793. */
  8794. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8795. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8796. var index = uri.lastIndexOf("/");
  8797. if (index < 0) {
  8798. if (returnUnchangedIfNoSlash) {
  8799. return uri;
  8800. }
  8801. return "";
  8802. }
  8803. return uri.substring(0, index + 1);
  8804. };
  8805. Tools.GetDOMTextContent = function (element) {
  8806. var result = "";
  8807. var child = element.firstChild;
  8808. while (child) {
  8809. if (child.nodeType === 3) {
  8810. result += child.textContent;
  8811. }
  8812. child = child.nextSibling;
  8813. }
  8814. return result;
  8815. };
  8816. Tools.ToDegrees = function (angle) {
  8817. return angle * 180 / Math.PI;
  8818. };
  8819. Tools.ToRadians = function (angle) {
  8820. return angle * Math.PI / 180;
  8821. };
  8822. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8823. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8824. var output = "";
  8825. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8826. var i = 0;
  8827. var bytes = new Uint8Array(buffer);
  8828. while (i < bytes.length) {
  8829. chr1 = bytes[i++];
  8830. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8831. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8832. enc1 = chr1 >> 2;
  8833. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8834. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8835. enc4 = chr3 & 63;
  8836. if (isNaN(chr2)) {
  8837. enc3 = enc4 = 64;
  8838. }
  8839. else if (isNaN(chr3)) {
  8840. enc4 = 64;
  8841. }
  8842. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8843. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8844. }
  8845. return "data:image/png;base64," + output;
  8846. };
  8847. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8848. if (bias === void 0) { bias = null; }
  8849. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8850. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8851. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8852. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8853. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8854. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8855. }
  8856. if (bias) {
  8857. minimum.x -= minimum.x * bias.x + bias.y;
  8858. minimum.y -= minimum.y * bias.x + bias.y;
  8859. minimum.z -= minimum.z * bias.x + bias.y;
  8860. maximum.x += maximum.x * bias.x + bias.y;
  8861. maximum.y += maximum.y * bias.x + bias.y;
  8862. maximum.z += maximum.z * bias.x + bias.y;
  8863. }
  8864. return {
  8865. minimum: minimum,
  8866. maximum: maximum
  8867. };
  8868. };
  8869. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8870. if (bias === void 0) { bias = null; }
  8871. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8872. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8873. if (!stride) {
  8874. stride = 3;
  8875. }
  8876. for (var index = start; index < start + count; index++) {
  8877. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8878. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8879. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8880. }
  8881. if (bias) {
  8882. minimum.x -= minimum.x * bias.x + bias.y;
  8883. minimum.y -= minimum.y * bias.x + bias.y;
  8884. minimum.z -= minimum.z * bias.x + bias.y;
  8885. maximum.x += maximum.x * bias.x + bias.y;
  8886. maximum.y += maximum.y * bias.x + bias.y;
  8887. maximum.z += maximum.z * bias.x + bias.y;
  8888. }
  8889. return {
  8890. minimum: minimum,
  8891. maximum: maximum
  8892. };
  8893. };
  8894. Tools.Vector2ArrayFeeder = function (array) {
  8895. return function (index) {
  8896. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8897. var length = isFloatArray ? array.length / 2 : array.length;
  8898. if (index >= length) {
  8899. return null;
  8900. }
  8901. if (isFloatArray) {
  8902. var fa = array;
  8903. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8904. }
  8905. var a = array;
  8906. return a[index];
  8907. };
  8908. };
  8909. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8910. if (bias === void 0) { bias = null; }
  8911. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8912. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8913. var i = 0;
  8914. var cur = feeder(i++);
  8915. while (cur) {
  8916. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8917. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8918. cur = feeder(i++);
  8919. }
  8920. if (bias) {
  8921. minimum.x -= minimum.x * bias.x + bias.y;
  8922. minimum.y -= minimum.y * bias.x + bias.y;
  8923. maximum.x += maximum.x * bias.x + bias.y;
  8924. maximum.y += maximum.y * bias.x + bias.y;
  8925. }
  8926. return {
  8927. minimum: minimum,
  8928. maximum: maximum
  8929. };
  8930. };
  8931. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8932. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8933. return null;
  8934. return Array.isArray(obj) ? obj : [obj];
  8935. };
  8936. // Misc.
  8937. Tools.GetPointerPrefix = function () {
  8938. var eventPrefix = "pointer";
  8939. // Check if pointer events are supported
  8940. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8941. eventPrefix = "mouse";
  8942. }
  8943. return eventPrefix;
  8944. };
  8945. /**
  8946. * @param func - the function to be called
  8947. * @param requester - the object that will request the next frame. Falls back to window.
  8948. */
  8949. Tools.QueueNewFrame = function (func, requester) {
  8950. if (!Tools.IsWindowObjectExist()) {
  8951. return setTimeout(func, 16);
  8952. }
  8953. if (!requester) {
  8954. requester = window;
  8955. }
  8956. if (requester.requestAnimationFrame) {
  8957. return requester.requestAnimationFrame(func);
  8958. }
  8959. else if (requester.msRequestAnimationFrame) {
  8960. return requester.msRequestAnimationFrame(func);
  8961. }
  8962. else if (requester.webkitRequestAnimationFrame) {
  8963. return requester.webkitRequestAnimationFrame(func);
  8964. }
  8965. else if (requester.mozRequestAnimationFrame) {
  8966. return requester.mozRequestAnimationFrame(func);
  8967. }
  8968. else if (requester.oRequestAnimationFrame) {
  8969. return requester.oRequestAnimationFrame(func);
  8970. }
  8971. else {
  8972. return window.setTimeout(func, 16);
  8973. }
  8974. };
  8975. Tools.RequestFullscreen = function (element) {
  8976. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8977. if (!requestFunction)
  8978. return;
  8979. requestFunction.call(element);
  8980. };
  8981. Tools.ExitFullscreen = function () {
  8982. if (document.exitFullscreen) {
  8983. document.exitFullscreen();
  8984. }
  8985. else if (document.mozCancelFullScreen) {
  8986. document.mozCancelFullScreen();
  8987. }
  8988. else if (document.webkitCancelFullScreen) {
  8989. document.webkitCancelFullScreen();
  8990. }
  8991. else if (document.msCancelFullScreen) {
  8992. document.msCancelFullScreen();
  8993. }
  8994. };
  8995. Tools.SetCorsBehavior = function (url, element) {
  8996. if (url && url.indexOf("data:") === 0) {
  8997. return;
  8998. }
  8999. if (Tools.CorsBehavior) {
  9000. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  9001. element.crossOrigin = Tools.CorsBehavior;
  9002. }
  9003. else {
  9004. var result = Tools.CorsBehavior(url);
  9005. if (result) {
  9006. element.crossOrigin = result;
  9007. }
  9008. }
  9009. }
  9010. };
  9011. // External files
  9012. Tools.CleanUrl = function (url) {
  9013. url = url.replace(/#/mg, "%23");
  9014. return url;
  9015. };
  9016. /**
  9017. * Loads an image as an HTMLImageElement.
  9018. * @param input url string, ArrayBuffer, or Blob to load
  9019. * @param onLoad callback called when the image successfully loads
  9020. * @param onError callback called when the image fails to load
  9021. * @param database database for caching
  9022. * @returns the HTMLImageElement of the loaded image
  9023. */
  9024. Tools.LoadImage = function (input, onLoad, onError, database) {
  9025. var url;
  9026. var usingObjectURL = false;
  9027. if (input instanceof ArrayBuffer) {
  9028. url = URL.createObjectURL(new Blob([input]));
  9029. usingObjectURL = true;
  9030. }
  9031. else if (input instanceof Blob) {
  9032. url = URL.createObjectURL(input);
  9033. usingObjectURL = true;
  9034. }
  9035. else {
  9036. url = Tools.CleanUrl(input);
  9037. url = Tools.PreprocessUrl(input);
  9038. }
  9039. var img = new Image();
  9040. Tools.SetCorsBehavior(url, img);
  9041. var loadHandler = function () {
  9042. if (usingObjectURL && img.src) {
  9043. URL.revokeObjectURL(img.src);
  9044. }
  9045. img.removeEventListener("load", loadHandler);
  9046. img.removeEventListener("error", errorHandler);
  9047. onLoad(img);
  9048. };
  9049. var errorHandler = function (err) {
  9050. if (usingObjectURL && img.src) {
  9051. URL.revokeObjectURL(img.src);
  9052. }
  9053. img.removeEventListener("load", loadHandler);
  9054. img.removeEventListener("error", errorHandler);
  9055. Tools.Error("Error while trying to load image: " + input);
  9056. if (onError) {
  9057. onError("Error while trying to load image: " + input, err);
  9058. }
  9059. };
  9060. img.addEventListener("load", loadHandler);
  9061. img.addEventListener("error", errorHandler);
  9062. var noIndexedDB = function () {
  9063. img.src = url;
  9064. };
  9065. var loadFromIndexedDB = function () {
  9066. if (database) {
  9067. database.loadImageFromDB(url, img);
  9068. }
  9069. };
  9070. //ANY database to do!
  9071. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9072. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9073. }
  9074. else {
  9075. if (url.indexOf("file:") !== -1) {
  9076. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9077. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9078. try {
  9079. var blobURL;
  9080. try {
  9081. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9082. }
  9083. catch (ex) {
  9084. // Chrome doesn't support oneTimeOnly parameter
  9085. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9086. }
  9087. img.src = blobURL;
  9088. usingObjectURL = true;
  9089. }
  9090. catch (e) {
  9091. img.src = "";
  9092. }
  9093. return img;
  9094. }
  9095. }
  9096. noIndexedDB();
  9097. }
  9098. return img;
  9099. };
  9100. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9101. url = Tools.CleanUrl(url);
  9102. url = Tools.PreprocessUrl(url);
  9103. // If file and file input are set
  9104. if (url.indexOf("file:") !== -1) {
  9105. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9106. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9107. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9108. }
  9109. }
  9110. var loadUrl = Tools.BaseUrl + url;
  9111. var aborted = false;
  9112. var fileRequest = {
  9113. onCompleteObservable: new BABYLON.Observable(),
  9114. abort: function () { return aborted = true; },
  9115. };
  9116. var requestFile = function () {
  9117. var request = new XMLHttpRequest();
  9118. var retryHandle = null;
  9119. fileRequest.abort = function () {
  9120. aborted = true;
  9121. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9122. request.abort();
  9123. }
  9124. if (retryHandle !== null) {
  9125. clearTimeout(retryHandle);
  9126. retryHandle = null;
  9127. }
  9128. };
  9129. var retryLoop = function (retryIndex) {
  9130. request.open('GET', loadUrl, true);
  9131. if (useArrayBuffer) {
  9132. request.responseType = "arraybuffer";
  9133. }
  9134. if (onProgress) {
  9135. request.addEventListener("progress", onProgress);
  9136. }
  9137. var onLoadEnd = function () {
  9138. request.removeEventListener("loadend", onLoadEnd);
  9139. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9140. fileRequest.onCompleteObservable.clear();
  9141. };
  9142. request.addEventListener("loadend", onLoadEnd);
  9143. var onReadyStateChange = function () {
  9144. if (aborted) {
  9145. return;
  9146. }
  9147. // In case of undefined state in some browsers.
  9148. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9149. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9150. request.removeEventListener("readystatechange", onReadyStateChange);
  9151. if ((request.status >= 200 && request.status < 300) || (request.status === 0 && (!Tools.IsWindowObjectExist() || Tools.IsFileURL()))) {
  9152. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9153. return;
  9154. }
  9155. var retryStrategy = Tools.DefaultRetryStrategy;
  9156. if (retryStrategy) {
  9157. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9158. if (waitTime !== -1) {
  9159. // Prevent the request from completing for retry.
  9160. request.removeEventListener("loadend", onLoadEnd);
  9161. request = new XMLHttpRequest();
  9162. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9163. return;
  9164. }
  9165. }
  9166. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9167. if (onError) {
  9168. onError(request, e);
  9169. }
  9170. else {
  9171. throw e;
  9172. }
  9173. }
  9174. };
  9175. request.addEventListener("readystatechange", onReadyStateChange);
  9176. request.send();
  9177. };
  9178. retryLoop(0);
  9179. };
  9180. // Caching all files
  9181. if (database && database.enableSceneOffline) {
  9182. var noIndexedDB_1 = function (request) {
  9183. if (request && request.status > 400) {
  9184. if (onError) {
  9185. onError(request);
  9186. }
  9187. }
  9188. else {
  9189. if (!aborted) {
  9190. requestFile();
  9191. }
  9192. }
  9193. };
  9194. var loadFromIndexedDB = function () {
  9195. // TODO: database needs to support aborting and should return a IFileRequest
  9196. if (aborted) {
  9197. return;
  9198. }
  9199. if (database) {
  9200. database.loadFileFromDB(url, function (data) {
  9201. if (!aborted) {
  9202. onSuccess(data);
  9203. }
  9204. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9205. }, onProgress ? function (event) {
  9206. if (!aborted) {
  9207. onProgress(event);
  9208. }
  9209. } : undefined, noIndexedDB_1, useArrayBuffer);
  9210. }
  9211. };
  9212. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9213. }
  9214. else {
  9215. requestFile();
  9216. }
  9217. return fileRequest;
  9218. };
  9219. /**
  9220. * Load a script (identified by an url). When the url returns, the
  9221. * content of this file is added into a new script element, attached to the DOM (body element)
  9222. */
  9223. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9224. if (!Tools.IsWindowObjectExist()) {
  9225. return;
  9226. }
  9227. var head = document.getElementsByTagName('head')[0];
  9228. var script = document.createElement('script');
  9229. script.type = 'text/javascript';
  9230. script.src = scriptUrl;
  9231. script.onload = function () {
  9232. if (onSuccess) {
  9233. onSuccess();
  9234. }
  9235. };
  9236. script.onerror = function (e) {
  9237. if (onError) {
  9238. onError("Unable to load script '" + scriptUrl + "'", e);
  9239. }
  9240. };
  9241. head.appendChild(script);
  9242. };
  9243. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9244. var reader = new FileReader();
  9245. var request = {
  9246. onCompleteObservable: new BABYLON.Observable(),
  9247. abort: function () { return reader.abort(); },
  9248. };
  9249. reader.onloadend = function (e) {
  9250. request.onCompleteObservable.notifyObservers(request);
  9251. };
  9252. reader.onload = function (e) {
  9253. //target doesn't have result from ts 1.3
  9254. callback(e.target['result']);
  9255. };
  9256. reader.onprogress = progressCallback;
  9257. reader.readAsDataURL(fileToLoad);
  9258. return request;
  9259. };
  9260. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9261. var reader = new FileReader();
  9262. var request = {
  9263. onCompleteObservable: new BABYLON.Observable(),
  9264. abort: function () { return reader.abort(); },
  9265. };
  9266. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9267. reader.onerror = function (e) {
  9268. Tools.Log("Error while reading file: " + fileToLoad.name);
  9269. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9270. };
  9271. reader.onload = function (e) {
  9272. //target doesn't have result from ts 1.3
  9273. callback(e.target['result']);
  9274. };
  9275. if (progressCallBack) {
  9276. reader.onprogress = progressCallBack;
  9277. }
  9278. if (!useArrayBuffer) {
  9279. // Asynchronous read
  9280. reader.readAsText(fileToLoad);
  9281. }
  9282. else {
  9283. reader.readAsArrayBuffer(fileToLoad);
  9284. }
  9285. return request;
  9286. };
  9287. //returns a downloadable url to a file content.
  9288. Tools.FileAsURL = function (content) {
  9289. var fileBlob = new Blob([content]);
  9290. var url = window.URL || window.webkitURL;
  9291. var link = url.createObjectURL(fileBlob);
  9292. return link;
  9293. };
  9294. // Misc.
  9295. Tools.Format = function (value, decimals) {
  9296. if (decimals === void 0) { decimals = 2; }
  9297. return value.toFixed(decimals);
  9298. };
  9299. Tools.CheckExtends = function (v, min, max) {
  9300. if (v.x < min.x)
  9301. min.x = v.x;
  9302. if (v.y < min.y)
  9303. min.y = v.y;
  9304. if (v.z < min.z)
  9305. min.z = v.z;
  9306. if (v.x > max.x)
  9307. max.x = v.x;
  9308. if (v.y > max.y)
  9309. max.y = v.y;
  9310. if (v.z > max.z)
  9311. max.z = v.z;
  9312. };
  9313. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9314. for (var prop in source) {
  9315. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9316. continue;
  9317. }
  9318. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9319. continue;
  9320. }
  9321. var sourceValue = source[prop];
  9322. var typeOfSourceValue = typeof sourceValue;
  9323. if (typeOfSourceValue === "function") {
  9324. continue;
  9325. }
  9326. try {
  9327. if (typeOfSourceValue === "object") {
  9328. if (sourceValue instanceof Array) {
  9329. destination[prop] = [];
  9330. if (sourceValue.length > 0) {
  9331. if (typeof sourceValue[0] == "object") {
  9332. for (var index = 0; index < sourceValue.length; index++) {
  9333. var clonedValue = cloneValue(sourceValue[index], destination);
  9334. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9335. destination[prop].push(clonedValue);
  9336. }
  9337. }
  9338. }
  9339. else {
  9340. destination[prop] = sourceValue.slice(0);
  9341. }
  9342. }
  9343. }
  9344. else {
  9345. destination[prop] = cloneValue(sourceValue, destination);
  9346. }
  9347. }
  9348. else {
  9349. destination[prop] = sourceValue;
  9350. }
  9351. }
  9352. catch (e) {
  9353. // Just ignore error (it could be because of a read-only property)
  9354. }
  9355. }
  9356. };
  9357. Tools.IsEmpty = function (obj) {
  9358. for (var i in obj) {
  9359. if (obj.hasOwnProperty(i)) {
  9360. return false;
  9361. }
  9362. }
  9363. return true;
  9364. };
  9365. Tools.RegisterTopRootEvents = function (events) {
  9366. for (var index = 0; index < events.length; index++) {
  9367. var event = events[index];
  9368. window.addEventListener(event.name, event.handler, false);
  9369. try {
  9370. if (window.parent) {
  9371. window.parent.addEventListener(event.name, event.handler, false);
  9372. }
  9373. }
  9374. catch (e) {
  9375. // Silently fails...
  9376. }
  9377. }
  9378. };
  9379. Tools.UnregisterTopRootEvents = function (events) {
  9380. for (var index = 0; index < events.length; index++) {
  9381. var event = events[index];
  9382. window.removeEventListener(event.name, event.handler);
  9383. try {
  9384. if (window.parent) {
  9385. window.parent.removeEventListener(event.name, event.handler);
  9386. }
  9387. }
  9388. catch (e) {
  9389. // Silently fails...
  9390. }
  9391. }
  9392. };
  9393. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9394. if (mimeType === void 0) { mimeType = "image/png"; }
  9395. // Read the contents of the framebuffer
  9396. var numberOfChannelsByLine = width * 4;
  9397. var halfHeight = height / 2;
  9398. //Reading datas from WebGL
  9399. var data = engine.readPixels(0, 0, width, height);
  9400. //To flip image on Y axis.
  9401. for (var i = 0; i < halfHeight; i++) {
  9402. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9403. var currentCell = j + i * numberOfChannelsByLine;
  9404. var targetLine = height - i - 1;
  9405. var targetCell = j + targetLine * numberOfChannelsByLine;
  9406. var temp = data[currentCell];
  9407. data[currentCell] = data[targetCell];
  9408. data[targetCell] = temp;
  9409. }
  9410. }
  9411. // Create a 2D canvas to store the result
  9412. if (!screenshotCanvas) {
  9413. screenshotCanvas = document.createElement('canvas');
  9414. }
  9415. screenshotCanvas.width = width;
  9416. screenshotCanvas.height = height;
  9417. var context = screenshotCanvas.getContext('2d');
  9418. if (context) {
  9419. // Copy the pixels to a 2D canvas
  9420. var imageData = context.createImageData(width, height);
  9421. var castData = (imageData.data);
  9422. castData.set(data);
  9423. context.putImageData(imageData, 0, 0);
  9424. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9425. }
  9426. };
  9427. /**
  9428. * Converts the canvas data to blob.
  9429. * This acts as a polyfill for browsers not supporting the to blob function.
  9430. * @param canvas Defines the canvas to extract the data from
  9431. * @param successCallback Defines the callback triggered once the data are available
  9432. * @param mimeType Defines the mime type of the result
  9433. */
  9434. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  9435. if (mimeType === void 0) { mimeType = "image/png"; }
  9436. // We need HTMLCanvasElement.toBlob for HD screenshots
  9437. if (!canvas.toBlob) {
  9438. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9439. canvas.toBlob = function (callback, type, quality) {
  9440. var _this = this;
  9441. setTimeout(function () {
  9442. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9443. for (var i = 0; i < len; i++) {
  9444. arr[i] = binStr.charCodeAt(i);
  9445. }
  9446. callback(new Blob([arr]));
  9447. });
  9448. };
  9449. }
  9450. canvas.toBlob(function (blob) {
  9451. successCallback(blob);
  9452. }, mimeType);
  9453. };
  9454. /**
  9455. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  9456. * @param successCallback Defines the callback triggered once the data are available
  9457. * @param mimeType Defines the mime type of the result
  9458. * @param fileName The filename to download. If present, the result will automatically be downloaded
  9459. */
  9460. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9461. if (mimeType === void 0) { mimeType = "image/png"; }
  9462. if (successCallback) {
  9463. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9464. successCallback(base64Image);
  9465. }
  9466. else {
  9467. this.ToBlob(screenshotCanvas, function (blob) {
  9468. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9469. if (("download" in document.createElement("a"))) {
  9470. if (!fileName) {
  9471. var date = new Date();
  9472. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9473. fileName = "screenshot_" + stringDate + ".png";
  9474. }
  9475. Tools.Download(blob, fileName);
  9476. }
  9477. else {
  9478. var url = URL.createObjectURL(blob);
  9479. var newWindow = window.open("");
  9480. if (!newWindow)
  9481. return;
  9482. var img = newWindow.document.createElement("img");
  9483. img.onload = function () {
  9484. // no longer need to read the blob so it's revoked
  9485. URL.revokeObjectURL(url);
  9486. };
  9487. img.src = url;
  9488. newWindow.document.body.appendChild(img);
  9489. }
  9490. }, mimeType);
  9491. }
  9492. };
  9493. /**
  9494. * Downloads a blob in the browser
  9495. * @param blob defines the blob to download
  9496. * @param fileName defines the name of the downloaded file
  9497. */
  9498. Tools.Download = function (blob, fileName) {
  9499. if (navigator && navigator.msSaveBlob) {
  9500. navigator.msSaveBlob(blob, fileName);
  9501. return;
  9502. }
  9503. var url = window.URL.createObjectURL(blob);
  9504. var a = document.createElement("a");
  9505. document.body.appendChild(a);
  9506. a.style.display = "none";
  9507. a.href = url;
  9508. a.download = fileName;
  9509. a.addEventListener("click", function () {
  9510. if (a.parentElement) {
  9511. a.parentElement.removeChild(a);
  9512. }
  9513. });
  9514. a.click();
  9515. window.URL.revokeObjectURL(url);
  9516. };
  9517. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9518. if (mimeType === void 0) { mimeType = "image/png"; }
  9519. var width;
  9520. var height;
  9521. // If a precision value is specified
  9522. if (size.precision) {
  9523. width = Math.round(engine.getRenderWidth() * size.precision);
  9524. height = Math.round(width / engine.getAspectRatio(camera));
  9525. }
  9526. else if (size.width && size.height) {
  9527. width = size.width;
  9528. height = size.height;
  9529. }
  9530. //If passing only width, computing height to keep display canvas ratio.
  9531. else if (size.width && !size.height) {
  9532. width = size.width;
  9533. height = Math.round(width / engine.getAspectRatio(camera));
  9534. }
  9535. //If passing only height, computing width to keep display canvas ratio.
  9536. else if (size.height && !size.width) {
  9537. height = size.height;
  9538. width = Math.round(height * engine.getAspectRatio(camera));
  9539. }
  9540. //Assuming here that "size" parameter is a number
  9541. else if (!isNaN(size)) {
  9542. height = size;
  9543. width = size;
  9544. }
  9545. else {
  9546. Tools.Error("Invalid 'size' parameter !");
  9547. return;
  9548. }
  9549. if (!screenshotCanvas) {
  9550. screenshotCanvas = document.createElement('canvas');
  9551. }
  9552. screenshotCanvas.width = width;
  9553. screenshotCanvas.height = height;
  9554. var renderContext = screenshotCanvas.getContext("2d");
  9555. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9556. var newWidth = width;
  9557. var newHeight = newWidth / ratio;
  9558. if (newHeight > height) {
  9559. newHeight = height;
  9560. newWidth = newHeight * ratio;
  9561. }
  9562. var offsetX = Math.max(0, width - newWidth) / 2;
  9563. var offsetY = Math.max(0, height - newHeight) / 2;
  9564. var renderingCanvas = engine.getRenderingCanvas();
  9565. if (renderContext && renderingCanvas) {
  9566. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9567. }
  9568. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9569. };
  9570. /**
  9571. * Generates an image screenshot from the specified camera.
  9572. *
  9573. * @param engine The engine to use for rendering
  9574. * @param camera The camera to use for rendering
  9575. * @param size This parameter can be set to a single number or to an object with the
  9576. * following (optional) properties: precision, width, height. If a single number is passed,
  9577. * it will be used for both width and height. If an object is passed, the screenshot size
  9578. * will be derived from the parameters. The precision property is a multiplier allowing
  9579. * rendering at a higher or lower resolution.
  9580. * @param successCallback The callback receives a single parameter which contains the
  9581. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9582. * src parameter of an <img> to display it.
  9583. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9584. * Check your browser for supported MIME types.
  9585. * @param samples Texture samples (default: 1)
  9586. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9587. * @param fileName A name for for the downloaded file.
  9588. * @constructor
  9589. */
  9590. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9591. if (mimeType === void 0) { mimeType = "image/png"; }
  9592. if (samples === void 0) { samples = 1; }
  9593. if (antialiasing === void 0) { antialiasing = false; }
  9594. var width;
  9595. var height;
  9596. //If a precision value is specified
  9597. if (size.precision) {
  9598. width = Math.round(engine.getRenderWidth() * size.precision);
  9599. height = Math.round(width / engine.getAspectRatio(camera));
  9600. size = { width: width, height: height };
  9601. }
  9602. else if (size.width && size.height) {
  9603. width = size.width;
  9604. height = size.height;
  9605. }
  9606. //If passing only width, computing height to keep display canvas ratio.
  9607. else if (size.width && !size.height) {
  9608. width = size.width;
  9609. height = Math.round(width / engine.getAspectRatio(camera));
  9610. size = { width: width, height: height };
  9611. }
  9612. //If passing only height, computing width to keep display canvas ratio.
  9613. else if (size.height && !size.width) {
  9614. height = size.height;
  9615. width = Math.round(height * engine.getAspectRatio(camera));
  9616. size = { width: width, height: height };
  9617. }
  9618. //Assuming here that "size" parameter is a number
  9619. else if (!isNaN(size)) {
  9620. height = size;
  9621. width = size;
  9622. }
  9623. else {
  9624. Tools.Error("Invalid 'size' parameter !");
  9625. return;
  9626. }
  9627. var scene = camera.getScene();
  9628. var previousCamera = null;
  9629. if (scene.activeCamera !== camera) {
  9630. previousCamera = scene.activeCamera;
  9631. scene.activeCamera = camera;
  9632. }
  9633. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9634. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9635. texture.renderList = null;
  9636. texture.samples = samples;
  9637. if (antialiasing) {
  9638. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9639. }
  9640. texture.onAfterRenderObservable.add(function () {
  9641. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9642. });
  9643. scene.incrementRenderId();
  9644. scene.resetCachedMaterial();
  9645. texture.render(true);
  9646. texture.dispose();
  9647. if (previousCamera) {
  9648. scene.activeCamera = previousCamera;
  9649. }
  9650. camera.getProjectionMatrix(true); // Force cache refresh;
  9651. };
  9652. // XHR response validator for local file scenario
  9653. Tools.ValidateXHRData = function (xhr, dataType) {
  9654. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9655. if (dataType === void 0) { dataType = 7; }
  9656. try {
  9657. if (dataType & 1) {
  9658. if (xhr.responseText && xhr.responseText.length > 0) {
  9659. return true;
  9660. }
  9661. else if (dataType === 1) {
  9662. return false;
  9663. }
  9664. }
  9665. if (dataType & 2) {
  9666. // Check header width and height since there is no "TGA" magic number
  9667. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9668. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9669. return true;
  9670. }
  9671. else if (dataType === 2) {
  9672. return false;
  9673. }
  9674. }
  9675. if (dataType & 4) {
  9676. // Check for the "DDS" magic number
  9677. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9678. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9679. return true;
  9680. }
  9681. else {
  9682. return false;
  9683. }
  9684. }
  9685. }
  9686. catch (e) {
  9687. // Global protection
  9688. }
  9689. return false;
  9690. };
  9691. /**
  9692. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9693. * Be aware Math.random() could cause collisions, but:
  9694. * "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"
  9695. */
  9696. Tools.RandomId = function () {
  9697. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9698. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9699. return v.toString(16);
  9700. });
  9701. };
  9702. /**
  9703. * Test if the given uri is a base64 string.
  9704. * @param uri The uri to test
  9705. * @return True if the uri is a base64 string or false otherwise.
  9706. */
  9707. Tools.IsBase64 = function (uri) {
  9708. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9709. };
  9710. /**
  9711. * Decode the given base64 uri.
  9712. * @param uri The uri to decode
  9713. * @return The decoded base64 data.
  9714. */
  9715. Tools.DecodeBase64 = function (uri) {
  9716. var decodedString = atob(uri.split(",")[1]);
  9717. var bufferLength = decodedString.length;
  9718. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9719. for (var i = 0; i < bufferLength; i++) {
  9720. bufferView[i] = decodedString.charCodeAt(i);
  9721. }
  9722. return bufferView.buffer;
  9723. };
  9724. Object.defineProperty(Tools, "NoneLogLevel", {
  9725. get: function () {
  9726. return Tools._NoneLogLevel;
  9727. },
  9728. enumerable: true,
  9729. configurable: true
  9730. });
  9731. Object.defineProperty(Tools, "MessageLogLevel", {
  9732. get: function () {
  9733. return Tools._MessageLogLevel;
  9734. },
  9735. enumerable: true,
  9736. configurable: true
  9737. });
  9738. Object.defineProperty(Tools, "WarningLogLevel", {
  9739. get: function () {
  9740. return Tools._WarningLogLevel;
  9741. },
  9742. enumerable: true,
  9743. configurable: true
  9744. });
  9745. Object.defineProperty(Tools, "ErrorLogLevel", {
  9746. get: function () {
  9747. return Tools._ErrorLogLevel;
  9748. },
  9749. enumerable: true,
  9750. configurable: true
  9751. });
  9752. Object.defineProperty(Tools, "AllLogLevel", {
  9753. get: function () {
  9754. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9755. },
  9756. enumerable: true,
  9757. configurable: true
  9758. });
  9759. Tools._AddLogEntry = function (entry) {
  9760. Tools._LogCache = entry + Tools._LogCache;
  9761. if (Tools.OnNewCacheEntry) {
  9762. Tools.OnNewCacheEntry(entry);
  9763. }
  9764. };
  9765. Tools._FormatMessage = function (message) {
  9766. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9767. var date = new Date();
  9768. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9769. };
  9770. Tools._LogDisabled = function (message) {
  9771. // nothing to do
  9772. };
  9773. Tools._LogEnabled = function (message) {
  9774. var formattedMessage = Tools._FormatMessage(message);
  9775. console.log("BJS - " + formattedMessage);
  9776. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9777. Tools._AddLogEntry(entry);
  9778. };
  9779. Tools._WarnDisabled = function (message) {
  9780. // nothing to do
  9781. };
  9782. Tools._WarnEnabled = function (message) {
  9783. var formattedMessage = Tools._FormatMessage(message);
  9784. console.warn("BJS - " + formattedMessage);
  9785. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9786. Tools._AddLogEntry(entry);
  9787. };
  9788. Tools._ErrorDisabled = function (message) {
  9789. // nothing to do
  9790. };
  9791. Tools._ErrorEnabled = function (message) {
  9792. Tools.errorsCount++;
  9793. var formattedMessage = Tools._FormatMessage(message);
  9794. console.error("BJS - " + formattedMessage);
  9795. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9796. Tools._AddLogEntry(entry);
  9797. };
  9798. Object.defineProperty(Tools, "LogCache", {
  9799. get: function () {
  9800. return Tools._LogCache;
  9801. },
  9802. enumerable: true,
  9803. configurable: true
  9804. });
  9805. Tools.ClearLogCache = function () {
  9806. Tools._LogCache = "";
  9807. Tools.errorsCount = 0;
  9808. };
  9809. Object.defineProperty(Tools, "LogLevels", {
  9810. set: function (level) {
  9811. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9812. Tools.Log = Tools._LogEnabled;
  9813. }
  9814. else {
  9815. Tools.Log = Tools._LogDisabled;
  9816. }
  9817. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9818. Tools.Warn = Tools._WarnEnabled;
  9819. }
  9820. else {
  9821. Tools.Warn = Tools._WarnDisabled;
  9822. }
  9823. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9824. Tools.Error = Tools._ErrorEnabled;
  9825. }
  9826. else {
  9827. Tools.Error = Tools._ErrorDisabled;
  9828. }
  9829. },
  9830. enumerable: true,
  9831. configurable: true
  9832. });
  9833. /**
  9834. * Check if the loaded document was accessed via `file:`-Protocol.
  9835. * @returns boolean
  9836. */
  9837. Tools.IsFileURL = function () {
  9838. return location.protocol === "file:";
  9839. };
  9840. Tools.IsWindowObjectExist = function () {
  9841. return (typeof window) !== "undefined";
  9842. };
  9843. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9844. get: function () {
  9845. return Tools._PerformanceNoneLogLevel;
  9846. },
  9847. enumerable: true,
  9848. configurable: true
  9849. });
  9850. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9851. get: function () {
  9852. return Tools._PerformanceUserMarkLogLevel;
  9853. },
  9854. enumerable: true,
  9855. configurable: true
  9856. });
  9857. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9858. get: function () {
  9859. return Tools._PerformanceConsoleLogLevel;
  9860. },
  9861. enumerable: true,
  9862. configurable: true
  9863. });
  9864. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9865. set: function (level) {
  9866. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9867. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9868. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9869. return;
  9870. }
  9871. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9872. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9873. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9874. return;
  9875. }
  9876. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9877. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9878. },
  9879. enumerable: true,
  9880. configurable: true
  9881. });
  9882. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9883. };
  9884. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9885. };
  9886. Tools._StartUserMark = function (counterName, condition) {
  9887. if (condition === void 0) { condition = true; }
  9888. if (!Tools._performance) {
  9889. if (!Tools.IsWindowObjectExist()) {
  9890. return;
  9891. }
  9892. Tools._performance = window.performance;
  9893. }
  9894. if (!condition || !Tools._performance.mark) {
  9895. return;
  9896. }
  9897. Tools._performance.mark(counterName + "-Begin");
  9898. };
  9899. Tools._EndUserMark = function (counterName, condition) {
  9900. if (condition === void 0) { condition = true; }
  9901. if (!condition || !Tools._performance.mark) {
  9902. return;
  9903. }
  9904. Tools._performance.mark(counterName + "-End");
  9905. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9906. };
  9907. Tools._StartPerformanceConsole = function (counterName, condition) {
  9908. if (condition === void 0) { condition = true; }
  9909. if (!condition) {
  9910. return;
  9911. }
  9912. Tools._StartUserMark(counterName, condition);
  9913. if (console.time) {
  9914. console.time(counterName);
  9915. }
  9916. };
  9917. Tools._EndPerformanceConsole = function (counterName, condition) {
  9918. if (condition === void 0) { condition = true; }
  9919. if (!condition) {
  9920. return;
  9921. }
  9922. Tools._EndUserMark(counterName, condition);
  9923. if (console.time) {
  9924. console.timeEnd(counterName);
  9925. }
  9926. };
  9927. Object.defineProperty(Tools, "Now", {
  9928. get: function () {
  9929. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9930. return window.performance.now();
  9931. }
  9932. return Date.now();
  9933. },
  9934. enumerable: true,
  9935. configurable: true
  9936. });
  9937. /**
  9938. * This method will return the name of the class used to create the instance of the given object.
  9939. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9940. * @param object the object to get the class name from
  9941. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9942. */
  9943. Tools.GetClassName = function (object, isType) {
  9944. if (isType === void 0) { isType = false; }
  9945. var name = null;
  9946. if (!isType && object.getClassName) {
  9947. name = object.getClassName();
  9948. }
  9949. else {
  9950. if (object instanceof Object) {
  9951. var classObj = isType ? object : Object.getPrototypeOf(object);
  9952. name = classObj.constructor["__bjsclassName__"];
  9953. }
  9954. if (!name) {
  9955. name = typeof object;
  9956. }
  9957. }
  9958. return name;
  9959. };
  9960. Tools.First = function (array, predicate) {
  9961. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9962. var el = array_1[_i];
  9963. if (predicate(el)) {
  9964. return el;
  9965. }
  9966. }
  9967. return null;
  9968. };
  9969. /**
  9970. * This method will return the name of the full name of the class, including its owning module (if any).
  9971. * 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).
  9972. * @param object the object to get the class name from
  9973. * @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.
  9974. */
  9975. Tools.getFullClassName = function (object, isType) {
  9976. if (isType === void 0) { isType = false; }
  9977. var className = null;
  9978. var moduleName = null;
  9979. if (!isType && object.getClassName) {
  9980. className = object.getClassName();
  9981. }
  9982. else {
  9983. if (object instanceof Object) {
  9984. var classObj = isType ? object : Object.getPrototypeOf(object);
  9985. className = classObj.constructor["__bjsclassName__"];
  9986. moduleName = classObj.constructor["__bjsmoduleName__"];
  9987. }
  9988. if (!className) {
  9989. className = typeof object;
  9990. }
  9991. }
  9992. if (!className) {
  9993. return null;
  9994. }
  9995. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9996. };
  9997. /**
  9998. * 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.
  9999. * @param array
  10000. */
  10001. Tools.arrayOrStringFeeder = function (array) {
  10002. return function (index) {
  10003. if (index >= array.length) {
  10004. return null;
  10005. }
  10006. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  10007. if (val && val.getHashCode) {
  10008. val = val.getHashCode();
  10009. }
  10010. if (typeof val === "string") {
  10011. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  10012. }
  10013. return val;
  10014. };
  10015. };
  10016. /**
  10017. * Compute the hashCode of a stream of number
  10018. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  10019. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  10020. * @return the hash code computed
  10021. */
  10022. Tools.hashCodeFromStream = function (feeder) {
  10023. // Based from here: http://stackoverflow.com/a/7616484/802124
  10024. var hash = 0;
  10025. var index = 0;
  10026. var chr = feeder(index++);
  10027. while (chr != null) {
  10028. hash = ((hash << 5) - hash) + chr;
  10029. hash |= 0; // Convert to 32bit integer
  10030. chr = feeder(index++);
  10031. }
  10032. return hash;
  10033. };
  10034. /**
  10035. * Returns a promise that resolves after the given amount of time.
  10036. * @param delay Number of milliseconds to delay
  10037. * @returns Promise that resolves after the given amount of time
  10038. */
  10039. Tools.DelayAsync = function (delay) {
  10040. return new Promise(function (resolve) {
  10041. setTimeout(function () {
  10042. resolve();
  10043. }, delay);
  10044. });
  10045. };
  10046. /**
  10047. * Gets the current gradient from an array of IValueGradient
  10048. * @param ratio defines the current ratio to get
  10049. * @param gradients defines the array of IValueGradient
  10050. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  10051. */
  10052. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  10053. if (gradients.length === 1) {
  10054. updateFunc(gradients[0], gradients[0], 0);
  10055. return;
  10056. }
  10057. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  10058. var currentGradient = gradients[gradientIndex];
  10059. var nextGradient = gradients[gradientIndex + 1];
  10060. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  10061. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  10062. updateFunc(currentGradient, nextGradient, scale);
  10063. }
  10064. }
  10065. };
  10066. Tools.BaseUrl = "";
  10067. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  10068. /**
  10069. * Default behaviour for cors in the application.
  10070. * It can be a string if the expected behavior is identical in the entire app.
  10071. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  10072. */
  10073. Tools.CorsBehavior = "anonymous";
  10074. Tools.UseFallbackTexture = true;
  10075. /**
  10076. * Use this object to register external classes like custom textures or material
  10077. * to allow the laoders to instantiate them
  10078. */
  10079. Tools.RegisteredExternalClasses = {};
  10080. // Used in case of a texture loading problem
  10081. 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";
  10082. Tools._tmpFloatArray = new Float32Array(1);
  10083. Tools.PreprocessUrl = function (url) {
  10084. return url;
  10085. };
  10086. // Logs
  10087. Tools._NoneLogLevel = 0;
  10088. Tools._MessageLogLevel = 1;
  10089. Tools._WarningLogLevel = 2;
  10090. Tools._ErrorLogLevel = 4;
  10091. Tools._LogCache = "";
  10092. Tools.errorsCount = 0;
  10093. Tools.Log = Tools._LogEnabled;
  10094. Tools.Warn = Tools._WarnEnabled;
  10095. Tools.Error = Tools._ErrorEnabled;
  10096. // Performances
  10097. Tools._PerformanceNoneLogLevel = 0;
  10098. Tools._PerformanceUserMarkLogLevel = 1;
  10099. Tools._PerformanceConsoleLogLevel = 2;
  10100. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10101. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10102. return Tools;
  10103. }());
  10104. BABYLON.Tools = Tools;
  10105. /**
  10106. * This class is used to track a performance counter which is number based.
  10107. * The user has access to many properties which give statistics of different nature
  10108. *
  10109. * The implementer can track two kinds of Performance Counter: time and count
  10110. * 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.
  10111. * 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.
  10112. */
  10113. var PerfCounter = /** @class */ (function () {
  10114. function PerfCounter() {
  10115. this._startMonitoringTime = 0;
  10116. this._min = 0;
  10117. this._max = 0;
  10118. this._average = 0;
  10119. this._lastSecAverage = 0;
  10120. this._current = 0;
  10121. this._totalValueCount = 0;
  10122. this._totalAccumulated = 0;
  10123. this._lastSecAccumulated = 0;
  10124. this._lastSecTime = 0;
  10125. this._lastSecValueCount = 0;
  10126. }
  10127. Object.defineProperty(PerfCounter.prototype, "min", {
  10128. /**
  10129. * Returns the smallest value ever
  10130. */
  10131. get: function () {
  10132. return this._min;
  10133. },
  10134. enumerable: true,
  10135. configurable: true
  10136. });
  10137. Object.defineProperty(PerfCounter.prototype, "max", {
  10138. /**
  10139. * Returns the biggest value ever
  10140. */
  10141. get: function () {
  10142. return this._max;
  10143. },
  10144. enumerable: true,
  10145. configurable: true
  10146. });
  10147. Object.defineProperty(PerfCounter.prototype, "average", {
  10148. /**
  10149. * Returns the average value since the performance counter is running
  10150. */
  10151. get: function () {
  10152. return this._average;
  10153. },
  10154. enumerable: true,
  10155. configurable: true
  10156. });
  10157. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10158. /**
  10159. * Returns the average value of the last second the counter was monitored
  10160. */
  10161. get: function () {
  10162. return this._lastSecAverage;
  10163. },
  10164. enumerable: true,
  10165. configurable: true
  10166. });
  10167. Object.defineProperty(PerfCounter.prototype, "current", {
  10168. /**
  10169. * Returns the current value
  10170. */
  10171. get: function () {
  10172. return this._current;
  10173. },
  10174. enumerable: true,
  10175. configurable: true
  10176. });
  10177. Object.defineProperty(PerfCounter.prototype, "total", {
  10178. get: function () {
  10179. return this._totalAccumulated;
  10180. },
  10181. enumerable: true,
  10182. configurable: true
  10183. });
  10184. Object.defineProperty(PerfCounter.prototype, "count", {
  10185. get: function () {
  10186. return this._totalValueCount;
  10187. },
  10188. enumerable: true,
  10189. configurable: true
  10190. });
  10191. /**
  10192. * Call this method to start monitoring a new frame.
  10193. * 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.
  10194. */
  10195. PerfCounter.prototype.fetchNewFrame = function () {
  10196. this._totalValueCount++;
  10197. this._current = 0;
  10198. this._lastSecValueCount++;
  10199. };
  10200. /**
  10201. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10202. * @param newCount the count value to add to the monitored count
  10203. * @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.
  10204. */
  10205. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10206. if (!PerfCounter.Enabled) {
  10207. return;
  10208. }
  10209. this._current += newCount;
  10210. if (fetchResult) {
  10211. this._fetchResult();
  10212. }
  10213. };
  10214. /**
  10215. * Start monitoring this performance counter
  10216. */
  10217. PerfCounter.prototype.beginMonitoring = function () {
  10218. if (!PerfCounter.Enabled) {
  10219. return;
  10220. }
  10221. this._startMonitoringTime = Tools.Now;
  10222. };
  10223. /**
  10224. * Compute the time lapsed since the previous beginMonitoring() call.
  10225. * @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
  10226. */
  10227. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10228. if (newFrame === void 0) { newFrame = true; }
  10229. if (!PerfCounter.Enabled) {
  10230. return;
  10231. }
  10232. if (newFrame) {
  10233. this.fetchNewFrame();
  10234. }
  10235. var currentTime = Tools.Now;
  10236. this._current = currentTime - this._startMonitoringTime;
  10237. if (newFrame) {
  10238. this._fetchResult();
  10239. }
  10240. };
  10241. PerfCounter.prototype._fetchResult = function () {
  10242. this._totalAccumulated += this._current;
  10243. this._lastSecAccumulated += this._current;
  10244. // Min/Max update
  10245. this._min = Math.min(this._min, this._current);
  10246. this._max = Math.max(this._max, this._current);
  10247. this._average = this._totalAccumulated / this._totalValueCount;
  10248. // Reset last sec?
  10249. var now = Tools.Now;
  10250. if ((now - this._lastSecTime) > 1000) {
  10251. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10252. this._lastSecTime = now;
  10253. this._lastSecAccumulated = 0;
  10254. this._lastSecValueCount = 0;
  10255. }
  10256. };
  10257. PerfCounter.Enabled = true;
  10258. return PerfCounter;
  10259. }());
  10260. BABYLON.PerfCounter = PerfCounter;
  10261. /**
  10262. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10263. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10264. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10265. * @param name The name of the class, case should be preserved
  10266. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10267. */
  10268. function className(name, module) {
  10269. return function (target) {
  10270. target["__bjsclassName__"] = name;
  10271. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10272. };
  10273. }
  10274. BABYLON.className = className;
  10275. /**
  10276. * An implementation of a loop for asynchronous functions.
  10277. */
  10278. var AsyncLoop = /** @class */ (function () {
  10279. /**
  10280. * Constroctor.
  10281. * @param iterations the number of iterations.
  10282. * @param _fn the function to run each iteration
  10283. * @param _successCallback the callback that will be called upon succesful execution
  10284. * @param offset starting offset.
  10285. */
  10286. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10287. if (offset === void 0) { offset = 0; }
  10288. this.iterations = iterations;
  10289. this._fn = _fn;
  10290. this._successCallback = _successCallback;
  10291. this.index = offset - 1;
  10292. this._done = false;
  10293. }
  10294. /**
  10295. * Execute the next iteration. Must be called after the last iteration was finished.
  10296. */
  10297. AsyncLoop.prototype.executeNext = function () {
  10298. if (!this._done) {
  10299. if (this.index + 1 < this.iterations) {
  10300. ++this.index;
  10301. this._fn(this);
  10302. }
  10303. else {
  10304. this.breakLoop();
  10305. }
  10306. }
  10307. };
  10308. /**
  10309. * Break the loop and run the success callback.
  10310. */
  10311. AsyncLoop.prototype.breakLoop = function () {
  10312. this._done = true;
  10313. this._successCallback();
  10314. };
  10315. /**
  10316. * Helper function
  10317. */
  10318. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10319. if (offset === void 0) { offset = 0; }
  10320. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10321. loop.executeNext();
  10322. return loop;
  10323. };
  10324. /**
  10325. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10326. * @param iterations total number of iterations
  10327. * @param syncedIterations number of synchronous iterations in each async iteration.
  10328. * @param fn the function to call each iteration.
  10329. * @param callback a success call back that will be called when iterating stops.
  10330. * @param breakFunction a break condition (optional)
  10331. * @param timeout timeout settings for the setTimeout function. default - 0.
  10332. * @constructor
  10333. */
  10334. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10335. if (timeout === void 0) { timeout = 0; }
  10336. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10337. if (breakFunction && breakFunction())
  10338. loop.breakLoop();
  10339. else {
  10340. setTimeout(function () {
  10341. for (var i = 0; i < syncedIterations; ++i) {
  10342. var iteration = (loop.index * syncedIterations) + i;
  10343. if (iteration >= iterations)
  10344. break;
  10345. fn(iteration);
  10346. if (breakFunction && breakFunction()) {
  10347. loop.breakLoop();
  10348. break;
  10349. }
  10350. }
  10351. loop.executeNext();
  10352. }, timeout);
  10353. }
  10354. }, callback);
  10355. };
  10356. return AsyncLoop;
  10357. }());
  10358. BABYLON.AsyncLoop = AsyncLoop;
  10359. })(BABYLON || (BABYLON = {}));
  10360. //# sourceMappingURL=babylon.tools.js.map
  10361. var BABYLON;
  10362. (function (BABYLON) {
  10363. var PromiseStates;
  10364. (function (PromiseStates) {
  10365. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10366. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10367. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10368. })(PromiseStates || (PromiseStates = {}));
  10369. var FulFillmentAgregator = /** @class */ (function () {
  10370. function FulFillmentAgregator() {
  10371. this.count = 0;
  10372. this.target = 0;
  10373. this.results = [];
  10374. }
  10375. return FulFillmentAgregator;
  10376. }());
  10377. var InternalPromise = /** @class */ (function () {
  10378. function InternalPromise(resolver) {
  10379. var _this = this;
  10380. this._state = PromiseStates.Pending;
  10381. this._children = new Array();
  10382. this._rejectWasConsumed = false;
  10383. if (!resolver) {
  10384. return;
  10385. }
  10386. try {
  10387. resolver(function (value) {
  10388. _this._resolve(value);
  10389. }, function (reason) {
  10390. _this._reject(reason);
  10391. });
  10392. }
  10393. catch (e) {
  10394. this._reject(e);
  10395. }
  10396. }
  10397. Object.defineProperty(InternalPromise.prototype, "_result", {
  10398. get: function () {
  10399. return this._resultValue;
  10400. },
  10401. set: function (value) {
  10402. this._resultValue = value;
  10403. if (this._parent && this._parent._result === undefined) {
  10404. this._parent._result = value;
  10405. }
  10406. },
  10407. enumerable: true,
  10408. configurable: true
  10409. });
  10410. InternalPromise.prototype.catch = function (onRejected) {
  10411. return this.then(undefined, onRejected);
  10412. };
  10413. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10414. var _this = this;
  10415. var newPromise = new InternalPromise();
  10416. newPromise._onFulfilled = onFulfilled;
  10417. newPromise._onRejected = onRejected;
  10418. // Composition
  10419. this._children.push(newPromise);
  10420. newPromise._parent = this;
  10421. if (this._state !== PromiseStates.Pending) {
  10422. BABYLON.Tools.SetImmediate(function () {
  10423. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10424. var returnedValue = newPromise._resolve(_this._result);
  10425. if (returnedValue !== undefined && returnedValue !== null) {
  10426. if (returnedValue._state !== undefined) {
  10427. var returnedPromise = returnedValue;
  10428. newPromise._children.push(returnedPromise);
  10429. returnedPromise._parent = newPromise;
  10430. newPromise = returnedPromise;
  10431. }
  10432. else {
  10433. newPromise._result = returnedValue;
  10434. }
  10435. }
  10436. }
  10437. else {
  10438. newPromise._reject(_this._reason);
  10439. }
  10440. });
  10441. }
  10442. return newPromise;
  10443. };
  10444. InternalPromise.prototype._moveChildren = function (children) {
  10445. var _this = this;
  10446. var _a;
  10447. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10448. this._children.forEach(function (child) {
  10449. child._parent = _this;
  10450. });
  10451. if (this._state === PromiseStates.Fulfilled) {
  10452. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10453. var child = _b[_i];
  10454. child._resolve(this._result);
  10455. }
  10456. }
  10457. else if (this._state === PromiseStates.Rejected) {
  10458. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10459. var child = _d[_c];
  10460. child._reject(this._reason);
  10461. }
  10462. }
  10463. };
  10464. InternalPromise.prototype._resolve = function (value) {
  10465. try {
  10466. this._state = PromiseStates.Fulfilled;
  10467. var returnedValue = null;
  10468. if (this._onFulfilled) {
  10469. returnedValue = this._onFulfilled(value);
  10470. }
  10471. if (returnedValue !== undefined && returnedValue !== null) {
  10472. if (returnedValue._state !== undefined) {
  10473. // Transmit children
  10474. var returnedPromise = returnedValue;
  10475. returnedPromise._parent = this;
  10476. returnedPromise._moveChildren(this._children);
  10477. value = returnedPromise._result;
  10478. }
  10479. else {
  10480. value = returnedValue;
  10481. }
  10482. }
  10483. this._result = value;
  10484. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10485. var child = _a[_i];
  10486. child._resolve(value);
  10487. }
  10488. this._children.length = 0;
  10489. delete this._onFulfilled;
  10490. delete this._onRejected;
  10491. }
  10492. catch (e) {
  10493. this._reject(e, true);
  10494. }
  10495. };
  10496. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10497. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10498. this._state = PromiseStates.Rejected;
  10499. this._reason = reason;
  10500. if (this._onRejected && !onLocalThrow) {
  10501. try {
  10502. this._onRejected(reason);
  10503. this._rejectWasConsumed = true;
  10504. }
  10505. catch (e) {
  10506. reason = e;
  10507. }
  10508. }
  10509. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10510. var child = _a[_i];
  10511. if (this._rejectWasConsumed) {
  10512. child._resolve(null);
  10513. }
  10514. else {
  10515. child._reject(reason);
  10516. }
  10517. }
  10518. this._children.length = 0;
  10519. delete this._onFulfilled;
  10520. delete this._onRejected;
  10521. };
  10522. InternalPromise.resolve = function (value) {
  10523. var newPromise = new InternalPromise();
  10524. newPromise._resolve(value);
  10525. return newPromise;
  10526. };
  10527. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10528. promise.then(function (value) {
  10529. agregator.results[index] = value;
  10530. agregator.count++;
  10531. if (agregator.count === agregator.target) {
  10532. agregator.rootPromise._resolve(agregator.results);
  10533. }
  10534. return null;
  10535. }, function (reason) {
  10536. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10537. agregator.rootPromise._reject(reason);
  10538. }
  10539. });
  10540. };
  10541. InternalPromise.all = function (promises) {
  10542. var newPromise = new InternalPromise();
  10543. var agregator = new FulFillmentAgregator();
  10544. agregator.target = promises.length;
  10545. agregator.rootPromise = newPromise;
  10546. if (promises.length) {
  10547. for (var index = 0; index < promises.length; index++) {
  10548. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10549. }
  10550. }
  10551. else {
  10552. newPromise._resolve([]);
  10553. }
  10554. return newPromise;
  10555. };
  10556. InternalPromise.race = function (promises) {
  10557. var newPromise = new InternalPromise();
  10558. if (promises.length) {
  10559. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10560. var promise = promises_1[_i];
  10561. promise.then(function (value) {
  10562. if (newPromise) {
  10563. newPromise._resolve(value);
  10564. newPromise = null;
  10565. }
  10566. return null;
  10567. }, function (reason) {
  10568. if (newPromise) {
  10569. newPromise._reject(reason);
  10570. newPromise = null;
  10571. }
  10572. });
  10573. }
  10574. }
  10575. return newPromise;
  10576. };
  10577. return InternalPromise;
  10578. }());
  10579. /**
  10580. * Helper class that provides a small promise polyfill
  10581. */
  10582. var PromisePolyfill = /** @class */ (function () {
  10583. function PromisePolyfill() {
  10584. }
  10585. /**
  10586. * Static function used to check if the polyfill is required
  10587. * If this is the case then the function will inject the polyfill to window.Promise
  10588. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10589. */
  10590. PromisePolyfill.Apply = function (force) {
  10591. if (force === void 0) { force = false; }
  10592. if (force || typeof Promise === 'undefined') {
  10593. var root = window;
  10594. root.Promise = InternalPromise;
  10595. }
  10596. };
  10597. return PromisePolyfill;
  10598. }());
  10599. BABYLON.PromisePolyfill = PromisePolyfill;
  10600. })(BABYLON || (BABYLON = {}));
  10601. //# sourceMappingURL=babylon.promise.js.map
  10602. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10603. var BABYLON;
  10604. (function (BABYLON) {
  10605. /**
  10606. * Helper class to push actions to a pool of workers.
  10607. */
  10608. var WorkerPool = /** @class */ (function () {
  10609. /**
  10610. * Constructor
  10611. * @param workers Array of workers to use for actions
  10612. */
  10613. function WorkerPool(workers) {
  10614. this._pendingActions = new Array();
  10615. this._workerInfos = workers.map(function (worker) { return ({
  10616. worker: worker,
  10617. active: false
  10618. }); });
  10619. }
  10620. /**
  10621. * Terminates all workers and clears any pending actions.
  10622. */
  10623. WorkerPool.prototype.dispose = function () {
  10624. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10625. var workerInfo = _a[_i];
  10626. workerInfo.worker.terminate();
  10627. }
  10628. delete this._workerInfos;
  10629. delete this._pendingActions;
  10630. };
  10631. /**
  10632. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10633. * pended until a worker has completed its action.
  10634. * @param action The action to perform. Call onComplete when the action is complete.
  10635. */
  10636. WorkerPool.prototype.push = function (action) {
  10637. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10638. var workerInfo = _a[_i];
  10639. if (!workerInfo.active) {
  10640. this._execute(workerInfo, action);
  10641. return;
  10642. }
  10643. }
  10644. this._pendingActions.push(action);
  10645. };
  10646. WorkerPool.prototype._execute = function (workerInfo, action) {
  10647. var _this = this;
  10648. workerInfo.active = true;
  10649. action(workerInfo.worker, function () {
  10650. workerInfo.active = false;
  10651. var nextAction = _this._pendingActions.shift();
  10652. if (nextAction) {
  10653. _this._execute(workerInfo, nextAction);
  10654. }
  10655. });
  10656. };
  10657. return WorkerPool;
  10658. }());
  10659. BABYLON.WorkerPool = WorkerPool;
  10660. })(BABYLON || (BABYLON = {}));
  10661. //# sourceMappingURL=babylon.workerPool.js.map
  10662. var BABYLON;
  10663. (function (BABYLON) {
  10664. /**
  10665. * @hidden
  10666. **/
  10667. var _AlphaState = /** @class */ (function () {
  10668. /**
  10669. * Initializes the state.
  10670. */
  10671. function _AlphaState() {
  10672. this._isAlphaBlendDirty = false;
  10673. this._isBlendFunctionParametersDirty = false;
  10674. this._isBlendEquationParametersDirty = false;
  10675. this._isBlendConstantsDirty = false;
  10676. this._alphaBlend = false;
  10677. this._blendFunctionParameters = new Array(4);
  10678. this._blendEquationParameters = new Array(2);
  10679. this._blendConstants = new Array(4);
  10680. this.reset();
  10681. }
  10682. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10683. get: function () {
  10684. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10685. },
  10686. enumerable: true,
  10687. configurable: true
  10688. });
  10689. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10690. get: function () {
  10691. return this._alphaBlend;
  10692. },
  10693. set: function (value) {
  10694. if (this._alphaBlend === value) {
  10695. return;
  10696. }
  10697. this._alphaBlend = value;
  10698. this._isAlphaBlendDirty = true;
  10699. },
  10700. enumerable: true,
  10701. configurable: true
  10702. });
  10703. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10704. if (this._blendConstants[0] === r &&
  10705. this._blendConstants[1] === g &&
  10706. this._blendConstants[2] === b &&
  10707. this._blendConstants[3] === a) {
  10708. return;
  10709. }
  10710. this._blendConstants[0] = r;
  10711. this._blendConstants[1] = g;
  10712. this._blendConstants[2] = b;
  10713. this._blendConstants[3] = a;
  10714. this._isBlendConstantsDirty = true;
  10715. };
  10716. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10717. if (this._blendFunctionParameters[0] === value0 &&
  10718. this._blendFunctionParameters[1] === value1 &&
  10719. this._blendFunctionParameters[2] === value2 &&
  10720. this._blendFunctionParameters[3] === value3) {
  10721. return;
  10722. }
  10723. this._blendFunctionParameters[0] = value0;
  10724. this._blendFunctionParameters[1] = value1;
  10725. this._blendFunctionParameters[2] = value2;
  10726. this._blendFunctionParameters[3] = value3;
  10727. this._isBlendFunctionParametersDirty = true;
  10728. };
  10729. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10730. if (this._blendEquationParameters[0] === rgb &&
  10731. this._blendEquationParameters[1] === alpha) {
  10732. return;
  10733. }
  10734. this._blendEquationParameters[0] = rgb;
  10735. this._blendEquationParameters[1] = alpha;
  10736. this._isBlendEquationParametersDirty = true;
  10737. };
  10738. _AlphaState.prototype.reset = function () {
  10739. this._alphaBlend = false;
  10740. this._blendFunctionParameters[0] = null;
  10741. this._blendFunctionParameters[1] = null;
  10742. this._blendFunctionParameters[2] = null;
  10743. this._blendFunctionParameters[3] = null;
  10744. this._blendEquationParameters[0] = null;
  10745. this._blendEquationParameters[1] = null;
  10746. this._blendConstants[0] = null;
  10747. this._blendConstants[1] = null;
  10748. this._blendConstants[2] = null;
  10749. this._blendConstants[3] = null;
  10750. this._isAlphaBlendDirty = true;
  10751. this._isBlendFunctionParametersDirty = false;
  10752. this._isBlendEquationParametersDirty = false;
  10753. this._isBlendConstantsDirty = false;
  10754. };
  10755. _AlphaState.prototype.apply = function (gl) {
  10756. if (!this.isDirty) {
  10757. return;
  10758. }
  10759. // Alpha blend
  10760. if (this._isAlphaBlendDirty) {
  10761. if (this._alphaBlend) {
  10762. gl.enable(gl.BLEND);
  10763. }
  10764. else {
  10765. gl.disable(gl.BLEND);
  10766. }
  10767. this._isAlphaBlendDirty = false;
  10768. }
  10769. // Alpha function
  10770. if (this._isBlendFunctionParametersDirty) {
  10771. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10772. this._isBlendFunctionParametersDirty = false;
  10773. }
  10774. // Alpha equation
  10775. if (this._isBlendEquationParametersDirty) {
  10776. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10777. this._isBlendEquationParametersDirty = false;
  10778. }
  10779. // Constants
  10780. if (this._isBlendConstantsDirty) {
  10781. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10782. this._isBlendConstantsDirty = false;
  10783. }
  10784. };
  10785. return _AlphaState;
  10786. }());
  10787. BABYLON._AlphaState = _AlphaState;
  10788. })(BABYLON || (BABYLON = {}));
  10789. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10790. var BABYLON;
  10791. (function (BABYLON) {
  10792. /**
  10793. * @hidden
  10794. **/
  10795. var _DepthCullingState = /** @class */ (function () {
  10796. /**
  10797. * Initializes the state.
  10798. */
  10799. function _DepthCullingState() {
  10800. this._isDepthTestDirty = false;
  10801. this._isDepthMaskDirty = false;
  10802. this._isDepthFuncDirty = false;
  10803. this._isCullFaceDirty = false;
  10804. this._isCullDirty = false;
  10805. this._isZOffsetDirty = false;
  10806. this._isFrontFaceDirty = false;
  10807. this.reset();
  10808. }
  10809. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10810. get: function () {
  10811. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10812. },
  10813. enumerable: true,
  10814. configurable: true
  10815. });
  10816. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10817. get: function () {
  10818. return this._zOffset;
  10819. },
  10820. set: function (value) {
  10821. if (this._zOffset === value) {
  10822. return;
  10823. }
  10824. this._zOffset = value;
  10825. this._isZOffsetDirty = true;
  10826. },
  10827. enumerable: true,
  10828. configurable: true
  10829. });
  10830. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10831. get: function () {
  10832. return this._cullFace;
  10833. },
  10834. set: function (value) {
  10835. if (this._cullFace === value) {
  10836. return;
  10837. }
  10838. this._cullFace = value;
  10839. this._isCullFaceDirty = true;
  10840. },
  10841. enumerable: true,
  10842. configurable: true
  10843. });
  10844. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10845. get: function () {
  10846. return this._cull;
  10847. },
  10848. set: function (value) {
  10849. if (this._cull === value) {
  10850. return;
  10851. }
  10852. this._cull = value;
  10853. this._isCullDirty = true;
  10854. },
  10855. enumerable: true,
  10856. configurable: true
  10857. });
  10858. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10859. get: function () {
  10860. return this._depthFunc;
  10861. },
  10862. set: function (value) {
  10863. if (this._depthFunc === value) {
  10864. return;
  10865. }
  10866. this._depthFunc = value;
  10867. this._isDepthFuncDirty = true;
  10868. },
  10869. enumerable: true,
  10870. configurable: true
  10871. });
  10872. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10873. get: function () {
  10874. return this._depthMask;
  10875. },
  10876. set: function (value) {
  10877. if (this._depthMask === value) {
  10878. return;
  10879. }
  10880. this._depthMask = value;
  10881. this._isDepthMaskDirty = true;
  10882. },
  10883. enumerable: true,
  10884. configurable: true
  10885. });
  10886. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10887. get: function () {
  10888. return this._depthTest;
  10889. },
  10890. set: function (value) {
  10891. if (this._depthTest === value) {
  10892. return;
  10893. }
  10894. this._depthTest = value;
  10895. this._isDepthTestDirty = true;
  10896. },
  10897. enumerable: true,
  10898. configurable: true
  10899. });
  10900. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10901. get: function () {
  10902. return this._frontFace;
  10903. },
  10904. set: function (value) {
  10905. if (this._frontFace === value) {
  10906. return;
  10907. }
  10908. this._frontFace = value;
  10909. this._isFrontFaceDirty = true;
  10910. },
  10911. enumerable: true,
  10912. configurable: true
  10913. });
  10914. _DepthCullingState.prototype.reset = function () {
  10915. this._depthMask = true;
  10916. this._depthTest = true;
  10917. this._depthFunc = null;
  10918. this._cullFace = null;
  10919. this._cull = null;
  10920. this._zOffset = 0;
  10921. this._frontFace = null;
  10922. this._isDepthTestDirty = true;
  10923. this._isDepthMaskDirty = true;
  10924. this._isDepthFuncDirty = false;
  10925. this._isCullFaceDirty = false;
  10926. this._isCullDirty = false;
  10927. this._isZOffsetDirty = false;
  10928. this._isFrontFaceDirty = false;
  10929. };
  10930. _DepthCullingState.prototype.apply = function (gl) {
  10931. if (!this.isDirty) {
  10932. return;
  10933. }
  10934. // Cull
  10935. if (this._isCullDirty) {
  10936. if (this.cull) {
  10937. gl.enable(gl.CULL_FACE);
  10938. }
  10939. else {
  10940. gl.disable(gl.CULL_FACE);
  10941. }
  10942. this._isCullDirty = false;
  10943. }
  10944. // Cull face
  10945. if (this._isCullFaceDirty) {
  10946. gl.cullFace(this.cullFace);
  10947. this._isCullFaceDirty = false;
  10948. }
  10949. // Depth mask
  10950. if (this._isDepthMaskDirty) {
  10951. gl.depthMask(this.depthMask);
  10952. this._isDepthMaskDirty = false;
  10953. }
  10954. // Depth test
  10955. if (this._isDepthTestDirty) {
  10956. if (this.depthTest) {
  10957. gl.enable(gl.DEPTH_TEST);
  10958. }
  10959. else {
  10960. gl.disable(gl.DEPTH_TEST);
  10961. }
  10962. this._isDepthTestDirty = false;
  10963. }
  10964. // Depth func
  10965. if (this._isDepthFuncDirty) {
  10966. gl.depthFunc(this.depthFunc);
  10967. this._isDepthFuncDirty = false;
  10968. }
  10969. // zOffset
  10970. if (this._isZOffsetDirty) {
  10971. if (this.zOffset) {
  10972. gl.enable(gl.POLYGON_OFFSET_FILL);
  10973. gl.polygonOffset(this.zOffset, 0);
  10974. }
  10975. else {
  10976. gl.disable(gl.POLYGON_OFFSET_FILL);
  10977. }
  10978. this._isZOffsetDirty = false;
  10979. }
  10980. // Front face
  10981. if (this._isFrontFaceDirty) {
  10982. gl.frontFace(this.frontFace);
  10983. this._isFrontFaceDirty = false;
  10984. }
  10985. };
  10986. return _DepthCullingState;
  10987. }());
  10988. BABYLON._DepthCullingState = _DepthCullingState;
  10989. })(BABYLON || (BABYLON = {}));
  10990. //# sourceMappingURL=babylon.depthCullingState.js.map
  10991. var BABYLON;
  10992. (function (BABYLON) {
  10993. /**
  10994. * @hidden
  10995. **/
  10996. var _StencilState = /** @class */ (function () {
  10997. function _StencilState() {
  10998. this._isStencilTestDirty = false;
  10999. this._isStencilMaskDirty = false;
  11000. this._isStencilFuncDirty = false;
  11001. this._isStencilOpDirty = false;
  11002. this.reset();
  11003. }
  11004. Object.defineProperty(_StencilState.prototype, "isDirty", {
  11005. get: function () {
  11006. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  11007. },
  11008. enumerable: true,
  11009. configurable: true
  11010. });
  11011. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  11012. get: function () {
  11013. return this._stencilFunc;
  11014. },
  11015. set: function (value) {
  11016. if (this._stencilFunc === value) {
  11017. return;
  11018. }
  11019. this._stencilFunc = value;
  11020. this._isStencilFuncDirty = true;
  11021. },
  11022. enumerable: true,
  11023. configurable: true
  11024. });
  11025. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  11026. get: function () {
  11027. return this._stencilFuncRef;
  11028. },
  11029. set: function (value) {
  11030. if (this._stencilFuncRef === value) {
  11031. return;
  11032. }
  11033. this._stencilFuncRef = value;
  11034. this._isStencilFuncDirty = true;
  11035. },
  11036. enumerable: true,
  11037. configurable: true
  11038. });
  11039. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  11040. get: function () {
  11041. return this._stencilFuncMask;
  11042. },
  11043. set: function (value) {
  11044. if (this._stencilFuncMask === value) {
  11045. return;
  11046. }
  11047. this._stencilFuncMask = value;
  11048. this._isStencilFuncDirty = true;
  11049. },
  11050. enumerable: true,
  11051. configurable: true
  11052. });
  11053. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  11054. get: function () {
  11055. return this._stencilOpStencilFail;
  11056. },
  11057. set: function (value) {
  11058. if (this._stencilOpStencilFail === value) {
  11059. return;
  11060. }
  11061. this._stencilOpStencilFail = value;
  11062. this._isStencilOpDirty = true;
  11063. },
  11064. enumerable: true,
  11065. configurable: true
  11066. });
  11067. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11068. get: function () {
  11069. return this._stencilOpDepthFail;
  11070. },
  11071. set: function (value) {
  11072. if (this._stencilOpDepthFail === value) {
  11073. return;
  11074. }
  11075. this._stencilOpDepthFail = value;
  11076. this._isStencilOpDirty = true;
  11077. },
  11078. enumerable: true,
  11079. configurable: true
  11080. });
  11081. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11082. get: function () {
  11083. return this._stencilOpStencilDepthPass;
  11084. },
  11085. set: function (value) {
  11086. if (this._stencilOpStencilDepthPass === value) {
  11087. return;
  11088. }
  11089. this._stencilOpStencilDepthPass = value;
  11090. this._isStencilOpDirty = true;
  11091. },
  11092. enumerable: true,
  11093. configurable: true
  11094. });
  11095. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11096. get: function () {
  11097. return this._stencilMask;
  11098. },
  11099. set: function (value) {
  11100. if (this._stencilMask === value) {
  11101. return;
  11102. }
  11103. this._stencilMask = value;
  11104. this._isStencilMaskDirty = true;
  11105. },
  11106. enumerable: true,
  11107. configurable: true
  11108. });
  11109. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11110. get: function () {
  11111. return this._stencilTest;
  11112. },
  11113. set: function (value) {
  11114. if (this._stencilTest === value) {
  11115. return;
  11116. }
  11117. this._stencilTest = value;
  11118. this._isStencilTestDirty = true;
  11119. },
  11120. enumerable: true,
  11121. configurable: true
  11122. });
  11123. _StencilState.prototype.reset = function () {
  11124. this._stencilTest = false;
  11125. this._stencilMask = 0xFF;
  11126. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11127. this._stencilFuncRef = 1;
  11128. this._stencilFuncMask = 0xFF;
  11129. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11130. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11131. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11132. this._isStencilTestDirty = true;
  11133. this._isStencilMaskDirty = true;
  11134. this._isStencilFuncDirty = true;
  11135. this._isStencilOpDirty = true;
  11136. };
  11137. _StencilState.prototype.apply = function (gl) {
  11138. if (!this.isDirty) {
  11139. return;
  11140. }
  11141. // Stencil test
  11142. if (this._isStencilTestDirty) {
  11143. if (this.stencilTest) {
  11144. gl.enable(gl.STENCIL_TEST);
  11145. }
  11146. else {
  11147. gl.disable(gl.STENCIL_TEST);
  11148. }
  11149. this._isStencilTestDirty = false;
  11150. }
  11151. // Stencil mask
  11152. if (this._isStencilMaskDirty) {
  11153. gl.stencilMask(this.stencilMask);
  11154. this._isStencilMaskDirty = false;
  11155. }
  11156. // Stencil func
  11157. if (this._isStencilFuncDirty) {
  11158. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11159. this._isStencilFuncDirty = false;
  11160. }
  11161. // Stencil op
  11162. if (this._isStencilOpDirty) {
  11163. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11164. this._isStencilOpDirty = false;
  11165. }
  11166. };
  11167. return _StencilState;
  11168. }());
  11169. BABYLON._StencilState = _StencilState;
  11170. })(BABYLON || (BABYLON = {}));
  11171. //# sourceMappingURL=babylon.stencilState.js.map
  11172. var __assign = (this && this.__assign) || function () {
  11173. __assign = Object.assign || function(t) {
  11174. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11175. s = arguments[i];
  11176. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11177. t[p] = s[p];
  11178. }
  11179. return t;
  11180. };
  11181. return __assign.apply(this, arguments);
  11182. };
  11183. var BABYLON;
  11184. (function (BABYLON) {
  11185. /**
  11186. * Keeps track of all the buffer info used in engine.
  11187. */
  11188. var BufferPointer = /** @class */ (function () {
  11189. function BufferPointer() {
  11190. }
  11191. return BufferPointer;
  11192. }());
  11193. /**
  11194. * Interface for attribute information associated with buffer instanciation
  11195. */
  11196. var InstancingAttributeInfo = /** @class */ (function () {
  11197. function InstancingAttributeInfo() {
  11198. }
  11199. return InstancingAttributeInfo;
  11200. }());
  11201. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11202. /**
  11203. * Define options used to create a render target texture
  11204. */
  11205. var RenderTargetCreationOptions = /** @class */ (function () {
  11206. function RenderTargetCreationOptions() {
  11207. }
  11208. return RenderTargetCreationOptions;
  11209. }());
  11210. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11211. /**
  11212. * Define options used to create a depth texture
  11213. */
  11214. var DepthTextureCreationOptions = /** @class */ (function () {
  11215. function DepthTextureCreationOptions() {
  11216. }
  11217. return DepthTextureCreationOptions;
  11218. }());
  11219. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11220. /**
  11221. * Class used to describe the capabilities of the engine relatively to the current browser
  11222. */
  11223. var EngineCapabilities = /** @class */ (function () {
  11224. function EngineCapabilities() {
  11225. }
  11226. return EngineCapabilities;
  11227. }());
  11228. BABYLON.EngineCapabilities = EngineCapabilities;
  11229. /**
  11230. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11231. */
  11232. var Engine = /** @class */ (function () {
  11233. /**
  11234. * Creates a new engine
  11235. * @param canvasOrContext defines the canvas or WebGL context to use for rendering. If you provide a WebGL context, Babylon.js will not hook events on the canvas (like pointers, keyboards, etc...) so no event observables will be available. This is mostly used when Babylon.js is used as a plugin on a system which alreay used the WebGL context
  11236. * @param antialias defines enable antialiasing (default: false)
  11237. * @param options defines further options to be sent to the getContext() function
  11238. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11239. */
  11240. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11241. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11242. var _this = this;
  11243. // Public members
  11244. /**
  11245. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11246. */
  11247. this.forcePOTTextures = false;
  11248. /**
  11249. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11250. */
  11251. this.isFullscreen = false;
  11252. /**
  11253. * Gets a boolean indicating if the pointer is currently locked
  11254. */
  11255. this.isPointerLock = false;
  11256. /**
  11257. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11258. */
  11259. this.cullBackFaces = true;
  11260. /**
  11261. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11262. */
  11263. this.renderEvenInBackground = true;
  11264. /**
  11265. * Gets or sets a boolean indicating that cache can be kept between frames
  11266. */
  11267. this.preventCacheWipeBetweenFrames = false;
  11268. /**
  11269. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11270. **/
  11271. this.enableOfflineSupport = false;
  11272. /**
  11273. * 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)
  11274. **/
  11275. this.disableManifestCheck = false;
  11276. /**
  11277. * Gets the list of created scenes
  11278. */
  11279. this.scenes = new Array();
  11280. /**
  11281. * Gets the list of created postprocesses
  11282. */
  11283. this.postProcesses = new Array();
  11284. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  11285. this.validateShaderPrograms = false;
  11286. // Observables
  11287. /**
  11288. * Observable event triggered each time the rendering canvas is resized
  11289. */
  11290. this.onResizeObservable = new BABYLON.Observable();
  11291. /**
  11292. * Observable event triggered each time the canvas loses focus
  11293. */
  11294. this.onCanvasBlurObservable = new BABYLON.Observable();
  11295. /**
  11296. * Observable event triggered each time the canvas gains focus
  11297. */
  11298. this.onCanvasFocusObservable = new BABYLON.Observable();
  11299. /**
  11300. * Observable event triggered each time the canvas receives pointerout event
  11301. */
  11302. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11303. /**
  11304. * Observable event triggered before each texture is initialized
  11305. */
  11306. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11307. //WebVR
  11308. this._vrDisplay = undefined;
  11309. this._vrSupported = false;
  11310. this._vrExclusivePointerMode = false;
  11311. // Uniform buffers list
  11312. /**
  11313. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11314. */
  11315. this.disableUniformBuffers = false;
  11316. /** @hidden */
  11317. this._uniformBuffers = new Array();
  11318. // Observables
  11319. /**
  11320. * Observable raised when the engine begins a new frame
  11321. */
  11322. this.onBeginFrameObservable = new BABYLON.Observable();
  11323. /**
  11324. * Observable raised when the engine ends the current frame
  11325. */
  11326. this.onEndFrameObservable = new BABYLON.Observable();
  11327. /**
  11328. * Observable raised when the engine is about to compile a shader
  11329. */
  11330. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11331. /**
  11332. * Observable raised when the engine has jsut compiled a shader
  11333. */
  11334. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11335. this._windowIsBackground = false;
  11336. this._webGLVersion = 1.0;
  11337. /** @hidden */
  11338. this._badOS = false;
  11339. /** @hidden */
  11340. this._badDesktopOS = false;
  11341. /**
  11342. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11343. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11344. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11345. */
  11346. this.disableTextureBindingOptimization = false;
  11347. /**
  11348. * Observable signaled when VR display mode changes
  11349. */
  11350. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11351. /**
  11352. * Observable signaled when VR request present is complete
  11353. */
  11354. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11355. /**
  11356. * Observable signaled when VR request present starts
  11357. */
  11358. this.onVRRequestPresentStart = new BABYLON.Observable();
  11359. this._colorWrite = true;
  11360. /** @hidden */
  11361. this._drawCalls = new BABYLON.PerfCounter();
  11362. /** @hidden */
  11363. this._textureCollisions = new BABYLON.PerfCounter();
  11364. this._renderingQueueLaunched = false;
  11365. this._activeRenderLoops = new Array();
  11366. // Deterministic lockstepMaxSteps
  11367. this._deterministicLockstep = false;
  11368. this._lockstepMaxSteps = 4;
  11369. // Lost context
  11370. /**
  11371. * Observable signaled when a context lost event is raised
  11372. */
  11373. this.onContextLostObservable = new BABYLON.Observable();
  11374. /**
  11375. * Observable signaled when a context restored event is raised
  11376. */
  11377. this.onContextRestoredObservable = new BABYLON.Observable();
  11378. this._contextWasLost = false;
  11379. this._doNotHandleContextLost = false;
  11380. // FPS
  11381. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11382. this._fps = 60;
  11383. this._deltaTime = 0;
  11384. /**
  11385. * Turn this value on if you want to pause FPS computation when in background
  11386. */
  11387. this.disablePerformanceMonitorInBackground = false;
  11388. // States
  11389. /** @hidden */
  11390. this._depthCullingState = new BABYLON._DepthCullingState();
  11391. /** @hidden */
  11392. this._stencilState = new BABYLON._StencilState();
  11393. /** @hidden */
  11394. this._alphaState = new BABYLON._AlphaState();
  11395. /** @hidden */
  11396. this._alphaMode = Engine.ALPHA_DISABLE;
  11397. // Cache
  11398. this._internalTexturesCache = new Array();
  11399. /** @hidden */
  11400. this._activeChannel = 0;
  11401. this._currentTextureChannel = -1;
  11402. /** @hidden */
  11403. this._boundTexturesCache = {};
  11404. this._compiledEffects = {};
  11405. this._vertexAttribArraysEnabled = [];
  11406. this._uintIndicesCurrentlySet = false;
  11407. this._currentBoundBuffer = new Array();
  11408. /** @hidden */
  11409. this._currentFramebuffer = null;
  11410. this._currentBufferPointers = new Array();
  11411. this._currentInstanceLocations = new Array();
  11412. this._currentInstanceBuffers = new Array();
  11413. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11414. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11415. this._vaoRecordInProgress = false;
  11416. this._mustWipeVertexAttributes = false;
  11417. this._nextFreeTextureSlots = new Array();
  11418. this._maxSimultaneousTextures = 0;
  11419. this._activeRequests = new Array();
  11420. // Hardware supported Compressed Textures
  11421. this._texturesSupported = new Array();
  11422. /**
  11423. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11424. */
  11425. this.premultipliedAlpha = true;
  11426. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11427. this._onVRFullScreenTriggered = function () {
  11428. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11429. //get the old size before we change
  11430. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11431. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11432. //get the width and height, change the render size
  11433. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11434. _this.setHardwareScalingLevel(1);
  11435. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11436. }
  11437. else {
  11438. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11439. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11440. }
  11441. };
  11442. this._unpackFlipYCached = null;
  11443. this._boundUniforms = {};
  11444. // Register promises
  11445. BABYLON.PromisePolyfill.Apply();
  11446. var canvas = null;
  11447. Engine.Instances.push(this);
  11448. if (!canvasOrContext) {
  11449. return;
  11450. }
  11451. options = options || {};
  11452. if (canvasOrContext.getContext) {
  11453. canvas = canvasOrContext;
  11454. this._renderingCanvas = canvas;
  11455. if (antialias != null) {
  11456. options.antialias = antialias;
  11457. }
  11458. if (options.deterministicLockstep === undefined) {
  11459. options.deterministicLockstep = false;
  11460. }
  11461. if (options.lockstepMaxSteps === undefined) {
  11462. options.lockstepMaxSteps = 4;
  11463. }
  11464. if (options.preserveDrawingBuffer === undefined) {
  11465. options.preserveDrawingBuffer = false;
  11466. }
  11467. if (options.audioEngine === undefined) {
  11468. options.audioEngine = true;
  11469. }
  11470. if (options.stencil === undefined) {
  11471. options.stencil = true;
  11472. }
  11473. if (options.premultipliedAlpha === false) {
  11474. this.premultipliedAlpha = false;
  11475. }
  11476. this._deterministicLockstep = options.deterministicLockstep;
  11477. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11478. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11479. // Exceptions
  11480. if (navigator && navigator.userAgent) {
  11481. var ua = navigator.userAgent;
  11482. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11483. var exception = _a[_i];
  11484. var key = exception.key;
  11485. var targets = exception.targets;
  11486. if (ua.indexOf(key) > -1) {
  11487. if (exception.capture && exception.captureConstraint) {
  11488. var capture = exception.capture;
  11489. var constraint = exception.captureConstraint;
  11490. var regex = new RegExp(capture);
  11491. var matches = regex.exec(ua);
  11492. if (matches && matches.length > 0) {
  11493. var capturedValue = parseInt(matches[matches.length - 1]);
  11494. if (capturedValue >= constraint) {
  11495. continue;
  11496. }
  11497. }
  11498. }
  11499. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11500. var target = targets_1[_b];
  11501. switch (target) {
  11502. case "uniformBuffer":
  11503. this.disableUniformBuffers = true;
  11504. break;
  11505. case "textureBindingOptimization":
  11506. this.disableTextureBindingOptimization = true;
  11507. break;
  11508. }
  11509. }
  11510. }
  11511. }
  11512. }
  11513. // GL
  11514. if (!options.disableWebGL2Support) {
  11515. try {
  11516. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11517. if (this._gl) {
  11518. this._webGLVersion = 2.0;
  11519. }
  11520. }
  11521. catch (e) {
  11522. // Do nothing
  11523. }
  11524. }
  11525. if (!this._gl) {
  11526. if (!canvas) {
  11527. throw new Error("The provided canvas is null or undefined.");
  11528. }
  11529. try {
  11530. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11531. }
  11532. catch (e) {
  11533. throw new Error("WebGL not supported");
  11534. }
  11535. }
  11536. if (!this._gl) {
  11537. throw new Error("WebGL not supported");
  11538. }
  11539. this._onCanvasFocus = function () {
  11540. _this.onCanvasFocusObservable.notifyObservers(_this);
  11541. };
  11542. this._onCanvasBlur = function () {
  11543. _this.onCanvasBlurObservable.notifyObservers(_this);
  11544. };
  11545. canvas.addEventListener("focus", this._onCanvasFocus);
  11546. canvas.addEventListener("blur", this._onCanvasBlur);
  11547. this._onBlur = function () {
  11548. if (_this.disablePerformanceMonitorInBackground) {
  11549. _this._performanceMonitor.disable();
  11550. }
  11551. _this._windowIsBackground = true;
  11552. };
  11553. this._onFocus = function () {
  11554. if (_this.disablePerformanceMonitorInBackground) {
  11555. _this._performanceMonitor.enable();
  11556. }
  11557. _this._windowIsBackground = false;
  11558. };
  11559. this._onCanvasPointerOut = function (ev) {
  11560. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11561. };
  11562. window.addEventListener("blur", this._onBlur);
  11563. window.addEventListener("focus", this._onFocus);
  11564. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11565. // Context lost
  11566. if (!this._doNotHandleContextLost) {
  11567. this._onContextLost = function (evt) {
  11568. evt.preventDefault();
  11569. _this._contextWasLost = true;
  11570. BABYLON.Tools.Warn("WebGL context lost.");
  11571. _this.onContextLostObservable.notifyObservers(_this);
  11572. };
  11573. this._onContextRestored = function (evt) {
  11574. // Adding a timeout to avoid race condition at browser level
  11575. setTimeout(function () {
  11576. // Rebuild gl context
  11577. _this._initGLContext();
  11578. // Rebuild effects
  11579. _this._rebuildEffects();
  11580. // Rebuild textures
  11581. _this._rebuildInternalTextures();
  11582. // Rebuild buffers
  11583. _this._rebuildBuffers();
  11584. // Cache
  11585. _this.wipeCaches(true);
  11586. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11587. _this.onContextRestoredObservable.notifyObservers(_this);
  11588. _this._contextWasLost = false;
  11589. }, 0);
  11590. };
  11591. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11592. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11593. }
  11594. }
  11595. else {
  11596. this._gl = canvasOrContext;
  11597. this._renderingCanvas = this._gl.canvas;
  11598. if (this._gl.renderbufferStorageMultisample) {
  11599. this._webGLVersion = 2.0;
  11600. }
  11601. options.stencil = this._gl.getContextAttributes().stencil;
  11602. }
  11603. // Viewport
  11604. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11605. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11606. this.resize();
  11607. this._isStencilEnable = options.stencil ? true : false;
  11608. this._initGLContext();
  11609. if (canvas) {
  11610. // Fullscreen
  11611. this._onFullscreenChange = function () {
  11612. if (document.fullscreen !== undefined) {
  11613. _this.isFullscreen = document.fullscreen;
  11614. }
  11615. else if (document.mozFullScreen !== undefined) {
  11616. _this.isFullscreen = document.mozFullScreen;
  11617. }
  11618. else if (document.webkitIsFullScreen !== undefined) {
  11619. _this.isFullscreen = document.webkitIsFullScreen;
  11620. }
  11621. else if (document.msIsFullScreen !== undefined) {
  11622. _this.isFullscreen = document.msIsFullScreen;
  11623. }
  11624. // Pointer lock
  11625. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11626. canvas.requestPointerLock = canvas.requestPointerLock ||
  11627. canvas.msRequestPointerLock ||
  11628. canvas.mozRequestPointerLock ||
  11629. canvas.webkitRequestPointerLock;
  11630. if (canvas.requestPointerLock) {
  11631. canvas.requestPointerLock();
  11632. }
  11633. }
  11634. };
  11635. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11636. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11637. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11638. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11639. // Pointer lock
  11640. this._onPointerLockChange = function () {
  11641. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11642. document.webkitPointerLockElement === canvas ||
  11643. document.msPointerLockElement === canvas ||
  11644. document.pointerLockElement === canvas);
  11645. };
  11646. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11647. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11648. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11649. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11650. this._onVRDisplayPointerRestricted = function () {
  11651. if (canvas) {
  11652. canvas.requestPointerLock();
  11653. }
  11654. };
  11655. this._onVRDisplayPointerUnrestricted = function () {
  11656. document.exitPointerLock();
  11657. };
  11658. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11659. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11660. }
  11661. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11662. Engine.audioEngine = new BABYLON.AudioEngine();
  11663. }
  11664. // Prepare buffer pointers
  11665. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11666. this._currentBufferPointers[i] = new BufferPointer();
  11667. }
  11668. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11669. // Load WebVR Devices
  11670. if (options.autoEnableWebVR) {
  11671. this.initWebVR();
  11672. }
  11673. // Detect if we are running on a faulty buggy OS.
  11674. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11675. // Detect if we are running on a faulty buggy desktop OS.
  11676. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11677. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11678. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11679. }
  11680. Object.defineProperty(Engine, "LastCreatedEngine", {
  11681. /**
  11682. * Gets the latest created engine
  11683. */
  11684. get: function () {
  11685. if (Engine.Instances.length === 0) {
  11686. return null;
  11687. }
  11688. return Engine.Instances[Engine.Instances.length - 1];
  11689. },
  11690. enumerable: true,
  11691. configurable: true
  11692. });
  11693. Object.defineProperty(Engine, "LastCreatedScene", {
  11694. /**
  11695. * Gets the latest created scene
  11696. */
  11697. get: function () {
  11698. var lastCreatedEngine = Engine.LastCreatedEngine;
  11699. if (!lastCreatedEngine) {
  11700. return null;
  11701. }
  11702. if (lastCreatedEngine.scenes.length === 0) {
  11703. return null;
  11704. }
  11705. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11706. },
  11707. enumerable: true,
  11708. configurable: true
  11709. });
  11710. /**
  11711. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11712. * @param flag defines which part of the materials must be marked as dirty
  11713. * @param predicate defines a predicate used to filter which materials should be affected
  11714. */
  11715. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11716. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11717. var engine = Engine.Instances[engineIndex];
  11718. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11719. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11720. }
  11721. }
  11722. };
  11723. Object.defineProperty(Engine, "Version", {
  11724. /**
  11725. * Returns the current version of the framework
  11726. */
  11727. get: function () {
  11728. return "3.3.0-beta.4";
  11729. },
  11730. enumerable: true,
  11731. configurable: true
  11732. });
  11733. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11734. /**
  11735. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11736. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11737. */
  11738. get: function () {
  11739. return this._vrExclusivePointerMode;
  11740. },
  11741. enumerable: true,
  11742. configurable: true
  11743. });
  11744. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11745. /**
  11746. * Gets a boolean indicating that the engine supports uniform buffers
  11747. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11748. */
  11749. get: function () {
  11750. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11751. },
  11752. enumerable: true,
  11753. configurable: true
  11754. });
  11755. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11756. /**
  11757. * Gets a boolean indicating that only power of 2 textures are supported
  11758. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11759. */
  11760. get: function () {
  11761. return this._webGLVersion < 2 || this.forcePOTTextures;
  11762. },
  11763. enumerable: true,
  11764. configurable: true
  11765. });
  11766. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  11767. /**
  11768. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  11769. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  11770. */
  11771. get: function () {
  11772. return this._doNotHandleContextLost;
  11773. },
  11774. set: function (value) {
  11775. this._doNotHandleContextLost = value;
  11776. },
  11777. enumerable: true,
  11778. configurable: true
  11779. });
  11780. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11781. /**
  11782. * Gets the performance monitor attached to this engine
  11783. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11784. */
  11785. get: function () {
  11786. return this._performanceMonitor;
  11787. },
  11788. enumerable: true,
  11789. configurable: true
  11790. });
  11791. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11792. /**
  11793. * Gets the list of texture formats supported
  11794. */
  11795. get: function () {
  11796. return this._texturesSupported;
  11797. },
  11798. enumerable: true,
  11799. configurable: true
  11800. });
  11801. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11802. /**
  11803. * Gets the list of texture formats in use
  11804. */
  11805. get: function () {
  11806. return this._textureFormatInUse;
  11807. },
  11808. enumerable: true,
  11809. configurable: true
  11810. });
  11811. Object.defineProperty(Engine.prototype, "currentViewport", {
  11812. /**
  11813. * Gets the current viewport
  11814. */
  11815. get: function () {
  11816. return this._cachedViewport;
  11817. },
  11818. enumerable: true,
  11819. configurable: true
  11820. });
  11821. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11822. /**
  11823. * Gets the default empty texture
  11824. */
  11825. get: function () {
  11826. if (!this._emptyTexture) {
  11827. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11828. }
  11829. return this._emptyTexture;
  11830. },
  11831. enumerable: true,
  11832. configurable: true
  11833. });
  11834. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11835. /**
  11836. * Gets the default empty 3D texture
  11837. */
  11838. get: function () {
  11839. if (!this._emptyTexture3D) {
  11840. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11841. }
  11842. return this._emptyTexture3D;
  11843. },
  11844. enumerable: true,
  11845. configurable: true
  11846. });
  11847. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11848. /**
  11849. * Gets the default empty cube texture
  11850. */
  11851. get: function () {
  11852. if (!this._emptyCubeTexture) {
  11853. var faceData = new Uint8Array(4);
  11854. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11855. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11856. }
  11857. return this._emptyCubeTexture;
  11858. },
  11859. enumerable: true,
  11860. configurable: true
  11861. });
  11862. Engine.prototype._rebuildInternalTextures = function () {
  11863. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11864. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11865. var internalTexture = currentState_1[_i];
  11866. internalTexture._rebuild();
  11867. }
  11868. };
  11869. Engine.prototype._rebuildEffects = function () {
  11870. for (var key in this._compiledEffects) {
  11871. var effect = this._compiledEffects[key];
  11872. effect._prepareEffect();
  11873. }
  11874. BABYLON.Effect.ResetCache();
  11875. };
  11876. Engine.prototype._rebuildBuffers = function () {
  11877. // Index / Vertex
  11878. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11879. var scene = _a[_i];
  11880. scene.resetCachedMaterial();
  11881. scene._rebuildGeometries();
  11882. scene._rebuildTextures();
  11883. }
  11884. // Uniforms
  11885. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11886. var uniformBuffer = _c[_b];
  11887. uniformBuffer._rebuild();
  11888. }
  11889. };
  11890. Engine.prototype._initGLContext = function () {
  11891. // Caps
  11892. this._caps = new EngineCapabilities();
  11893. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11894. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11895. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11896. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11897. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11898. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11899. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11900. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11901. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11902. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11903. // Infos
  11904. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11905. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11906. if (rendererInfo != null) {
  11907. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11908. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11909. }
  11910. if (!this._glVendor) {
  11911. this._glVendor = "Unknown vendor";
  11912. }
  11913. if (!this._glRenderer) {
  11914. this._glRenderer = "Unknown renderer";
  11915. }
  11916. // Constants
  11917. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11918. if (this._gl.RGBA16F !== 0x881A) {
  11919. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11920. }
  11921. if (this._gl.RGBA32F !== 0x8814) {
  11922. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11923. }
  11924. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11925. this._gl.DEPTH24_STENCIL8 = 35056;
  11926. }
  11927. // Extensions
  11928. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11929. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11930. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11931. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11932. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11933. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11934. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11935. 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');
  11936. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11937. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11938. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11939. this._caps.highPrecisionShaderSupported = true;
  11940. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11941. if (this._caps.timerQuery) {
  11942. if (this._webGLVersion === 1) {
  11943. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11944. }
  11945. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11946. }
  11947. // Checks if some of the format renders first to allow the use of webgl inspector.
  11948. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11949. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11950. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11951. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11952. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11953. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11954. if (this._webGLVersion > 1) {
  11955. this._gl.HALF_FLOAT_OES = 0x140B;
  11956. }
  11957. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11958. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11959. // Draw buffers
  11960. if (this._webGLVersion > 1) {
  11961. this._caps.drawBuffersExtension = true;
  11962. }
  11963. else {
  11964. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11965. if (drawBuffersExtension !== null) {
  11966. this._caps.drawBuffersExtension = true;
  11967. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11968. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11969. for (var i = 0; i < 16; i++) {
  11970. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11971. }
  11972. }
  11973. else {
  11974. this._caps.drawBuffersExtension = false;
  11975. }
  11976. }
  11977. // Depth Texture
  11978. if (this._webGLVersion > 1) {
  11979. this._caps.depthTextureExtension = true;
  11980. }
  11981. else {
  11982. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11983. if (depthTextureExtension != null) {
  11984. this._caps.depthTextureExtension = true;
  11985. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11986. }
  11987. }
  11988. // Vertex array object
  11989. if (this._webGLVersion > 1) {
  11990. this._caps.vertexArrayObject = true;
  11991. }
  11992. else {
  11993. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11994. if (vertexArrayObjectExtension != null) {
  11995. this._caps.vertexArrayObject = true;
  11996. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11997. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11998. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11999. }
  12000. else {
  12001. this._caps.vertexArrayObject = false;
  12002. }
  12003. }
  12004. // Instances count
  12005. if (this._webGLVersion > 1) {
  12006. this._caps.instancedArrays = true;
  12007. }
  12008. else {
  12009. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12010. if (instanceExtension != null) {
  12011. this._caps.instancedArrays = true;
  12012. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12013. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12014. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12015. }
  12016. else {
  12017. this._caps.instancedArrays = false;
  12018. }
  12019. }
  12020. // Intelligently add supported compressed formats in order to check for.
  12021. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12022. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12023. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12024. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12025. if (this._caps.astc)
  12026. this.texturesSupported.push('-astc.ktx');
  12027. if (this._caps.s3tc)
  12028. this.texturesSupported.push('-dxt.ktx');
  12029. if (this._caps.pvrtc)
  12030. this.texturesSupported.push('-pvrtc.ktx');
  12031. if (this._caps.etc2)
  12032. this.texturesSupported.push('-etc2.ktx');
  12033. if (this._caps.etc1)
  12034. this.texturesSupported.push('-etc1.ktx');
  12035. if (this._gl.getShaderPrecisionFormat) {
  12036. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12037. if (highp) {
  12038. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12039. }
  12040. }
  12041. // Depth buffer
  12042. this.setDepthBuffer(true);
  12043. this.setDepthFunctionToLessOrEqual();
  12044. this.setDepthWrite(true);
  12045. // Texture maps
  12046. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12047. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12048. this._nextFreeTextureSlots.push(slot);
  12049. }
  12050. };
  12051. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12052. /**
  12053. * Gets version of the current webGL context
  12054. */
  12055. get: function () {
  12056. return this._webGLVersion;
  12057. },
  12058. enumerable: true,
  12059. configurable: true
  12060. });
  12061. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12062. /**
  12063. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12064. */
  12065. get: function () {
  12066. return this._isStencilEnable;
  12067. },
  12068. enumerable: true,
  12069. configurable: true
  12070. });
  12071. Engine.prototype._prepareWorkingCanvas = function () {
  12072. if (this._workingCanvas) {
  12073. return;
  12074. }
  12075. this._workingCanvas = document.createElement("canvas");
  12076. var context = this._workingCanvas.getContext("2d");
  12077. if (context) {
  12078. this._workingContext = context;
  12079. }
  12080. };
  12081. /**
  12082. * Reset the texture cache to empty state
  12083. */
  12084. Engine.prototype.resetTextureCache = function () {
  12085. for (var key in this._boundTexturesCache) {
  12086. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12087. continue;
  12088. }
  12089. var boundTexture = this._boundTexturesCache[key];
  12090. if (boundTexture) {
  12091. this._removeDesignatedSlot(boundTexture);
  12092. }
  12093. this._boundTexturesCache[key] = null;
  12094. }
  12095. if (!this.disableTextureBindingOptimization) {
  12096. this._nextFreeTextureSlots = [];
  12097. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12098. this._nextFreeTextureSlots.push(slot);
  12099. }
  12100. }
  12101. this._currentTextureChannel = -1;
  12102. };
  12103. /**
  12104. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12105. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12106. * @returns true if engine is in deterministic lock step mode
  12107. */
  12108. Engine.prototype.isDeterministicLockStep = function () {
  12109. return this._deterministicLockstep;
  12110. };
  12111. /**
  12112. * Gets the max steps when engine is running in deterministic lock step
  12113. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12114. * @returns the max steps
  12115. */
  12116. Engine.prototype.getLockstepMaxSteps = function () {
  12117. return this._lockstepMaxSteps;
  12118. };
  12119. /**
  12120. * Gets an object containing information about the current webGL context
  12121. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12122. */
  12123. Engine.prototype.getGlInfo = function () {
  12124. return {
  12125. vendor: this._glVendor,
  12126. renderer: this._glRenderer,
  12127. version: this._glVersion
  12128. };
  12129. };
  12130. /**
  12131. * Gets current aspect ratio
  12132. * @param camera defines the camera to use to get the aspect ratio
  12133. * @param useScreen defines if screen size must be used (or the current render target if any)
  12134. * @returns a number defining the aspect ratio
  12135. */
  12136. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12137. if (useScreen === void 0) { useScreen = false; }
  12138. var viewport = camera.viewport;
  12139. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12140. };
  12141. /**
  12142. * Gets current screen aspect ratio
  12143. * @returns a number defining the aspect ratio
  12144. */
  12145. Engine.prototype.getScreenAspectRatio = function () {
  12146. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12147. };
  12148. /**
  12149. * Gets the current render width
  12150. * @param useScreen defines if screen size must be used (or the current render target if any)
  12151. * @returns a number defining the current render width
  12152. */
  12153. Engine.prototype.getRenderWidth = function (useScreen) {
  12154. if (useScreen === void 0) { useScreen = false; }
  12155. if (!useScreen && this._currentRenderTarget) {
  12156. return this._currentRenderTarget.width;
  12157. }
  12158. return this._gl.drawingBufferWidth;
  12159. };
  12160. /**
  12161. * Gets the current render height
  12162. * @param useScreen defines if screen size must be used (or the current render target if any)
  12163. * @returns a number defining the current render height
  12164. */
  12165. Engine.prototype.getRenderHeight = function (useScreen) {
  12166. if (useScreen === void 0) { useScreen = false; }
  12167. if (!useScreen && this._currentRenderTarget) {
  12168. return this._currentRenderTarget.height;
  12169. }
  12170. return this._gl.drawingBufferHeight;
  12171. };
  12172. /**
  12173. * Gets the HTML canvas attached with the current webGL context
  12174. * @returns a HTML canvas
  12175. */
  12176. Engine.prototype.getRenderingCanvas = function () {
  12177. return this._renderingCanvas;
  12178. };
  12179. /**
  12180. * Gets the client rect of the HTML canvas attached with the current webGL context
  12181. * @returns a client rectanglee
  12182. */
  12183. Engine.prototype.getRenderingCanvasClientRect = function () {
  12184. if (!this._renderingCanvas) {
  12185. return null;
  12186. }
  12187. return this._renderingCanvas.getBoundingClientRect();
  12188. };
  12189. /**
  12190. * Defines the hardware scaling level.
  12191. * By default the hardware scaling level is computed from the window device ratio.
  12192. * 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.
  12193. * @param level defines the level to use
  12194. */
  12195. Engine.prototype.setHardwareScalingLevel = function (level) {
  12196. this._hardwareScalingLevel = level;
  12197. this.resize();
  12198. };
  12199. /**
  12200. * Gets the current hardware scaling level.
  12201. * By default the hardware scaling level is computed from the window device ratio.
  12202. * 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.
  12203. * @returns a number indicating the current hardware scaling level
  12204. */
  12205. Engine.prototype.getHardwareScalingLevel = function () {
  12206. return this._hardwareScalingLevel;
  12207. };
  12208. /**
  12209. * Gets the list of loaded textures
  12210. * @returns an array containing all loaded textures
  12211. */
  12212. Engine.prototype.getLoadedTexturesCache = function () {
  12213. return this._internalTexturesCache;
  12214. };
  12215. /**
  12216. * Gets the object containing all engine capabilities
  12217. * @returns the EngineCapabilities object
  12218. */
  12219. Engine.prototype.getCaps = function () {
  12220. return this._caps;
  12221. };
  12222. Object.defineProperty(Engine.prototype, "drawCalls", {
  12223. /** @hidden */
  12224. get: function () {
  12225. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12226. return 0;
  12227. },
  12228. enumerable: true,
  12229. configurable: true
  12230. });
  12231. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12232. /** @hidden */
  12233. get: function () {
  12234. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12235. return null;
  12236. },
  12237. enumerable: true,
  12238. configurable: true
  12239. });
  12240. /**
  12241. * Gets the current depth function
  12242. * @returns a number defining the depth function
  12243. */
  12244. Engine.prototype.getDepthFunction = function () {
  12245. return this._depthCullingState.depthFunc;
  12246. };
  12247. /**
  12248. * Sets the current depth function
  12249. * @param depthFunc defines the function to use
  12250. */
  12251. Engine.prototype.setDepthFunction = function (depthFunc) {
  12252. this._depthCullingState.depthFunc = depthFunc;
  12253. };
  12254. /**
  12255. * Sets the current depth function to GREATER
  12256. */
  12257. Engine.prototype.setDepthFunctionToGreater = function () {
  12258. this._depthCullingState.depthFunc = this._gl.GREATER;
  12259. };
  12260. /**
  12261. * Sets the current depth function to GEQUAL
  12262. */
  12263. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12264. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12265. };
  12266. /**
  12267. * Sets the current depth function to LESS
  12268. */
  12269. Engine.prototype.setDepthFunctionToLess = function () {
  12270. this._depthCullingState.depthFunc = this._gl.LESS;
  12271. };
  12272. /**
  12273. * Sets the current depth function to LEQUAL
  12274. */
  12275. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12276. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12277. };
  12278. /**
  12279. * Gets a boolean indicating if stencil buffer is enabled
  12280. * @returns the current stencil buffer state
  12281. */
  12282. Engine.prototype.getStencilBuffer = function () {
  12283. return this._stencilState.stencilTest;
  12284. };
  12285. /**
  12286. * Enable or disable the stencil buffer
  12287. * @param enable defines if the stencil buffer must be enabled or disabled
  12288. */
  12289. Engine.prototype.setStencilBuffer = function (enable) {
  12290. this._stencilState.stencilTest = enable;
  12291. };
  12292. /**
  12293. * Gets the current stencil mask
  12294. * @returns a number defining the new stencil mask to use
  12295. */
  12296. Engine.prototype.getStencilMask = function () {
  12297. return this._stencilState.stencilMask;
  12298. };
  12299. /**
  12300. * Sets the current stencil mask
  12301. * @param mask defines the new stencil mask to use
  12302. */
  12303. Engine.prototype.setStencilMask = function (mask) {
  12304. this._stencilState.stencilMask = mask;
  12305. };
  12306. /**
  12307. * Gets the current stencil function
  12308. * @returns a number defining the stencil function to use
  12309. */
  12310. Engine.prototype.getStencilFunction = function () {
  12311. return this._stencilState.stencilFunc;
  12312. };
  12313. /**
  12314. * Gets the current stencil reference value
  12315. * @returns a number defining the stencil reference value to use
  12316. */
  12317. Engine.prototype.getStencilFunctionReference = function () {
  12318. return this._stencilState.stencilFuncRef;
  12319. };
  12320. /**
  12321. * Gets the current stencil mask
  12322. * @returns a number defining the stencil mask to use
  12323. */
  12324. Engine.prototype.getStencilFunctionMask = function () {
  12325. return this._stencilState.stencilFuncMask;
  12326. };
  12327. /**
  12328. * Sets the current stencil function
  12329. * @param stencilFunc defines the new stencil function to use
  12330. */
  12331. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12332. this._stencilState.stencilFunc = stencilFunc;
  12333. };
  12334. /**
  12335. * Sets the current stencil reference
  12336. * @param reference defines the new stencil reference to use
  12337. */
  12338. Engine.prototype.setStencilFunctionReference = function (reference) {
  12339. this._stencilState.stencilFuncRef = reference;
  12340. };
  12341. /**
  12342. * Sets the current stencil mask
  12343. * @param mask defines the new stencil mask to use
  12344. */
  12345. Engine.prototype.setStencilFunctionMask = function (mask) {
  12346. this._stencilState.stencilFuncMask = mask;
  12347. };
  12348. /**
  12349. * Gets the current stencil operation when stencil fails
  12350. * @returns a number defining stencil operation to use when stencil fails
  12351. */
  12352. Engine.prototype.getStencilOperationFail = function () {
  12353. return this._stencilState.stencilOpStencilFail;
  12354. };
  12355. /**
  12356. * Gets the current stencil operation when depth fails
  12357. * @returns a number defining stencil operation to use when depth fails
  12358. */
  12359. Engine.prototype.getStencilOperationDepthFail = function () {
  12360. return this._stencilState.stencilOpDepthFail;
  12361. };
  12362. /**
  12363. * Gets the current stencil operation when stencil passes
  12364. * @returns a number defining stencil operation to use when stencil passes
  12365. */
  12366. Engine.prototype.getStencilOperationPass = function () {
  12367. return this._stencilState.stencilOpStencilDepthPass;
  12368. };
  12369. /**
  12370. * Sets the stencil operation to use when stencil fails
  12371. * @param operation defines the stencil operation to use when stencil fails
  12372. */
  12373. Engine.prototype.setStencilOperationFail = function (operation) {
  12374. this._stencilState.stencilOpStencilFail = operation;
  12375. };
  12376. /**
  12377. * Sets the stencil operation to use when depth fails
  12378. * @param operation defines the stencil operation to use when depth fails
  12379. */
  12380. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12381. this._stencilState.stencilOpDepthFail = operation;
  12382. };
  12383. /**
  12384. * Sets the stencil operation to use when stencil passes
  12385. * @param operation defines the stencil operation to use when stencil passes
  12386. */
  12387. Engine.prototype.setStencilOperationPass = function (operation) {
  12388. this._stencilState.stencilOpStencilDepthPass = operation;
  12389. };
  12390. /**
  12391. * Sets a boolean indicating if the dithering state is enabled or disabled
  12392. * @param value defines the dithering state
  12393. */
  12394. Engine.prototype.setDitheringState = function (value) {
  12395. if (value) {
  12396. this._gl.enable(this._gl.DITHER);
  12397. }
  12398. else {
  12399. this._gl.disable(this._gl.DITHER);
  12400. }
  12401. };
  12402. /**
  12403. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12404. * @param value defines the rasterizer state
  12405. */
  12406. Engine.prototype.setRasterizerState = function (value) {
  12407. if (value) {
  12408. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12409. }
  12410. else {
  12411. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12412. }
  12413. };
  12414. /**
  12415. * stop executing a render loop function and remove it from the execution array
  12416. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12417. */
  12418. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12419. if (!renderFunction) {
  12420. this._activeRenderLoops = [];
  12421. return;
  12422. }
  12423. var index = this._activeRenderLoops.indexOf(renderFunction);
  12424. if (index >= 0) {
  12425. this._activeRenderLoops.splice(index, 1);
  12426. }
  12427. };
  12428. /** @hidden */
  12429. Engine.prototype._renderLoop = function () {
  12430. if (!this._contextWasLost) {
  12431. var shouldRender = true;
  12432. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12433. shouldRender = false;
  12434. }
  12435. if (shouldRender) {
  12436. // Start new frame
  12437. this.beginFrame();
  12438. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12439. var renderFunction = this._activeRenderLoops[index];
  12440. renderFunction();
  12441. }
  12442. // Present
  12443. this.endFrame();
  12444. }
  12445. }
  12446. if (this._activeRenderLoops.length > 0) {
  12447. // Register new frame
  12448. var requester = null;
  12449. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12450. requester = this._vrDisplay;
  12451. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12452. }
  12453. else {
  12454. this._renderingQueueLaunched = false;
  12455. }
  12456. };
  12457. /**
  12458. * Register and execute a render loop. The engine can have more than one render function
  12459. * @param renderFunction defines the function to continuously execute
  12460. */
  12461. Engine.prototype.runRenderLoop = function (renderFunction) {
  12462. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12463. return;
  12464. }
  12465. this._activeRenderLoops.push(renderFunction);
  12466. if (!this._renderingQueueLaunched) {
  12467. this._renderingQueueLaunched = true;
  12468. this._bindedRenderFunction = this._renderLoop.bind(this);
  12469. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12470. }
  12471. };
  12472. /**
  12473. * Toggle full screen mode
  12474. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12475. * @param options defines an option object to be sent to the requestFullscreen function
  12476. */
  12477. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12478. if (this.isFullscreen) {
  12479. BABYLON.Tools.ExitFullscreen();
  12480. }
  12481. else {
  12482. this._pointerLockRequested = requestPointerLock;
  12483. if (this._renderingCanvas) {
  12484. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12485. }
  12486. }
  12487. };
  12488. /**
  12489. * Clear the current render buffer or the current render target (if any is set up)
  12490. * @param color defines the color to use
  12491. * @param backBuffer defines if the back buffer must be cleared
  12492. * @param depth defines if the depth buffer must be cleared
  12493. * @param stencil defines if the stencil buffer must be cleared
  12494. */
  12495. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12496. if (stencil === void 0) { stencil = false; }
  12497. this.applyStates();
  12498. var mode = 0;
  12499. if (backBuffer && color) {
  12500. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12501. mode |= this._gl.COLOR_BUFFER_BIT;
  12502. }
  12503. if (depth) {
  12504. this._gl.clearDepth(1.0);
  12505. mode |= this._gl.DEPTH_BUFFER_BIT;
  12506. }
  12507. if (stencil) {
  12508. this._gl.clearStencil(0);
  12509. mode |= this._gl.STENCIL_BUFFER_BIT;
  12510. }
  12511. this._gl.clear(mode);
  12512. };
  12513. /**
  12514. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12515. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12516. * @param y defines the y-coordinate of the corner of the clear rectangle
  12517. * @param width defines the width of the clear rectangle
  12518. * @param height defines the height of the clear rectangle
  12519. * @param clearColor defines the clear color
  12520. */
  12521. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12522. var gl = this._gl;
  12523. // Save state
  12524. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12525. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12526. // Change state
  12527. gl.enable(gl.SCISSOR_TEST);
  12528. gl.scissor(x, y, width, height);
  12529. // Clear
  12530. this.clear(clearColor, true, true, true);
  12531. // Restore state
  12532. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12533. if (curScissor === true) {
  12534. gl.enable(gl.SCISSOR_TEST);
  12535. }
  12536. else {
  12537. gl.disable(gl.SCISSOR_TEST);
  12538. }
  12539. };
  12540. /** @hidden */
  12541. Engine.prototype._viewport = function (x, y, width, height) {
  12542. if (x !== this._viewportCached.x ||
  12543. y !== this._viewportCached.y ||
  12544. width !== this._viewportCached.z ||
  12545. height !== this._viewportCached.w) {
  12546. this._viewportCached.x = x;
  12547. this._viewportCached.y = y;
  12548. this._viewportCached.z = width;
  12549. this._viewportCached.w = height;
  12550. this._gl.viewport(x, y, width, height);
  12551. }
  12552. };
  12553. /**
  12554. * Set the WebGL's viewport
  12555. * @param viewport defines the viewport element to be used
  12556. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12557. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12558. */
  12559. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12560. var width = requiredWidth || this.getRenderWidth();
  12561. var height = requiredHeight || this.getRenderHeight();
  12562. var x = viewport.x || 0;
  12563. var y = viewport.y || 0;
  12564. this._cachedViewport = viewport;
  12565. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12566. };
  12567. /**
  12568. * Directly set the WebGL Viewport
  12569. * @param x defines the x coordinate of the viewport (in screen space)
  12570. * @param y defines the y coordinate of the viewport (in screen space)
  12571. * @param width defines the width of the viewport (in screen space)
  12572. * @param height defines the height of the viewport (in screen space)
  12573. * @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
  12574. */
  12575. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12576. var currentViewport = this._cachedViewport;
  12577. this._cachedViewport = null;
  12578. this._viewport(x, y, width, height);
  12579. return currentViewport;
  12580. };
  12581. /**
  12582. * Begin a new frame
  12583. */
  12584. Engine.prototype.beginFrame = function () {
  12585. this.onBeginFrameObservable.notifyObservers(this);
  12586. this._measureFps();
  12587. };
  12588. /**
  12589. * Enf the current frame
  12590. */
  12591. Engine.prototype.endFrame = function () {
  12592. // Force a flush in case we are using a bad OS.
  12593. if (this._badOS) {
  12594. this.flushFramebuffer();
  12595. }
  12596. // Submit frame to the vr device, if enabled
  12597. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12598. // TODO: We should only submit the frame if we read frameData successfully.
  12599. this._vrDisplay.submitFrame();
  12600. }
  12601. this.onEndFrameObservable.notifyObservers(this);
  12602. };
  12603. /**
  12604. * Resize the view according to the canvas' size
  12605. */
  12606. Engine.prototype.resize = function () {
  12607. // We're not resizing the size of the canvas while in VR mode & presenting
  12608. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12609. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12610. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12611. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12612. }
  12613. };
  12614. /**
  12615. * Force a specific size of the canvas
  12616. * @param width defines the new canvas' width
  12617. * @param height defines the new canvas' height
  12618. */
  12619. Engine.prototype.setSize = function (width, height) {
  12620. if (!this._renderingCanvas) {
  12621. return;
  12622. }
  12623. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12624. return;
  12625. }
  12626. this._renderingCanvas.width = width;
  12627. this._renderingCanvas.height = height;
  12628. for (var index = 0; index < this.scenes.length; index++) {
  12629. var scene = this.scenes[index];
  12630. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12631. var cam = scene.cameras[camIndex];
  12632. cam._currentRenderId = 0;
  12633. }
  12634. }
  12635. if (this.onResizeObservable.hasObservers) {
  12636. this.onResizeObservable.notifyObservers(this);
  12637. }
  12638. };
  12639. // WebVR functions
  12640. /**
  12641. * Gets a boolean indicating if a webVR device was detected
  12642. * @returns true if a webVR device was detected
  12643. */
  12644. Engine.prototype.isVRDevicePresent = function () {
  12645. return !!this._vrDisplay;
  12646. };
  12647. /**
  12648. * Gets the current webVR device
  12649. * @returns the current webVR device (or null)
  12650. */
  12651. Engine.prototype.getVRDevice = function () {
  12652. return this._vrDisplay;
  12653. };
  12654. /**
  12655. * Initializes a webVR display and starts listening to display change events
  12656. * The onVRDisplayChangedObservable will be notified upon these changes
  12657. * @returns The onVRDisplayChangedObservable
  12658. */
  12659. Engine.prototype.initWebVR = function () {
  12660. this.initWebVRAsync();
  12661. return this.onVRDisplayChangedObservable;
  12662. };
  12663. /**
  12664. * Initializes a webVR display and starts listening to display change events
  12665. * The onVRDisplayChangedObservable will be notified upon these changes
  12666. * @returns A promise containing a VRDisplay and if vr is supported
  12667. */
  12668. Engine.prototype.initWebVRAsync = function () {
  12669. var _this = this;
  12670. var notifyObservers = function () {
  12671. var eventArgs = {
  12672. vrDisplay: _this._vrDisplay,
  12673. vrSupported: _this._vrSupported
  12674. };
  12675. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12676. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12677. };
  12678. if (!this._onVrDisplayConnect) {
  12679. this._onVrDisplayConnect = function (event) {
  12680. _this._vrDisplay = event.display;
  12681. notifyObservers();
  12682. };
  12683. this._onVrDisplayDisconnect = function () {
  12684. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12685. _this._vrDisplay = undefined;
  12686. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12687. notifyObservers();
  12688. };
  12689. this._onVrDisplayPresentChange = function () {
  12690. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12691. };
  12692. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12693. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12694. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12695. }
  12696. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12697. this._webVRInitPromise.then(notifyObservers);
  12698. return this._webVRInitPromise;
  12699. };
  12700. /**
  12701. * Call this function to switch to webVR mode
  12702. * Will do nothing if webVR is not supported or if there is no webVR device
  12703. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12704. */
  12705. Engine.prototype.enableVR = function () {
  12706. var _this = this;
  12707. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12708. var onResolved = function () {
  12709. _this.onVRRequestPresentComplete.notifyObservers(true);
  12710. _this._onVRFullScreenTriggered();
  12711. };
  12712. var onRejected = function () {
  12713. _this.onVRRequestPresentComplete.notifyObservers(false);
  12714. };
  12715. this.onVRRequestPresentStart.notifyObservers(this);
  12716. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12717. }
  12718. };
  12719. /**
  12720. * Call this function to leave webVR mode
  12721. * Will do nothing if webVR is not supported or if there is no webVR device
  12722. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12723. */
  12724. Engine.prototype.disableVR = function () {
  12725. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12726. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12727. }
  12728. };
  12729. Engine.prototype._getVRDisplaysAsync = function () {
  12730. var _this = this;
  12731. return new Promise(function (res, rej) {
  12732. if (navigator.getVRDisplays) {
  12733. navigator.getVRDisplays().then(function (devices) {
  12734. _this._vrSupported = true;
  12735. // note that devices may actually be an empty array. This is fine;
  12736. // we expect this._vrDisplay to be undefined in this case.
  12737. _this._vrDisplay = devices[0];
  12738. res({
  12739. vrDisplay: _this._vrDisplay,
  12740. vrSupported: _this._vrSupported
  12741. });
  12742. });
  12743. }
  12744. else {
  12745. _this._vrDisplay = undefined;
  12746. _this._vrSupported = false;
  12747. res({
  12748. vrDisplay: _this._vrDisplay,
  12749. vrSupported: _this._vrSupported
  12750. });
  12751. }
  12752. });
  12753. };
  12754. /**
  12755. * Binds the frame buffer to the specified texture.
  12756. * @param texture The texture to render to or null for the default canvas
  12757. * @param faceIndex The face of the texture to render to in case of cube texture
  12758. * @param requiredWidth The width of the target to render to
  12759. * @param requiredHeight The height of the target to render to
  12760. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12761. * @param depthStencilTexture The depth stencil texture to use to render
  12762. * @param lodLevel defines le lod level to bind to the frame buffer
  12763. */
  12764. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  12765. if (lodLevel === void 0) { lodLevel = 0; }
  12766. if (this._currentRenderTarget) {
  12767. this.unBindFramebuffer(this._currentRenderTarget);
  12768. }
  12769. this._currentRenderTarget = texture;
  12770. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12771. var gl = this._gl;
  12772. if (texture.isCube) {
  12773. if (faceIndex === undefined) {
  12774. faceIndex = 0;
  12775. }
  12776. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  12777. if (depthStencilTexture) {
  12778. if (depthStencilTexture._generateStencilBuffer) {
  12779. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12780. }
  12781. else {
  12782. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12783. }
  12784. }
  12785. }
  12786. if (this._cachedViewport && !forceFullscreenViewport) {
  12787. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12788. }
  12789. else {
  12790. if (!requiredWidth) {
  12791. requiredWidth = texture.width;
  12792. if (lodLevel) {
  12793. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  12794. }
  12795. }
  12796. if (!requiredHeight) {
  12797. requiredHeight = texture.height;
  12798. if (lodLevel) {
  12799. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  12800. }
  12801. }
  12802. this._viewport(0, 0, requiredWidth, requiredHeight);
  12803. }
  12804. this.wipeCaches();
  12805. };
  12806. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12807. if (this._currentFramebuffer !== framebuffer) {
  12808. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12809. this._currentFramebuffer = framebuffer;
  12810. }
  12811. };
  12812. /**
  12813. * Unbind the current render target texture from the webGL context
  12814. * @param texture defines the render target texture to unbind
  12815. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12816. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12817. */
  12818. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12819. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12820. this._currentRenderTarget = null;
  12821. // If MSAA, we need to bitblt back to main texture
  12822. var gl = this._gl;
  12823. if (texture._MSAAFramebuffer) {
  12824. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12825. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12826. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12827. }
  12828. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12829. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12830. gl.generateMipmap(gl.TEXTURE_2D);
  12831. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12832. }
  12833. if (onBeforeUnbind) {
  12834. if (texture._MSAAFramebuffer) {
  12835. // Bind the correct framebuffer
  12836. this.bindUnboundFramebuffer(texture._framebuffer);
  12837. }
  12838. onBeforeUnbind();
  12839. }
  12840. this.bindUnboundFramebuffer(null);
  12841. };
  12842. /**
  12843. * Unbind a list of render target textures from the webGL context
  12844. * This is used only when drawBuffer extension or webGL2 are active
  12845. * @param textures defines the render target textures to unbind
  12846. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12847. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12848. */
  12849. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12850. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12851. this._currentRenderTarget = null;
  12852. // If MSAA, we need to bitblt back to main texture
  12853. var gl = this._gl;
  12854. if (textures[0]._MSAAFramebuffer) {
  12855. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12856. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12857. var attachments = textures[0]._attachments;
  12858. if (!attachments) {
  12859. attachments = new Array(textures.length);
  12860. textures[0]._attachments = attachments;
  12861. }
  12862. for (var i = 0; i < textures.length; i++) {
  12863. var texture = textures[i];
  12864. for (var j = 0; j < attachments.length; j++) {
  12865. attachments[j] = gl.NONE;
  12866. }
  12867. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12868. gl.readBuffer(attachments[i]);
  12869. gl.drawBuffers(attachments);
  12870. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12871. }
  12872. for (var i = 0; i < attachments.length; i++) {
  12873. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12874. }
  12875. gl.drawBuffers(attachments);
  12876. }
  12877. for (var i = 0; i < textures.length; i++) {
  12878. var texture = textures[i];
  12879. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12880. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12881. gl.generateMipmap(gl.TEXTURE_2D);
  12882. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12883. }
  12884. }
  12885. if (onBeforeUnbind) {
  12886. if (textures[0]._MSAAFramebuffer) {
  12887. // Bind the correct framebuffer
  12888. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12889. }
  12890. onBeforeUnbind();
  12891. }
  12892. this.bindUnboundFramebuffer(null);
  12893. };
  12894. /**
  12895. * Force the mipmap generation for the given render target texture
  12896. * @param texture defines the render target texture to use
  12897. */
  12898. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12899. if (texture.generateMipMaps) {
  12900. var gl = this._gl;
  12901. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12902. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12903. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12904. }
  12905. };
  12906. /**
  12907. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  12908. */
  12909. Engine.prototype.flushFramebuffer = function () {
  12910. this._gl.flush();
  12911. };
  12912. /**
  12913. * Unbind the current render target and bind the default framebuffer
  12914. */
  12915. Engine.prototype.restoreDefaultFramebuffer = function () {
  12916. if (this._currentRenderTarget) {
  12917. this.unBindFramebuffer(this._currentRenderTarget);
  12918. }
  12919. else {
  12920. this.bindUnboundFramebuffer(null);
  12921. }
  12922. if (this._cachedViewport) {
  12923. this.setViewport(this._cachedViewport);
  12924. }
  12925. this.wipeCaches();
  12926. };
  12927. // UBOs
  12928. /**
  12929. * Create an uniform buffer
  12930. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12931. * @param elements defines the content of the uniform buffer
  12932. * @returns the webGL uniform buffer
  12933. */
  12934. Engine.prototype.createUniformBuffer = function (elements) {
  12935. var ubo = this._gl.createBuffer();
  12936. if (!ubo) {
  12937. throw new Error("Unable to create uniform buffer");
  12938. }
  12939. this.bindUniformBuffer(ubo);
  12940. if (elements instanceof Float32Array) {
  12941. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12942. }
  12943. else {
  12944. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12945. }
  12946. this.bindUniformBuffer(null);
  12947. ubo.references = 1;
  12948. return ubo;
  12949. };
  12950. /**
  12951. * Create a dynamic uniform buffer
  12952. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12953. * @param elements defines the content of the uniform buffer
  12954. * @returns the webGL uniform buffer
  12955. */
  12956. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12957. var ubo = this._gl.createBuffer();
  12958. if (!ubo) {
  12959. throw new Error("Unable to create dynamic uniform buffer");
  12960. }
  12961. this.bindUniformBuffer(ubo);
  12962. if (elements instanceof Float32Array) {
  12963. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12964. }
  12965. else {
  12966. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12967. }
  12968. this.bindUniformBuffer(null);
  12969. ubo.references = 1;
  12970. return ubo;
  12971. };
  12972. /**
  12973. * Update an existing uniform buffer
  12974. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12975. * @param uniformBuffer defines the target uniform buffer
  12976. * @param elements defines the content to update
  12977. * @param offset defines the offset in the uniform buffer where update should start
  12978. * @param count defines the size of the data to update
  12979. */
  12980. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12981. this.bindUniformBuffer(uniformBuffer);
  12982. if (offset === undefined) {
  12983. offset = 0;
  12984. }
  12985. if (count === undefined) {
  12986. if (elements instanceof Float32Array) {
  12987. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12988. }
  12989. else {
  12990. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12991. }
  12992. }
  12993. else {
  12994. if (elements instanceof Float32Array) {
  12995. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12996. }
  12997. else {
  12998. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12999. }
  13000. }
  13001. this.bindUniformBuffer(null);
  13002. };
  13003. // VBOs
  13004. Engine.prototype._resetVertexBufferBinding = function () {
  13005. this.bindArrayBuffer(null);
  13006. this._cachedVertexBuffers = null;
  13007. };
  13008. /**
  13009. * Creates a vertex buffer
  13010. * @param data the data for the vertex buffer
  13011. * @returns the new WebGL static buffer
  13012. */
  13013. Engine.prototype.createVertexBuffer = function (data) {
  13014. var vbo = this._gl.createBuffer();
  13015. if (!vbo) {
  13016. throw new Error("Unable to create vertex buffer");
  13017. }
  13018. this.bindArrayBuffer(vbo);
  13019. if (data instanceof Array) {
  13020. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13021. }
  13022. else {
  13023. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13024. }
  13025. this._resetVertexBufferBinding();
  13026. vbo.references = 1;
  13027. return vbo;
  13028. };
  13029. /**
  13030. * Creates a dynamic vertex buffer
  13031. * @param data the data for the dynamic vertex buffer
  13032. * @returns the new WebGL dynamic buffer
  13033. */
  13034. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13035. var vbo = this._gl.createBuffer();
  13036. if (!vbo) {
  13037. throw new Error("Unable to create dynamic vertex buffer");
  13038. }
  13039. this.bindArrayBuffer(vbo);
  13040. if (data instanceof Array) {
  13041. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13042. }
  13043. else {
  13044. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13045. }
  13046. this._resetVertexBufferBinding();
  13047. vbo.references = 1;
  13048. return vbo;
  13049. };
  13050. /**
  13051. * Update a dynamic index buffer
  13052. * @param indexBuffer defines the target index buffer
  13053. * @param indices defines the data to update
  13054. * @param offset defines the offset in the target index buffer where update should start
  13055. */
  13056. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13057. if (offset === void 0) { offset = 0; }
  13058. // Force cache update
  13059. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13060. this.bindIndexBuffer(indexBuffer);
  13061. var arrayBuffer;
  13062. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13063. arrayBuffer = indices;
  13064. }
  13065. else {
  13066. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13067. }
  13068. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13069. this._resetIndexBufferBinding();
  13070. };
  13071. /**
  13072. * Updates a dynamic vertex buffer.
  13073. * @param vertexBuffer the vertex buffer to update
  13074. * @param data the data used to update the vertex buffer
  13075. * @param byteOffset the byte offset of the data
  13076. * @param byteLength the byte length of the data
  13077. */
  13078. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13079. this.bindArrayBuffer(vertexBuffer);
  13080. if (byteOffset === undefined) {
  13081. byteOffset = 0;
  13082. }
  13083. if (byteLength === undefined) {
  13084. if (data instanceof Array) {
  13085. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13086. }
  13087. else {
  13088. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13089. }
  13090. }
  13091. else {
  13092. if (data instanceof Array) {
  13093. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13094. }
  13095. else {
  13096. if (data instanceof ArrayBuffer) {
  13097. data = new Uint8Array(data, byteOffset, byteLength);
  13098. }
  13099. else {
  13100. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13101. }
  13102. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13103. }
  13104. }
  13105. this._resetVertexBufferBinding();
  13106. };
  13107. Engine.prototype._resetIndexBufferBinding = function () {
  13108. this.bindIndexBuffer(null);
  13109. this._cachedIndexBuffer = null;
  13110. };
  13111. /**
  13112. * Creates a new index buffer
  13113. * @param indices defines the content of the index buffer
  13114. * @param updatable defines if the index buffer must be updatable
  13115. * @returns a new webGL buffer
  13116. */
  13117. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13118. var vbo = this._gl.createBuffer();
  13119. if (!vbo) {
  13120. throw new Error("Unable to create index buffer");
  13121. }
  13122. this.bindIndexBuffer(vbo);
  13123. // Check for 32 bits indices
  13124. var arrayBuffer;
  13125. var need32Bits = false;
  13126. if (indices instanceof Uint16Array) {
  13127. arrayBuffer = indices;
  13128. }
  13129. else {
  13130. //check 32 bit support
  13131. if (this._caps.uintIndices) {
  13132. if (indices instanceof Uint32Array) {
  13133. arrayBuffer = indices;
  13134. need32Bits = true;
  13135. }
  13136. else {
  13137. //number[] or Int32Array, check if 32 bit is necessary
  13138. for (var index = 0; index < indices.length; index++) {
  13139. if (indices[index] > 65535) {
  13140. need32Bits = true;
  13141. break;
  13142. }
  13143. }
  13144. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13145. }
  13146. }
  13147. else {
  13148. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13149. arrayBuffer = new Uint16Array(indices);
  13150. }
  13151. }
  13152. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13153. this._resetIndexBufferBinding();
  13154. vbo.references = 1;
  13155. vbo.is32Bits = need32Bits;
  13156. return vbo;
  13157. };
  13158. /**
  13159. * Bind a webGL buffer to the webGL context
  13160. * @param buffer defines the buffer to bind
  13161. */
  13162. Engine.prototype.bindArrayBuffer = function (buffer) {
  13163. if (!this._vaoRecordInProgress) {
  13164. this._unbindVertexArrayObject();
  13165. }
  13166. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13167. };
  13168. /**
  13169. * Bind an uniform buffer to the current webGL context
  13170. * @param buffer defines the buffer to bind
  13171. */
  13172. Engine.prototype.bindUniformBuffer = function (buffer) {
  13173. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13174. };
  13175. /**
  13176. * Bind a buffer to the current webGL context at a given location
  13177. * @param buffer defines the buffer to bind
  13178. * @param location defines the index where to bind the buffer
  13179. */
  13180. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13181. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13182. };
  13183. /**
  13184. * Bind a specific block at a given index in a specific shader program
  13185. * @param shaderProgram defines the shader program
  13186. * @param blockName defines the block name
  13187. * @param index defines the index where to bind the block
  13188. */
  13189. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13190. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13191. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13192. };
  13193. ;
  13194. Engine.prototype.bindIndexBuffer = function (buffer) {
  13195. if (!this._vaoRecordInProgress) {
  13196. this._unbindVertexArrayObject();
  13197. }
  13198. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13199. };
  13200. Engine.prototype.bindBuffer = function (buffer, target) {
  13201. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13202. this._gl.bindBuffer(target, buffer);
  13203. this._currentBoundBuffer[target] = buffer;
  13204. }
  13205. };
  13206. /**
  13207. * update the bound buffer with the given data
  13208. * @param data defines the data to update
  13209. */
  13210. Engine.prototype.updateArrayBuffer = function (data) {
  13211. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13212. };
  13213. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13214. var pointer = this._currentBufferPointers[indx];
  13215. var changed = false;
  13216. if (!pointer.active) {
  13217. changed = true;
  13218. pointer.active = true;
  13219. pointer.index = indx;
  13220. pointer.size = size;
  13221. pointer.type = type;
  13222. pointer.normalized = normalized;
  13223. pointer.stride = stride;
  13224. pointer.offset = offset;
  13225. pointer.buffer = buffer;
  13226. }
  13227. else {
  13228. if (pointer.buffer !== buffer) {
  13229. pointer.buffer = buffer;
  13230. changed = true;
  13231. }
  13232. if (pointer.size !== size) {
  13233. pointer.size = size;
  13234. changed = true;
  13235. }
  13236. if (pointer.type !== type) {
  13237. pointer.type = type;
  13238. changed = true;
  13239. }
  13240. if (pointer.normalized !== normalized) {
  13241. pointer.normalized = normalized;
  13242. changed = true;
  13243. }
  13244. if (pointer.stride !== stride) {
  13245. pointer.stride = stride;
  13246. changed = true;
  13247. }
  13248. if (pointer.offset !== offset) {
  13249. pointer.offset = offset;
  13250. changed = true;
  13251. }
  13252. }
  13253. if (changed || this._vaoRecordInProgress) {
  13254. this.bindArrayBuffer(buffer);
  13255. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13256. }
  13257. };
  13258. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13259. if (indexBuffer == null) {
  13260. return;
  13261. }
  13262. if (this._cachedIndexBuffer !== indexBuffer) {
  13263. this._cachedIndexBuffer = indexBuffer;
  13264. this.bindIndexBuffer(indexBuffer);
  13265. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13266. }
  13267. };
  13268. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13269. var attributes = effect.getAttributesNames();
  13270. if (!this._vaoRecordInProgress) {
  13271. this._unbindVertexArrayObject();
  13272. }
  13273. this.unbindAllAttributes();
  13274. for (var index = 0; index < attributes.length; index++) {
  13275. var order = effect.getAttributeLocation(index);
  13276. if (order >= 0) {
  13277. var vertexBuffer = vertexBuffers[attributes[index]];
  13278. if (!vertexBuffer) {
  13279. continue;
  13280. }
  13281. this._gl.enableVertexAttribArray(order);
  13282. if (!this._vaoRecordInProgress) {
  13283. this._vertexAttribArraysEnabled[order] = true;
  13284. }
  13285. var buffer = vertexBuffer.getBuffer();
  13286. if (buffer) {
  13287. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13288. if (vertexBuffer.getIsInstanced()) {
  13289. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13290. if (!this._vaoRecordInProgress) {
  13291. this._currentInstanceLocations.push(order);
  13292. this._currentInstanceBuffers.push(buffer);
  13293. }
  13294. }
  13295. }
  13296. }
  13297. }
  13298. };
  13299. /**
  13300. * Records a vertex array object
  13301. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13302. * @param vertexBuffers defines the list of vertex buffers to store
  13303. * @param indexBuffer defines the index buffer to store
  13304. * @param effect defines the effect to store
  13305. * @returns the new vertex array object
  13306. */
  13307. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13308. var vao = this._gl.createVertexArray();
  13309. this._vaoRecordInProgress = true;
  13310. this._gl.bindVertexArray(vao);
  13311. this._mustWipeVertexAttributes = true;
  13312. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13313. this.bindIndexBuffer(indexBuffer);
  13314. this._vaoRecordInProgress = false;
  13315. this._gl.bindVertexArray(null);
  13316. return vao;
  13317. };
  13318. /**
  13319. * Bind a specific vertex array object
  13320. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13321. * @param vertexArrayObject defines the vertex array object to bind
  13322. * @param indexBuffer defines the index buffer to bind
  13323. */
  13324. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13325. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13326. this._cachedVertexArrayObject = vertexArrayObject;
  13327. this._gl.bindVertexArray(vertexArrayObject);
  13328. this._cachedVertexBuffers = null;
  13329. this._cachedIndexBuffer = null;
  13330. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13331. this._mustWipeVertexAttributes = true;
  13332. }
  13333. };
  13334. /**
  13335. * Bind webGl buffers directly to the webGL context
  13336. * @param vertexBuffer defines the vertex buffer to bind
  13337. * @param indexBuffer defines the index buffer to bind
  13338. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13339. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13340. * @param effect defines the effect associated with the vertex buffer
  13341. */
  13342. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13343. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13344. this._cachedVertexBuffers = vertexBuffer;
  13345. this._cachedEffectForVertexBuffers = effect;
  13346. var attributesCount = effect.getAttributesCount();
  13347. this._unbindVertexArrayObject();
  13348. this.unbindAllAttributes();
  13349. var offset = 0;
  13350. for (var index = 0; index < attributesCount; index++) {
  13351. if (index < vertexDeclaration.length) {
  13352. var order = effect.getAttributeLocation(index);
  13353. if (order >= 0) {
  13354. this._gl.enableVertexAttribArray(order);
  13355. this._vertexAttribArraysEnabled[order] = true;
  13356. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13357. }
  13358. offset += vertexDeclaration[index] * 4;
  13359. }
  13360. }
  13361. }
  13362. this._bindIndexBufferWithCache(indexBuffer);
  13363. };
  13364. Engine.prototype._unbindVertexArrayObject = function () {
  13365. if (!this._cachedVertexArrayObject) {
  13366. return;
  13367. }
  13368. this._cachedVertexArrayObject = null;
  13369. this._gl.bindVertexArray(null);
  13370. };
  13371. /**
  13372. * Bind a list of vertex buffers to the webGL context
  13373. * @param vertexBuffers defines the list of vertex buffers to bind
  13374. * @param indexBuffer defines the index buffer to bind
  13375. * @param effect defines the effect associated with the vertex buffers
  13376. */
  13377. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13378. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13379. this._cachedVertexBuffers = vertexBuffers;
  13380. this._cachedEffectForVertexBuffers = effect;
  13381. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13382. }
  13383. this._bindIndexBufferWithCache(indexBuffer);
  13384. };
  13385. /**
  13386. * Unbind all instance attributes
  13387. */
  13388. Engine.prototype.unbindInstanceAttributes = function () {
  13389. var boundBuffer;
  13390. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13391. var instancesBuffer = this._currentInstanceBuffers[i];
  13392. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13393. boundBuffer = instancesBuffer;
  13394. this.bindArrayBuffer(instancesBuffer);
  13395. }
  13396. var offsetLocation = this._currentInstanceLocations[i];
  13397. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13398. }
  13399. this._currentInstanceBuffers.length = 0;
  13400. this._currentInstanceLocations.length = 0;
  13401. };
  13402. /**
  13403. * Release and free the memory of a vertex array object
  13404. * @param vao defines the vertex array object to delete
  13405. */
  13406. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13407. this._gl.deleteVertexArray(vao);
  13408. };
  13409. /** @hidden */
  13410. Engine.prototype._releaseBuffer = function (buffer) {
  13411. buffer.references--;
  13412. if (buffer.references === 0) {
  13413. this._gl.deleteBuffer(buffer);
  13414. return true;
  13415. }
  13416. return false;
  13417. };
  13418. /**
  13419. * Creates a webGL buffer to use with instanciation
  13420. * @param capacity defines the size of the buffer
  13421. * @returns the webGL buffer
  13422. */
  13423. Engine.prototype.createInstancesBuffer = function (capacity) {
  13424. var buffer = this._gl.createBuffer();
  13425. if (!buffer) {
  13426. throw new Error("Unable to create instance buffer");
  13427. }
  13428. buffer.capacity = capacity;
  13429. this.bindArrayBuffer(buffer);
  13430. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13431. return buffer;
  13432. };
  13433. /**
  13434. * Delete a webGL buffer used with instanciation
  13435. * @param buffer defines the webGL buffer to delete
  13436. */
  13437. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13438. this._gl.deleteBuffer(buffer);
  13439. };
  13440. /**
  13441. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13442. * @param instancesBuffer defines the webGL buffer to update and bind
  13443. * @param data defines the data to store in the buffer
  13444. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13445. */
  13446. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13447. this.bindArrayBuffer(instancesBuffer);
  13448. if (data) {
  13449. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13450. }
  13451. if (offsetLocations[0].index !== undefined) {
  13452. var stride = 0;
  13453. for (var i = 0; i < offsetLocations.length; i++) {
  13454. var ai = offsetLocations[i];
  13455. stride += ai.attributeSize * 4;
  13456. }
  13457. for (var i = 0; i < offsetLocations.length; i++) {
  13458. var ai = offsetLocations[i];
  13459. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13460. this._gl.enableVertexAttribArray(ai.index);
  13461. this._vertexAttribArraysEnabled[ai.index] = true;
  13462. }
  13463. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13464. this._gl.vertexAttribDivisor(ai.index, 1);
  13465. this._currentInstanceLocations.push(ai.index);
  13466. this._currentInstanceBuffers.push(instancesBuffer);
  13467. }
  13468. }
  13469. else {
  13470. for (var index = 0; index < 4; index++) {
  13471. var offsetLocation = offsetLocations[index];
  13472. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13473. this._gl.enableVertexAttribArray(offsetLocation);
  13474. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13475. }
  13476. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13477. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13478. this._currentInstanceLocations.push(offsetLocation);
  13479. this._currentInstanceBuffers.push(instancesBuffer);
  13480. }
  13481. }
  13482. };
  13483. /**
  13484. * Apply all cached states (depth, culling, stencil and alpha)
  13485. */
  13486. Engine.prototype.applyStates = function () {
  13487. this._depthCullingState.apply(this._gl);
  13488. this._stencilState.apply(this._gl);
  13489. this._alphaState.apply(this._gl);
  13490. };
  13491. /**
  13492. * Send a draw order
  13493. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13494. * @param indexStart defines the starting index
  13495. * @param indexCount defines the number of index to draw
  13496. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13497. */
  13498. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13499. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13500. };
  13501. /**
  13502. * Draw a list of points
  13503. * @param verticesStart defines the index of first vertex to draw
  13504. * @param verticesCount defines the count of vertices to draw
  13505. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13506. */
  13507. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13508. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13509. };
  13510. /**
  13511. * Draw a list of unindexed primitives
  13512. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13513. * @param verticesStart defines the index of first vertex to draw
  13514. * @param verticesCount defines the count of vertices to draw
  13515. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13516. */
  13517. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13518. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13519. };
  13520. /**
  13521. * Draw a list of indexed primitives
  13522. * @param fillMode defines the primitive to use
  13523. * @param indexStart defines the starting index
  13524. * @param indexCount defines the number of index to draw
  13525. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13526. */
  13527. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13528. // Apply states
  13529. this.applyStates();
  13530. this._drawCalls.addCount(1, false);
  13531. // Render
  13532. var drawMode = this._drawMode(fillMode);
  13533. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13534. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13535. if (instancesCount) {
  13536. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13537. }
  13538. else {
  13539. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13540. }
  13541. };
  13542. /**
  13543. * Draw a list of unindexed primitives
  13544. * @param fillMode defines the primitive to use
  13545. * @param verticesStart defines the index of first vertex to draw
  13546. * @param verticesCount defines the count of vertices to draw
  13547. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13548. */
  13549. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13550. // Apply states
  13551. this.applyStates();
  13552. this._drawCalls.addCount(1, false);
  13553. var drawMode = this._drawMode(fillMode);
  13554. if (instancesCount) {
  13555. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13556. }
  13557. else {
  13558. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13559. }
  13560. };
  13561. Engine.prototype._drawMode = function (fillMode) {
  13562. switch (fillMode) {
  13563. // Triangle views
  13564. case BABYLON.Material.TriangleFillMode:
  13565. return this._gl.TRIANGLES;
  13566. case BABYLON.Material.PointFillMode:
  13567. return this._gl.POINTS;
  13568. case BABYLON.Material.WireFrameFillMode:
  13569. return this._gl.LINES;
  13570. // Draw modes
  13571. case BABYLON.Material.PointListDrawMode:
  13572. return this._gl.POINTS;
  13573. case BABYLON.Material.LineListDrawMode:
  13574. return this._gl.LINES;
  13575. case BABYLON.Material.LineLoopDrawMode:
  13576. return this._gl.LINE_LOOP;
  13577. case BABYLON.Material.LineStripDrawMode:
  13578. return this._gl.LINE_STRIP;
  13579. case BABYLON.Material.TriangleStripDrawMode:
  13580. return this._gl.TRIANGLE_STRIP;
  13581. case BABYLON.Material.TriangleFanDrawMode:
  13582. return this._gl.TRIANGLE_FAN;
  13583. default:
  13584. return this._gl.TRIANGLES;
  13585. }
  13586. };
  13587. // Shaders
  13588. /** @hidden */
  13589. Engine.prototype._releaseEffect = function (effect) {
  13590. if (this._compiledEffects[effect._key]) {
  13591. delete this._compiledEffects[effect._key];
  13592. this._deleteProgram(effect.getProgram());
  13593. }
  13594. };
  13595. /** @hidden */
  13596. Engine.prototype._deleteProgram = function (program) {
  13597. if (program) {
  13598. program.__SPECTOR_rebuildProgram = null;
  13599. if (program.transformFeedback) {
  13600. this.deleteTransformFeedback(program.transformFeedback);
  13601. program.transformFeedback = null;
  13602. }
  13603. this._gl.deleteProgram(program);
  13604. }
  13605. };
  13606. /**
  13607. * Create a new effect (used to store vertex/fragment shaders)
  13608. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13609. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13610. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13611. * @param samplers defines an array of string used to represent textures
  13612. * @param defines defines the string containing the defines to use to compile the shaders
  13613. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13614. * @param onCompiled defines a function to call when the effect creation is successful
  13615. * @param onError defines a function to call when the effect creation has failed
  13616. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13617. * @returns the new Effect
  13618. */
  13619. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13620. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13621. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13622. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13623. if (this._compiledEffects[name]) {
  13624. var compiledEffect = this._compiledEffects[name];
  13625. if (onCompiled && compiledEffect.isReady()) {
  13626. onCompiled(compiledEffect);
  13627. }
  13628. return compiledEffect;
  13629. }
  13630. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13631. effect._key = name;
  13632. this._compiledEffects[name] = effect;
  13633. return effect;
  13634. };
  13635. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  13636. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  13637. };
  13638. ;
  13639. Engine.prototype._compileRawShader = function (source, type) {
  13640. var gl = this._gl;
  13641. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  13642. gl.shaderSource(shader, source);
  13643. gl.compileShader(shader);
  13644. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  13645. var log = gl.getShaderInfoLog(shader);
  13646. if (log) {
  13647. throw new Error(log);
  13648. }
  13649. }
  13650. if (!shader) {
  13651. throw new Error("Something went wrong while compile the shader.");
  13652. }
  13653. return shader;
  13654. };
  13655. ;
  13656. /**
  13657. * Directly creates a webGL program
  13658. * @param vertexCode defines the vertex shader code to use
  13659. * @param fragmentCode defines the fragment shader code to use
  13660. * @param context defines the webGL context to use (if not set, the current one will be used)
  13661. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13662. * @returns the new webGL program
  13663. */
  13664. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13665. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13666. context = context || this._gl;
  13667. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  13668. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  13669. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13670. };
  13671. /**
  13672. * Creates a webGL program
  13673. * @param vertexCode defines the vertex shader code to use
  13674. * @param fragmentCode defines the fragment shader code to use
  13675. * @param defines defines the string containing the defines to use to compile the shaders
  13676. * @param context defines the webGL context to use (if not set, the current one will be used)
  13677. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13678. * @returns the new webGL program
  13679. */
  13680. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13681. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13682. context = context || this._gl;
  13683. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13684. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13685. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  13686. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  13687. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13688. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13689. return program;
  13690. };
  13691. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13692. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13693. var shaderProgram = context.createProgram();
  13694. if (!shaderProgram) {
  13695. throw new Error("Unable to create program");
  13696. }
  13697. context.attachShader(shaderProgram, vertexShader);
  13698. context.attachShader(shaderProgram, fragmentShader);
  13699. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13700. var transformFeedback = this.createTransformFeedback();
  13701. this.bindTransformFeedback(transformFeedback);
  13702. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13703. shaderProgram.transformFeedback = transformFeedback;
  13704. }
  13705. context.linkProgram(shaderProgram);
  13706. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13707. this.bindTransformFeedback(null);
  13708. }
  13709. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13710. if (!linked) {
  13711. var error = context.getProgramInfoLog(shaderProgram);
  13712. if (error) {
  13713. throw new Error(error);
  13714. }
  13715. }
  13716. if (this.validateShaderPrograms) {
  13717. context.validateProgram(shaderProgram);
  13718. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  13719. if (!validated) {
  13720. var error = context.getProgramInfoLog(shaderProgram);
  13721. if (error) {
  13722. throw new Error(error);
  13723. }
  13724. }
  13725. }
  13726. context.deleteShader(vertexShader);
  13727. context.deleteShader(fragmentShader);
  13728. return shaderProgram;
  13729. };
  13730. /**
  13731. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13732. * @param shaderProgram defines the webGL program to use
  13733. * @param uniformsNames defines the list of uniform names
  13734. * @returns an array of webGL uniform locations
  13735. */
  13736. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13737. var results = new Array();
  13738. for (var index = 0; index < uniformsNames.length; index++) {
  13739. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13740. }
  13741. return results;
  13742. };
  13743. /**
  13744. * Gets the lsit of active attributes for a given webGL program
  13745. * @param shaderProgram defines the webGL program to use
  13746. * @param attributesNames defines the list of attribute names to get
  13747. * @returns an array of indices indicating the offset of each attribute
  13748. */
  13749. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13750. var results = [];
  13751. for (var index = 0; index < attributesNames.length; index++) {
  13752. try {
  13753. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13754. }
  13755. catch (e) {
  13756. results.push(-1);
  13757. }
  13758. }
  13759. return results;
  13760. };
  13761. /**
  13762. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13763. * @param effect defines the effect to activate
  13764. */
  13765. Engine.prototype.enableEffect = function (effect) {
  13766. if (!effect || effect === this._currentEffect) {
  13767. return;
  13768. }
  13769. // Use program
  13770. this.bindSamplers(effect);
  13771. this._currentEffect = effect;
  13772. if (effect.onBind) {
  13773. effect.onBind(effect);
  13774. }
  13775. if (effect._onBindObservable) {
  13776. effect._onBindObservable.notifyObservers(effect);
  13777. }
  13778. };
  13779. /**
  13780. * Set the value of an uniform to an array of int32
  13781. * @param uniform defines the webGL uniform location where to store the value
  13782. * @param array defines the array of int32 to store
  13783. */
  13784. Engine.prototype.setIntArray = function (uniform, array) {
  13785. if (!uniform)
  13786. return;
  13787. this._gl.uniform1iv(uniform, array);
  13788. };
  13789. /**
  13790. * Set the value of an uniform to an array of int32 (stored as vec2)
  13791. * @param uniform defines the webGL uniform location where to store the value
  13792. * @param array defines the array of int32 to store
  13793. */
  13794. Engine.prototype.setIntArray2 = function (uniform, array) {
  13795. if (!uniform || array.length % 2 !== 0)
  13796. return;
  13797. this._gl.uniform2iv(uniform, array);
  13798. };
  13799. /**
  13800. * Set the value of an uniform to an array of int32 (stored as vec3)
  13801. * @param uniform defines the webGL uniform location where to store the value
  13802. * @param array defines the array of int32 to store
  13803. */
  13804. Engine.prototype.setIntArray3 = function (uniform, array) {
  13805. if (!uniform || array.length % 3 !== 0)
  13806. return;
  13807. this._gl.uniform3iv(uniform, array);
  13808. };
  13809. /**
  13810. * Set the value of an uniform to an array of int32 (stored as vec4)
  13811. * @param uniform defines the webGL uniform location where to store the value
  13812. * @param array defines the array of int32 to store
  13813. */
  13814. Engine.prototype.setIntArray4 = function (uniform, array) {
  13815. if (!uniform || array.length % 4 !== 0)
  13816. return;
  13817. this._gl.uniform4iv(uniform, array);
  13818. };
  13819. /**
  13820. * Set the value of an uniform to an array of float32
  13821. * @param uniform defines the webGL uniform location where to store the value
  13822. * @param array defines the array of float32 to store
  13823. */
  13824. Engine.prototype.setFloatArray = function (uniform, array) {
  13825. if (!uniform)
  13826. return;
  13827. this._gl.uniform1fv(uniform, array);
  13828. };
  13829. /**
  13830. * Set the value of an uniform to an array of float32 (stored as vec2)
  13831. * @param uniform defines the webGL uniform location where to store the value
  13832. * @param array defines the array of float32 to store
  13833. */
  13834. Engine.prototype.setFloatArray2 = function (uniform, array) {
  13835. if (!uniform || array.length % 2 !== 0)
  13836. return;
  13837. this._gl.uniform2fv(uniform, array);
  13838. };
  13839. /**
  13840. * Set the value of an uniform to an array of float32 (stored as vec3)
  13841. * @param uniform defines the webGL uniform location where to store the value
  13842. * @param array defines the array of float32 to store
  13843. */
  13844. Engine.prototype.setFloatArray3 = function (uniform, array) {
  13845. if (!uniform || array.length % 3 !== 0)
  13846. return;
  13847. this._gl.uniform3fv(uniform, array);
  13848. };
  13849. /**
  13850. * Set the value of an uniform to an array of float32 (stored as vec4)
  13851. * @param uniform defines the webGL uniform location where to store the value
  13852. * @param array defines the array of float32 to store
  13853. */
  13854. Engine.prototype.setFloatArray4 = function (uniform, array) {
  13855. if (!uniform || array.length % 4 !== 0)
  13856. return;
  13857. this._gl.uniform4fv(uniform, array);
  13858. };
  13859. /**
  13860. * Set the value of an uniform to an array of number
  13861. * @param uniform defines the webGL uniform location where to store the value
  13862. * @param array defines the array of number to store
  13863. */
  13864. Engine.prototype.setArray = function (uniform, array) {
  13865. if (!uniform)
  13866. return;
  13867. this._gl.uniform1fv(uniform, array);
  13868. };
  13869. /**
  13870. * Set the value of an uniform to an array of number (stored as vec2)
  13871. * @param uniform defines the webGL uniform location where to store the value
  13872. * @param array defines the array of number to store
  13873. */
  13874. Engine.prototype.setArray2 = function (uniform, array) {
  13875. if (!uniform || array.length % 2 !== 0)
  13876. return;
  13877. this._gl.uniform2fv(uniform, array);
  13878. };
  13879. /**
  13880. * Set the value of an uniform to an array of number (stored as vec3)
  13881. * @param uniform defines the webGL uniform location where to store the value
  13882. * @param array defines the array of number to store
  13883. */
  13884. Engine.prototype.setArray3 = function (uniform, array) {
  13885. if (!uniform || array.length % 3 !== 0)
  13886. return;
  13887. this._gl.uniform3fv(uniform, array);
  13888. };
  13889. /**
  13890. * Set the value of an uniform to an array of number (stored as vec4)
  13891. * @param uniform defines the webGL uniform location where to store the value
  13892. * @param array defines the array of number to store
  13893. */
  13894. Engine.prototype.setArray4 = function (uniform, array) {
  13895. if (!uniform || array.length % 4 !== 0)
  13896. return;
  13897. this._gl.uniform4fv(uniform, array);
  13898. };
  13899. /**
  13900. * Set the value of an uniform to an array of float32 (stored as matrices)
  13901. * @param uniform defines the webGL uniform location where to store the value
  13902. * @param matrices defines the array of float32 to store
  13903. */
  13904. Engine.prototype.setMatrices = function (uniform, matrices) {
  13905. if (!uniform)
  13906. return;
  13907. this._gl.uniformMatrix4fv(uniform, false, matrices);
  13908. };
  13909. /**
  13910. * Set the value of an uniform to a matrix
  13911. * @param uniform defines the webGL uniform location where to store the value
  13912. * @param matrix defines the matrix to store
  13913. */
  13914. Engine.prototype.setMatrix = function (uniform, matrix) {
  13915. if (!uniform)
  13916. return;
  13917. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  13918. };
  13919. /**
  13920. * Set the value of an uniform to a matrix (3x3)
  13921. * @param uniform defines the webGL uniform location where to store the value
  13922. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  13923. */
  13924. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  13925. if (!uniform)
  13926. return;
  13927. this._gl.uniformMatrix3fv(uniform, false, matrix);
  13928. };
  13929. /**
  13930. * Set the value of an uniform to a matrix (2x2)
  13931. * @param uniform defines the webGL uniform location where to store the value
  13932. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  13933. */
  13934. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  13935. if (!uniform)
  13936. return;
  13937. this._gl.uniformMatrix2fv(uniform, false, matrix);
  13938. };
  13939. /**
  13940. * Set the value of an uniform to a number (int)
  13941. * @param uniform defines the webGL uniform location where to store the value
  13942. * @param value defines the int number to store
  13943. */
  13944. Engine.prototype.setInt = function (uniform, value) {
  13945. if (!uniform)
  13946. return;
  13947. this._gl.uniform1i(uniform, value);
  13948. };
  13949. /**
  13950. * Set the value of an uniform to a number (float)
  13951. * @param uniform defines the webGL uniform location where to store the value
  13952. * @param value defines the float number to store
  13953. */
  13954. Engine.prototype.setFloat = function (uniform, value) {
  13955. if (!uniform)
  13956. return;
  13957. this._gl.uniform1f(uniform, value);
  13958. };
  13959. /**
  13960. * Set the value of an uniform to a vec2
  13961. * @param uniform defines the webGL uniform location where to store the value
  13962. * @param x defines the 1st component of the value
  13963. * @param y defines the 2nd component of the value
  13964. */
  13965. Engine.prototype.setFloat2 = function (uniform, x, y) {
  13966. if (!uniform)
  13967. return;
  13968. this._gl.uniform2f(uniform, x, y);
  13969. };
  13970. /**
  13971. * Set the value of an uniform to a vec3
  13972. * @param uniform defines the webGL uniform location where to store the value
  13973. * @param x defines the 1st component of the value
  13974. * @param y defines the 2nd component of the value
  13975. * @param z defines the 3rd component of the value
  13976. */
  13977. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  13978. if (!uniform)
  13979. return;
  13980. this._gl.uniform3f(uniform, x, y, z);
  13981. };
  13982. /**
  13983. * Set the value of an uniform to a boolean
  13984. * @param uniform defines the webGL uniform location where to store the value
  13985. * @param bool defines the boolean to store
  13986. */
  13987. Engine.prototype.setBool = function (uniform, bool) {
  13988. if (!uniform)
  13989. return;
  13990. this._gl.uniform1i(uniform, bool);
  13991. };
  13992. /**
  13993. * Set the value of an uniform to a vec4
  13994. * @param uniform defines the webGL uniform location where to store the value
  13995. * @param x defines the 1st component of the value
  13996. * @param y defines the 2nd component of the value
  13997. * @param z defines the 3rd component of the value
  13998. * @param w defines the 4th component of the value
  13999. */
  14000. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14001. if (!uniform)
  14002. return;
  14003. this._gl.uniform4f(uniform, x, y, z, w);
  14004. };
  14005. /**
  14006. * Set the value of an uniform to a Color3
  14007. * @param uniform defines the webGL uniform location where to store the value
  14008. * @param color3 defines the color to store
  14009. */
  14010. Engine.prototype.setColor3 = function (uniform, color3) {
  14011. if (!uniform)
  14012. return;
  14013. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14014. };
  14015. /**
  14016. * Set the value of an uniform to a Color3 and an alpha value
  14017. * @param uniform defines the webGL uniform location where to store the value
  14018. * @param color3 defines the color to store
  14019. * @param alpha defines the alpha component to store
  14020. */
  14021. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14022. if (!uniform)
  14023. return;
  14024. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14025. };
  14026. /**
  14027. * Sets a Color4 on a uniform variable
  14028. * @param uniform defines the uniform location
  14029. * @param color4 defines the value to be set
  14030. */
  14031. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14032. if (!uniform)
  14033. return;
  14034. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14035. };
  14036. // States
  14037. /**
  14038. * Set various states to the webGL context
  14039. * @param culling defines backface culling state
  14040. * @param zOffset defines the value to apply to zOffset (0 by default)
  14041. * @param force defines if states must be applied even if cache is up to date
  14042. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14043. */
  14044. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14045. if (zOffset === void 0) { zOffset = 0; }
  14046. if (reverseSide === void 0) { reverseSide = false; }
  14047. // Culling
  14048. if (this._depthCullingState.cull !== culling || force) {
  14049. this._depthCullingState.cull = culling;
  14050. }
  14051. // Cull face
  14052. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14053. if (this._depthCullingState.cullFace !== cullFace || force) {
  14054. this._depthCullingState.cullFace = cullFace;
  14055. }
  14056. // Z offset
  14057. this.setZOffset(zOffset);
  14058. // Front face
  14059. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14060. if (this._depthCullingState.frontFace !== frontFace || force) {
  14061. this._depthCullingState.frontFace = frontFace;
  14062. }
  14063. };
  14064. /**
  14065. * Set the z offset to apply to current rendering
  14066. * @param value defines the offset to apply
  14067. */
  14068. Engine.prototype.setZOffset = function (value) {
  14069. this._depthCullingState.zOffset = value;
  14070. };
  14071. /**
  14072. * Gets the current value of the zOffset
  14073. * @returns the current zOffset state
  14074. */
  14075. Engine.prototype.getZOffset = function () {
  14076. return this._depthCullingState.zOffset;
  14077. };
  14078. /**
  14079. * Enable or disable depth buffering
  14080. * @param enable defines the state to set
  14081. */
  14082. Engine.prototype.setDepthBuffer = function (enable) {
  14083. this._depthCullingState.depthTest = enable;
  14084. };
  14085. /**
  14086. * Gets a boolean indicating if depth writing is enabled
  14087. * @returns the current depth writing state
  14088. */
  14089. Engine.prototype.getDepthWrite = function () {
  14090. return this._depthCullingState.depthMask;
  14091. };
  14092. /**
  14093. * Enable or disable depth writing
  14094. * @param enable defines the state to set
  14095. */
  14096. Engine.prototype.setDepthWrite = function (enable) {
  14097. this._depthCullingState.depthMask = enable;
  14098. };
  14099. /**
  14100. * Enable or disable color writing
  14101. * @param enable defines the state to set
  14102. */
  14103. Engine.prototype.setColorWrite = function (enable) {
  14104. this._gl.colorMask(enable, enable, enable, enable);
  14105. this._colorWrite = enable;
  14106. };
  14107. /**
  14108. * Gets a boolean indicating if color writing is enabled
  14109. * @returns the current color writing state
  14110. */
  14111. Engine.prototype.getColorWrite = function () {
  14112. return this._colorWrite;
  14113. };
  14114. /**
  14115. * Sets alpha constants used by some alpha blending modes
  14116. * @param r defines the red component
  14117. * @param g defines the green component
  14118. * @param b defines the blue component
  14119. * @param a defines the alpha component
  14120. */
  14121. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14122. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14123. };
  14124. /**
  14125. * Sets the current alpha mode
  14126. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14127. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14128. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14129. */
  14130. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14131. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14132. if (this._alphaMode === mode) {
  14133. return;
  14134. }
  14135. switch (mode) {
  14136. case Engine.ALPHA_DISABLE:
  14137. this._alphaState.alphaBlend = false;
  14138. break;
  14139. case Engine.ALPHA_PREMULTIPLIED:
  14140. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14141. this._alphaState.alphaBlend = true;
  14142. break;
  14143. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14144. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14145. this._alphaState.alphaBlend = true;
  14146. break;
  14147. case Engine.ALPHA_COMBINE:
  14148. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14149. this._alphaState.alphaBlend = true;
  14150. break;
  14151. case Engine.ALPHA_ONEONE:
  14152. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14153. this._alphaState.alphaBlend = true;
  14154. break;
  14155. case Engine.ALPHA_ADD:
  14156. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14157. this._alphaState.alphaBlend = true;
  14158. break;
  14159. case Engine.ALPHA_SUBTRACT:
  14160. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14161. this._alphaState.alphaBlend = true;
  14162. break;
  14163. case Engine.ALPHA_MULTIPLY:
  14164. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14165. this._alphaState.alphaBlend = true;
  14166. break;
  14167. case Engine.ALPHA_MAXIMIZED:
  14168. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14169. this._alphaState.alphaBlend = true;
  14170. break;
  14171. case Engine.ALPHA_INTERPOLATE:
  14172. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14173. this._alphaState.alphaBlend = true;
  14174. break;
  14175. case Engine.ALPHA_SCREENMODE:
  14176. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14177. this._alphaState.alphaBlend = true;
  14178. break;
  14179. }
  14180. if (!noDepthWriteChange) {
  14181. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14182. }
  14183. this._alphaMode = mode;
  14184. };
  14185. /**
  14186. * Gets the current alpha mode
  14187. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14188. * @returns the current alpha mode
  14189. */
  14190. Engine.prototype.getAlphaMode = function () {
  14191. return this._alphaMode;
  14192. };
  14193. // Textures
  14194. /**
  14195. * Clears the list of texture accessible through engine.
  14196. * This can help preventing texture load conflict due to name collision.
  14197. */
  14198. Engine.prototype.clearInternalTexturesCache = function () {
  14199. this._internalTexturesCache = [];
  14200. };
  14201. /**
  14202. * Force the entire cache to be cleared
  14203. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14204. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14205. */
  14206. Engine.prototype.wipeCaches = function (bruteForce) {
  14207. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14208. return;
  14209. }
  14210. this._currentEffect = null;
  14211. this._unpackFlipYCached = null;
  14212. this._viewportCached.x = 0;
  14213. this._viewportCached.y = 0;
  14214. this._viewportCached.z = 0;
  14215. this._viewportCached.w = 0;
  14216. if (bruteForce) {
  14217. this.resetTextureCache();
  14218. this._currentProgram = null;
  14219. this._stencilState.reset();
  14220. this._depthCullingState.reset();
  14221. this.setDepthFunctionToLessOrEqual();
  14222. this._alphaState.reset();
  14223. }
  14224. this._resetVertexBufferBinding();
  14225. this._cachedIndexBuffer = null;
  14226. this._cachedEffectForVertexBuffers = null;
  14227. this._unbindVertexArrayObject();
  14228. this.bindIndexBuffer(null);
  14229. };
  14230. /**
  14231. * Set the compressed texture format to use, based on the formats you have, and the formats
  14232. * supported by the hardware / browser.
  14233. *
  14234. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14235. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14236. * to API arguments needed to compressed textures. This puts the burden on the container
  14237. * generator to house the arcane code for determining these for current & future formats.
  14238. *
  14239. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14240. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14241. *
  14242. * Note: The result of this call is not taken into account when a texture is base64.
  14243. *
  14244. * @param formatsAvailable defines the list of those format families you have created
  14245. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14246. *
  14247. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14248. * @returns The extension selected.
  14249. */
  14250. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14251. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14252. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14253. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14254. return this._textureFormatInUse = this._texturesSupported[i];
  14255. }
  14256. }
  14257. }
  14258. // actively set format to nothing, to allow this to be called more than once
  14259. // and possibly fail the 2nd time
  14260. this._textureFormatInUse = null;
  14261. return null;
  14262. };
  14263. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  14264. var gl = this._gl;
  14265. var magFilter = gl.NEAREST;
  14266. var minFilter = gl.NEAREST;
  14267. switch (samplingMode) {
  14268. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  14269. magFilter = gl.LINEAR;
  14270. if (generateMipMaps) {
  14271. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14272. }
  14273. else {
  14274. minFilter = gl.LINEAR;
  14275. }
  14276. break;
  14277. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  14278. magFilter = gl.LINEAR;
  14279. if (generateMipMaps) {
  14280. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14281. }
  14282. else {
  14283. minFilter = gl.LINEAR;
  14284. }
  14285. break;
  14286. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  14287. magFilter = gl.NEAREST;
  14288. if (generateMipMaps) {
  14289. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14290. }
  14291. else {
  14292. minFilter = gl.NEAREST;
  14293. }
  14294. break;
  14295. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  14296. magFilter = gl.NEAREST;
  14297. if (generateMipMaps) {
  14298. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14299. }
  14300. else {
  14301. minFilter = gl.NEAREST;
  14302. }
  14303. break;
  14304. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  14305. magFilter = gl.NEAREST;
  14306. if (generateMipMaps) {
  14307. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14308. }
  14309. else {
  14310. minFilter = gl.LINEAR;
  14311. }
  14312. break;
  14313. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  14314. magFilter = gl.NEAREST;
  14315. if (generateMipMaps) {
  14316. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14317. }
  14318. else {
  14319. minFilter = gl.LINEAR;
  14320. }
  14321. break;
  14322. case Engine.TEXTURE_NEAREST_LINEAR:
  14323. magFilter = gl.NEAREST;
  14324. minFilter = gl.LINEAR;
  14325. break;
  14326. case Engine.TEXTURE_NEAREST_NEAREST:
  14327. magFilter = gl.NEAREST;
  14328. minFilter = gl.NEAREST;
  14329. break;
  14330. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  14331. magFilter = gl.LINEAR;
  14332. if (generateMipMaps) {
  14333. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14334. }
  14335. else {
  14336. minFilter = gl.NEAREST;
  14337. }
  14338. break;
  14339. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  14340. magFilter = gl.LINEAR;
  14341. if (generateMipMaps) {
  14342. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14343. }
  14344. else {
  14345. minFilter = gl.NEAREST;
  14346. }
  14347. break;
  14348. case Engine.TEXTURE_LINEAR_LINEAR:
  14349. magFilter = gl.LINEAR;
  14350. minFilter = gl.LINEAR;
  14351. break;
  14352. case Engine.TEXTURE_LINEAR_NEAREST:
  14353. magFilter = gl.LINEAR;
  14354. minFilter = gl.NEAREST;
  14355. break;
  14356. }
  14357. return {
  14358. min: minFilter,
  14359. mag: magFilter
  14360. };
  14361. };
  14362. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  14363. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14364. var img;
  14365. var onload = function () {
  14366. loadedImages[index] = img;
  14367. loadedImages._internalCount++;
  14368. if (scene) {
  14369. scene._removePendingData(img);
  14370. }
  14371. if (loadedImages._internalCount === 6) {
  14372. onfinish(loadedImages);
  14373. }
  14374. };
  14375. var onerror = function (message, exception) {
  14376. if (scene) {
  14377. scene._removePendingData(img);
  14378. }
  14379. if (onErrorCallBack) {
  14380. onErrorCallBack(message, exception);
  14381. }
  14382. };
  14383. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14384. if (scene) {
  14385. scene._addPendingData(img);
  14386. }
  14387. };
  14388. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  14389. if (onError === void 0) { onError = null; }
  14390. var loadedImages = [];
  14391. loadedImages._internalCount = 0;
  14392. for (var index = 0; index < 6; index++) {
  14393. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  14394. }
  14395. };
  14396. ;
  14397. /** @hidden */
  14398. Engine.prototype._createTexture = function () {
  14399. var texture = this._gl.createTexture();
  14400. if (!texture) {
  14401. throw new Error("Unable to create texture");
  14402. }
  14403. return texture;
  14404. };
  14405. /**
  14406. * Usually called from BABYLON.Texture.ts.
  14407. * Passed information to create a WebGLTexture
  14408. * @param urlArg defines a value which contains one of the following:
  14409. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14410. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14411. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14412. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14413. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14414. * @param scene needed for loading to the correct scene
  14415. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14416. * @param onLoad optional callback to be called upon successful completion
  14417. * @param onError optional callback to be called upon failure
  14418. * @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
  14419. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14420. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14421. * @param forcedExtension defines the extension to use to pick the right loader
  14422. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14423. */
  14424. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  14425. var _this = this;
  14426. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  14427. if (onLoad === void 0) { onLoad = null; }
  14428. if (onError === void 0) { onError = null; }
  14429. if (buffer === void 0) { buffer = null; }
  14430. if (fallback === void 0) { fallback = null; }
  14431. if (format === void 0) { format = null; }
  14432. if (forcedExtension === void 0) { forcedExtension = null; }
  14433. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14434. var fromData = url.substr(0, 5) === "data:";
  14435. var fromBlob = url.substr(0, 5) === "blob:";
  14436. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14437. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14438. // establish the file extension, if possible
  14439. var lastDot = url.lastIndexOf('.');
  14440. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  14441. var loader = null;
  14442. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  14443. var availableLoader = _a[_i];
  14444. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  14445. loader = availableLoader;
  14446. break;
  14447. }
  14448. }
  14449. if (loader) {
  14450. url = loader.transformUrl(url, this._textureFormatInUse);
  14451. }
  14452. if (scene) {
  14453. scene._addPendingData(texture);
  14454. }
  14455. texture.url = url;
  14456. texture.generateMipMaps = !noMipmap;
  14457. texture.samplingMode = samplingMode;
  14458. texture.invertY = invertY;
  14459. if (!this._doNotHandleContextLost) {
  14460. // Keep a link to the buffer only if we plan to handle context lost
  14461. texture._buffer = buffer;
  14462. }
  14463. var onLoadObserver = null;
  14464. if (onLoad && !fallback) {
  14465. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14466. }
  14467. if (!fallback)
  14468. this._internalTexturesCache.push(texture);
  14469. var onInternalError = function (message, exception) {
  14470. if (scene) {
  14471. scene._removePendingData(texture);
  14472. }
  14473. var customFallback = false;
  14474. if (loader) {
  14475. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  14476. if (fallbackUrl) {
  14477. // Add Back
  14478. customFallback = true;
  14479. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14480. }
  14481. }
  14482. if (!customFallback) {
  14483. if (onLoadObserver) {
  14484. texture.onLoadedObservable.remove(onLoadObserver);
  14485. }
  14486. if (BABYLON.Tools.UseFallbackTexture) {
  14487. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14488. }
  14489. }
  14490. if (onError) {
  14491. onError(message || "Unknown error", exception);
  14492. }
  14493. };
  14494. // processing for non-image formats
  14495. if (loader) {
  14496. var callback = function (data) {
  14497. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  14498. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  14499. done();
  14500. return false;
  14501. }, samplingMode);
  14502. });
  14503. };
  14504. if (!buffer) {
  14505. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14506. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  14507. });
  14508. }
  14509. else {
  14510. callback(buffer);
  14511. }
  14512. }
  14513. else {
  14514. var onload = function (img) {
  14515. if (fromBlob && !_this._doNotHandleContextLost) {
  14516. // We need to store the image if we need to rebuild the texture
  14517. // in case of a webgl context lost
  14518. texture._buffer = img;
  14519. }
  14520. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14521. var gl = _this._gl;
  14522. var isPot = (img.width === potWidth && img.height === potHeight);
  14523. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14524. if (isPot) {
  14525. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14526. return false;
  14527. }
  14528. var maxTextureSize = _this._caps.maxTextureSize;
  14529. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14530. _this._prepareWorkingCanvas();
  14531. if (!_this._workingCanvas || !_this._workingContext) {
  14532. return false;
  14533. }
  14534. _this._workingCanvas.width = potWidth;
  14535. _this._workingCanvas.height = potHeight;
  14536. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14537. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14538. texture.width = potWidth;
  14539. texture.height = potHeight;
  14540. return false;
  14541. }
  14542. else {
  14543. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14544. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14545. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14546. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14547. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14548. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14549. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14550. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14551. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14552. _this._releaseTexture(source_1);
  14553. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14554. continuationCallback();
  14555. });
  14556. }
  14557. return true;
  14558. }, samplingMode);
  14559. };
  14560. if (!fromData || isBase64) {
  14561. if (buffer instanceof HTMLImageElement) {
  14562. onload(buffer);
  14563. }
  14564. else {
  14565. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  14566. }
  14567. }
  14568. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14569. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  14570. }
  14571. else {
  14572. onload(buffer);
  14573. }
  14574. }
  14575. return texture;
  14576. };
  14577. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14578. var _this = this;
  14579. var rtt = this.createRenderTargetTexture({
  14580. width: destination.width,
  14581. height: destination.height,
  14582. }, {
  14583. generateMipMaps: false,
  14584. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14585. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  14586. generateDepthBuffer: false,
  14587. generateStencilBuffer: false
  14588. });
  14589. if (!this._rescalePostProcess) {
  14590. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14591. }
  14592. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14593. _this._rescalePostProcess.onApply = function (effect) {
  14594. effect._bindTexture("textureSampler", source);
  14595. };
  14596. var hostingScene = scene;
  14597. if (!hostingScene) {
  14598. hostingScene = _this.scenes[_this.scenes.length - 1];
  14599. }
  14600. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14601. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14602. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14603. _this.unBindFramebuffer(rtt);
  14604. _this._releaseTexture(rtt);
  14605. if (onComplete) {
  14606. onComplete();
  14607. }
  14608. });
  14609. };
  14610. /**
  14611. * Update a raw texture
  14612. * @param texture defines the texture to update
  14613. * @param data defines the data to store in the texture
  14614. * @param format defines the format of the data
  14615. * @param invertY defines if data must be stored with Y axis inverted
  14616. * @param compression defines the compression used (null by default)
  14617. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14618. */
  14619. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14620. if (compression === void 0) { compression = null; }
  14621. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14622. if (!texture) {
  14623. return;
  14624. }
  14625. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14626. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14627. // babylon's internalFormat but gl's texImage2D format
  14628. var internalFormat = this._getInternalFormat(format);
  14629. var textureType = this._getWebGLTextureType(type);
  14630. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14631. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14632. if (!this._doNotHandleContextLost) {
  14633. texture._bufferView = data;
  14634. texture.format = format;
  14635. texture.type = type;
  14636. texture.invertY = invertY;
  14637. texture._compression = compression;
  14638. }
  14639. if (texture.width % 4 !== 0) {
  14640. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14641. }
  14642. if (compression && data) {
  14643. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14644. }
  14645. else {
  14646. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14647. }
  14648. if (texture.generateMipMaps) {
  14649. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14650. }
  14651. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14652. // this.resetTextureCache();
  14653. texture.isReady = true;
  14654. };
  14655. /**
  14656. * Creates a raw texture
  14657. * @param data defines the data to store in the texture
  14658. * @param width defines the width of the texture
  14659. * @param height defines the height of the texture
  14660. * @param format defines the format of the data
  14661. * @param generateMipMaps defines if the engine should generate the mip levels
  14662. * @param invertY defines if data must be stored with Y axis inverted
  14663. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14664. * @param compression defines the compression used (null by default)
  14665. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14666. * @returns the raw texture inside an InternalTexture
  14667. */
  14668. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14669. if (compression === void 0) { compression = null; }
  14670. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14671. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14672. texture.baseWidth = width;
  14673. texture.baseHeight = height;
  14674. texture.width = width;
  14675. texture.height = height;
  14676. texture.format = format;
  14677. texture.generateMipMaps = generateMipMaps;
  14678. texture.samplingMode = samplingMode;
  14679. texture.invertY = invertY;
  14680. texture._compression = compression;
  14681. texture.type = type;
  14682. if (!this._doNotHandleContextLost) {
  14683. texture._bufferView = data;
  14684. }
  14685. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14686. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14687. // Filters
  14688. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  14689. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14690. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14691. if (generateMipMaps) {
  14692. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14693. }
  14694. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14695. this._internalTexturesCache.push(texture);
  14696. return texture;
  14697. };
  14698. /** @hidden */
  14699. Engine.prototype._unpackFlipY = function (value) {
  14700. if (this._unpackFlipYCached !== value) {
  14701. this._unpackFlipYCached = value;
  14702. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  14703. }
  14704. };
  14705. /** @hidden */
  14706. Engine.prototype._getUnpackAlignement = function () {
  14707. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  14708. };
  14709. /**
  14710. * Creates a dynamic texture
  14711. * @param width defines the width of the texture
  14712. * @param height defines the height of the texture
  14713. * @param generateMipMaps defines if the engine should generate the mip levels
  14714. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14715. * @returns the dynamic texture inside an InternalTexture
  14716. */
  14717. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14718. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14719. texture.baseWidth = width;
  14720. texture.baseHeight = height;
  14721. if (generateMipMaps) {
  14722. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14723. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14724. }
  14725. // this.resetTextureCache();
  14726. texture.width = width;
  14727. texture.height = height;
  14728. texture.isReady = false;
  14729. texture.generateMipMaps = generateMipMaps;
  14730. texture.samplingMode = samplingMode;
  14731. this.updateTextureSamplingMode(samplingMode, texture);
  14732. this._internalTexturesCache.push(texture);
  14733. return texture;
  14734. };
  14735. /**
  14736. * Update the sampling mode of a given texture
  14737. * @param samplingMode defines the required sampling mode
  14738. * @param texture defines the texture to update
  14739. */
  14740. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14741. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  14742. if (texture.isCube) {
  14743. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14744. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14745. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14746. }
  14747. else if (texture.is3D) {
  14748. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14749. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14750. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14751. }
  14752. else {
  14753. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14754. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14755. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14756. }
  14757. texture.samplingMode = samplingMode;
  14758. };
  14759. /**
  14760. * Update the content of a dynamic texture
  14761. * @param texture defines the texture to update
  14762. * @param canvas defines the canvas containing the source
  14763. * @param invertY defines if data must be stored with Y axis inverted
  14764. * @param premulAlpha defines if alpha is stored as premultiplied
  14765. * @param format defines the format of the data
  14766. */
  14767. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14768. if (premulAlpha === void 0) { premulAlpha = false; }
  14769. if (!texture) {
  14770. return;
  14771. }
  14772. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14773. this._unpackFlipY(invertY);
  14774. if (premulAlpha) {
  14775. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14776. }
  14777. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14778. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14779. if (texture.generateMipMaps) {
  14780. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14781. }
  14782. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14783. if (premulAlpha) {
  14784. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14785. }
  14786. texture.isReady = true;
  14787. };
  14788. /**
  14789. * Update a video texture
  14790. * @param texture defines the texture to update
  14791. * @param video defines the video element to use
  14792. * @param invertY defines if data must be stored with Y axis inverted
  14793. */
  14794. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14795. if (!texture || texture._isDisabled) {
  14796. return;
  14797. }
  14798. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14799. this._unpackFlipY(!invertY); // Video are upside down by default
  14800. try {
  14801. // Testing video texture support
  14802. if (this._videoTextureSupported === undefined) {
  14803. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14804. if (this._gl.getError() !== 0) {
  14805. this._videoTextureSupported = false;
  14806. }
  14807. else {
  14808. this._videoTextureSupported = true;
  14809. }
  14810. }
  14811. // Copy video through the current working canvas if video texture is not supported
  14812. if (!this._videoTextureSupported) {
  14813. if (!texture._workingCanvas) {
  14814. texture._workingCanvas = document.createElement("canvas");
  14815. var context = texture._workingCanvas.getContext("2d");
  14816. if (!context) {
  14817. throw new Error("Unable to get 2d context");
  14818. }
  14819. texture._workingContext = context;
  14820. texture._workingCanvas.width = texture.width;
  14821. texture._workingCanvas.height = texture.height;
  14822. }
  14823. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14824. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14825. }
  14826. else {
  14827. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14828. }
  14829. if (texture.generateMipMaps) {
  14830. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14831. }
  14832. if (!wasPreviouslyBound) {
  14833. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14834. }
  14835. // this.resetTextureCache();
  14836. texture.isReady = true;
  14837. }
  14838. catch (ex) {
  14839. // Something unexpected
  14840. // Let's disable the texture
  14841. texture._isDisabled = true;
  14842. }
  14843. };
  14844. /**
  14845. * Updates a depth texture Comparison Mode and Function.
  14846. * If the comparison Function is equal to 0, the mode will be set to none.
  14847. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14848. * @param texture The texture to set the comparison function for
  14849. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14850. */
  14851. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14852. if (this.webGLVersion === 1) {
  14853. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14854. return;
  14855. }
  14856. var gl = this._gl;
  14857. if (texture.isCube) {
  14858. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14859. if (comparisonFunction === 0) {
  14860. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14861. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14862. }
  14863. else {
  14864. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14865. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14866. }
  14867. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14868. }
  14869. else {
  14870. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14871. if (comparisonFunction === 0) {
  14872. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14873. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14874. }
  14875. else {
  14876. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14877. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14878. }
  14879. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14880. }
  14881. texture._comparisonFunction = comparisonFunction;
  14882. };
  14883. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14884. var width = size.width || size;
  14885. var height = size.height || size;
  14886. internalTexture.baseWidth = width;
  14887. internalTexture.baseHeight = height;
  14888. internalTexture.width = width;
  14889. internalTexture.height = height;
  14890. internalTexture.isReady = true;
  14891. internalTexture.samples = 1;
  14892. internalTexture.generateMipMaps = false;
  14893. internalTexture._generateDepthBuffer = true;
  14894. internalTexture._generateStencilBuffer = generateStencil;
  14895. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  14896. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14897. internalTexture._comparisonFunction = comparisonFunction;
  14898. var gl = this._gl;
  14899. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14900. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  14901. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14902. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14903. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14904. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14905. if (comparisonFunction === 0) {
  14906. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14907. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14908. }
  14909. else {
  14910. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14911. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14912. }
  14913. };
  14914. /**
  14915. * Creates a depth stencil texture.
  14916. * This is only available in WebGL 2 or with the depth texture extension available.
  14917. * @param size The size of face edge in the texture.
  14918. * @param options The options defining the texture.
  14919. * @returns The texture
  14920. */
  14921. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14922. if (options.isCube) {
  14923. var width = size.width || size;
  14924. return this._createDepthStencilCubeTexture(width, options);
  14925. }
  14926. else {
  14927. return this._createDepthStencilTexture(size, options);
  14928. }
  14929. };
  14930. /**
  14931. * Creates a depth stencil texture.
  14932. * This is only available in WebGL 2 or with the depth texture extension available.
  14933. * @param size The size of face edge in the texture.
  14934. * @param options The options defining the texture.
  14935. * @returns The texture
  14936. */
  14937. Engine.prototype._createDepthStencilTexture = function (size, options) {
  14938. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  14939. if (!this._caps.depthTextureExtension) {
  14940. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  14941. return internalTexture;
  14942. }
  14943. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14944. var gl = this._gl;
  14945. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  14946. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14947. if (this.webGLVersion > 1) {
  14948. if (internalOptions.generateStencil) {
  14949. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14950. }
  14951. else {
  14952. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14953. }
  14954. }
  14955. else {
  14956. if (internalOptions.generateStencil) {
  14957. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14958. }
  14959. else {
  14960. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14961. }
  14962. }
  14963. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14964. return internalTexture;
  14965. };
  14966. /**
  14967. * Creates a depth stencil cube texture.
  14968. * This is only available in WebGL 2.
  14969. * @param size The size of face edge in the cube texture.
  14970. * @param options The options defining the cube texture.
  14971. * @returns The cube texture
  14972. */
  14973. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  14974. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  14975. internalTexture.isCube = true;
  14976. if (this.webGLVersion === 1) {
  14977. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  14978. return internalTexture;
  14979. }
  14980. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14981. var gl = this._gl;
  14982. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  14983. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14984. // Create the depth/stencil buffer
  14985. for (var face = 0; face < 6; face++) {
  14986. if (internalOptions.generateStencil) {
  14987. 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);
  14988. }
  14989. else {
  14990. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14991. }
  14992. }
  14993. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14994. return internalTexture;
  14995. };
  14996. /**
  14997. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  14998. * @param renderTarget The render target to set the frame buffer for
  14999. */
  15000. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15001. // Create the framebuffer
  15002. var internalTexture = renderTarget.getInternalTexture();
  15003. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15004. return;
  15005. }
  15006. var gl = this._gl;
  15007. var depthStencilTexture = renderTarget.depthStencilTexture;
  15008. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15009. if (depthStencilTexture.isCube) {
  15010. if (depthStencilTexture._generateStencilBuffer) {
  15011. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15012. }
  15013. else {
  15014. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15015. }
  15016. }
  15017. else {
  15018. if (depthStencilTexture._generateStencilBuffer) {
  15019. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15020. }
  15021. else {
  15022. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15023. }
  15024. }
  15025. this.bindUnboundFramebuffer(null);
  15026. };
  15027. /**
  15028. * Creates a new render target texture
  15029. * @param size defines the size of the texture
  15030. * @param options defines the options used to create the texture
  15031. * @returns a new render target texture stored in an InternalTexture
  15032. */
  15033. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15034. var fullOptions = new RenderTargetCreationOptions();
  15035. if (options !== undefined && typeof options === "object") {
  15036. fullOptions.generateMipMaps = options.generateMipMaps;
  15037. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15038. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15039. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15040. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15041. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15042. }
  15043. else {
  15044. fullOptions.generateMipMaps = options;
  15045. fullOptions.generateDepthBuffer = true;
  15046. fullOptions.generateStencilBuffer = false;
  15047. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15048. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15049. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15050. }
  15051. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15052. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15053. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15054. }
  15055. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15056. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15057. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15058. }
  15059. var gl = this._gl;
  15060. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15061. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15062. var width = size.width || size;
  15063. var height = size.height || size;
  15064. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  15065. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15066. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15067. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15068. }
  15069. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15070. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15071. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15072. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15073. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15074. // Create the framebuffer
  15075. var currentFrameBuffer = this._currentFramebuffer;
  15076. var framebuffer = gl.createFramebuffer();
  15077. this.bindUnboundFramebuffer(framebuffer);
  15078. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15079. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15080. if (fullOptions.generateMipMaps) {
  15081. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15082. }
  15083. // Unbind
  15084. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15085. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15086. this.bindUnboundFramebuffer(currentFrameBuffer);
  15087. texture._framebuffer = framebuffer;
  15088. texture.baseWidth = width;
  15089. texture.baseHeight = height;
  15090. texture.width = width;
  15091. texture.height = height;
  15092. texture.isReady = true;
  15093. texture.samples = 1;
  15094. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15095. texture.samplingMode = fullOptions.samplingMode;
  15096. texture.type = fullOptions.type;
  15097. texture.format = fullOptions.format;
  15098. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15099. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15100. // this.resetTextureCache();
  15101. this._internalTexturesCache.push(texture);
  15102. return texture;
  15103. };
  15104. /**
  15105. * Create a multi render target texture
  15106. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15107. * @param size defines the size of the texture
  15108. * @param options defines the creation options
  15109. * @returns the cube texture as an InternalTexture
  15110. */
  15111. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15112. var generateMipMaps = false;
  15113. var generateDepthBuffer = true;
  15114. var generateStencilBuffer = false;
  15115. var generateDepthTexture = false;
  15116. var textureCount = 1;
  15117. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15118. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15119. var types = new Array();
  15120. var samplingModes = new Array();
  15121. if (options !== undefined) {
  15122. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15123. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15124. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15125. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15126. textureCount = options.textureCount || 1;
  15127. if (options.types) {
  15128. types = options.types;
  15129. }
  15130. if (options.samplingModes) {
  15131. samplingModes = options.samplingModes;
  15132. }
  15133. }
  15134. var gl = this._gl;
  15135. // Create the framebuffer
  15136. var framebuffer = gl.createFramebuffer();
  15137. this.bindUnboundFramebuffer(framebuffer);
  15138. var width = size.width || size;
  15139. var height = size.height || size;
  15140. var textures = [];
  15141. var attachments = [];
  15142. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15143. for (var i = 0; i < textureCount; i++) {
  15144. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15145. var type = types[i] || defaultType;
  15146. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15147. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15148. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15149. }
  15150. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15151. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15152. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15153. }
  15154. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15155. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15156. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15157. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15158. }
  15159. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15160. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15161. textures.push(texture);
  15162. attachments.push(attachment);
  15163. gl.activeTexture(gl["TEXTURE" + i]);
  15164. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15165. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15166. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15167. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15168. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15169. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15170. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15171. if (generateMipMaps) {
  15172. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15173. }
  15174. // Unbind
  15175. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15176. texture._framebuffer = framebuffer;
  15177. texture._depthStencilBuffer = depthStencilBuffer;
  15178. texture.baseWidth = width;
  15179. texture.baseHeight = height;
  15180. texture.width = width;
  15181. texture.height = height;
  15182. texture.isReady = true;
  15183. texture.samples = 1;
  15184. texture.generateMipMaps = generateMipMaps;
  15185. texture.samplingMode = samplingMode;
  15186. texture.type = type;
  15187. texture._generateDepthBuffer = generateDepthBuffer;
  15188. texture._generateStencilBuffer = generateStencilBuffer;
  15189. texture._attachments = attachments;
  15190. this._internalTexturesCache.push(texture);
  15191. }
  15192. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15193. // Depth texture
  15194. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15195. gl.activeTexture(gl.TEXTURE0);
  15196. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15197. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15198. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15199. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15200. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15201. 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);
  15202. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15203. depthTexture._framebuffer = framebuffer;
  15204. depthTexture.baseWidth = width;
  15205. depthTexture.baseHeight = height;
  15206. depthTexture.width = width;
  15207. depthTexture.height = height;
  15208. depthTexture.isReady = true;
  15209. depthTexture.samples = 1;
  15210. depthTexture.generateMipMaps = generateMipMaps;
  15211. depthTexture.samplingMode = gl.NEAREST;
  15212. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15213. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15214. textures.push(depthTexture);
  15215. this._internalTexturesCache.push(depthTexture);
  15216. }
  15217. gl.drawBuffers(attachments);
  15218. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15219. this.bindUnboundFramebuffer(null);
  15220. this.resetTextureCache();
  15221. return textures;
  15222. };
  15223. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15224. if (samples === void 0) { samples = 1; }
  15225. var depthStencilBuffer = null;
  15226. var gl = this._gl;
  15227. // Create the depth/stencil buffer
  15228. if (generateStencilBuffer) {
  15229. depthStencilBuffer = gl.createRenderbuffer();
  15230. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15231. if (samples > 1) {
  15232. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15233. }
  15234. else {
  15235. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15236. }
  15237. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15238. }
  15239. else if (generateDepthBuffer) {
  15240. depthStencilBuffer = gl.createRenderbuffer();
  15241. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15242. if (samples > 1) {
  15243. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15244. }
  15245. else {
  15246. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15247. }
  15248. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15249. }
  15250. return depthStencilBuffer;
  15251. };
  15252. /**
  15253. * Updates the sample count of a render target texture
  15254. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15255. * @param texture defines the texture to update
  15256. * @param samples defines the sample count to set
  15257. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15258. */
  15259. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15260. if (this.webGLVersion < 2 || !texture) {
  15261. return 1;
  15262. }
  15263. if (texture.samples === samples) {
  15264. return samples;
  15265. }
  15266. var gl = this._gl;
  15267. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15268. // Dispose previous render buffers
  15269. if (texture._depthStencilBuffer) {
  15270. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15271. texture._depthStencilBuffer = null;
  15272. }
  15273. if (texture._MSAAFramebuffer) {
  15274. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15275. texture._MSAAFramebuffer = null;
  15276. }
  15277. if (texture._MSAARenderBuffer) {
  15278. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15279. texture._MSAARenderBuffer = null;
  15280. }
  15281. if (samples > 1) {
  15282. var framebuffer = gl.createFramebuffer();
  15283. if (!framebuffer) {
  15284. throw new Error("Unable to create multi sampled framebuffer");
  15285. }
  15286. texture._MSAAFramebuffer = framebuffer;
  15287. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15288. var colorRenderbuffer = gl.createRenderbuffer();
  15289. if (!colorRenderbuffer) {
  15290. throw new Error("Unable to create multi sampled framebuffer");
  15291. }
  15292. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15293. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15294. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15295. texture._MSAARenderBuffer = colorRenderbuffer;
  15296. }
  15297. else {
  15298. this.bindUnboundFramebuffer(texture._framebuffer);
  15299. }
  15300. texture.samples = samples;
  15301. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15302. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15303. this.bindUnboundFramebuffer(null);
  15304. return samples;
  15305. };
  15306. /**
  15307. * Update the sample count for a given multiple render target texture
  15308. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15309. * @param textures defines the textures to update
  15310. * @param samples defines the sample count to set
  15311. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15312. */
  15313. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15314. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15315. return 1;
  15316. }
  15317. if (textures[0].samples === samples) {
  15318. return samples;
  15319. }
  15320. var gl = this._gl;
  15321. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15322. // Dispose previous render buffers
  15323. if (textures[0]._depthStencilBuffer) {
  15324. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15325. textures[0]._depthStencilBuffer = null;
  15326. }
  15327. if (textures[0]._MSAAFramebuffer) {
  15328. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15329. textures[0]._MSAAFramebuffer = null;
  15330. }
  15331. for (var i = 0; i < textures.length; i++) {
  15332. if (textures[i]._MSAARenderBuffer) {
  15333. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15334. textures[i]._MSAARenderBuffer = null;
  15335. }
  15336. }
  15337. if (samples > 1) {
  15338. var framebuffer = gl.createFramebuffer();
  15339. if (!framebuffer) {
  15340. throw new Error("Unable to create multi sampled framebuffer");
  15341. }
  15342. this.bindUnboundFramebuffer(framebuffer);
  15343. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15344. var attachments = [];
  15345. for (var i = 0; i < textures.length; i++) {
  15346. var texture = textures[i];
  15347. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15348. var colorRenderbuffer = gl.createRenderbuffer();
  15349. if (!colorRenderbuffer) {
  15350. throw new Error("Unable to create multi sampled framebuffer");
  15351. }
  15352. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15353. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15354. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15355. texture._MSAAFramebuffer = framebuffer;
  15356. texture._MSAARenderBuffer = colorRenderbuffer;
  15357. texture.samples = samples;
  15358. texture._depthStencilBuffer = depthStencilBuffer;
  15359. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15360. attachments.push(attachment);
  15361. }
  15362. gl.drawBuffers(attachments);
  15363. }
  15364. else {
  15365. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15366. }
  15367. this.bindUnboundFramebuffer(null);
  15368. return samples;
  15369. };
  15370. /** @hidden */
  15371. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  15372. if (faceIndex === void 0) { faceIndex = 0; }
  15373. if (lod === void 0) { lod = 0; }
  15374. var gl = this._gl;
  15375. var target = gl.TEXTURE_2D;
  15376. if (texture.isCube) {
  15377. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15378. }
  15379. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15380. };
  15381. /** @hidden */
  15382. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  15383. if (faceIndex === void 0) { faceIndex = 0; }
  15384. if (lod === void 0) { lod = 0; }
  15385. var gl = this._gl;
  15386. var textureType = this._getWebGLTextureType(texture.type);
  15387. var format = this._getInternalFormat(texture.format);
  15388. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15389. this._unpackFlipY(texture.invertY);
  15390. var target = gl.TEXTURE_2D;
  15391. if (texture.isCube) {
  15392. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15393. }
  15394. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  15395. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  15396. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  15397. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  15398. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  15399. };
  15400. /** @hidden */
  15401. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  15402. if (faceIndex === void 0) { faceIndex = 0; }
  15403. if (lod === void 0) { lod = 0; }
  15404. var gl = this._gl;
  15405. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15406. this._bindTextureDirectly(bindTarget, texture, true);
  15407. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  15408. this._bindTextureDirectly(bindTarget, null, true);
  15409. };
  15410. /** @hidden */
  15411. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  15412. if (faceIndex === void 0) { faceIndex = 0; }
  15413. if (lod === void 0) { lod = 0; }
  15414. var gl = this._gl;
  15415. var textureType = this._getWebGLTextureType(texture.type);
  15416. var format = this._getInternalFormat(texture.format);
  15417. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15418. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15419. this._bindTextureDirectly(bindTarget, texture, true);
  15420. this._unpackFlipY(texture.invertY);
  15421. var target = gl.TEXTURE_2D;
  15422. if (texture.isCube) {
  15423. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15424. }
  15425. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15426. this._bindTextureDirectly(bindTarget, null, true);
  15427. };
  15428. /**
  15429. * Creates a new render target cube texture
  15430. * @param size defines the size of the texture
  15431. * @param options defines the options used to create the texture
  15432. * @returns a new render target cube texture stored in an InternalTexture
  15433. */
  15434. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15435. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15436. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15437. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15438. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15439. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15440. }
  15441. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15442. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15443. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15444. }
  15445. var gl = this._gl;
  15446. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15447. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15448. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  15449. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15450. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15451. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15452. }
  15453. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15454. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15455. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15456. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15457. for (var face = 0; face < 6; face++) {
  15458. 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);
  15459. }
  15460. // Create the framebuffer
  15461. var framebuffer = gl.createFramebuffer();
  15462. this.bindUnboundFramebuffer(framebuffer);
  15463. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15464. // MipMaps
  15465. if (fullOptions.generateMipMaps) {
  15466. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15467. }
  15468. // Unbind
  15469. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15470. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15471. this.bindUnboundFramebuffer(null);
  15472. texture._framebuffer = framebuffer;
  15473. texture.width = size;
  15474. texture.height = size;
  15475. texture.isReady = true;
  15476. texture.isCube = true;
  15477. texture.samples = 1;
  15478. texture.generateMipMaps = fullOptions.generateMipMaps;
  15479. texture.samplingMode = fullOptions.samplingMode;
  15480. texture.type = fullOptions.type;
  15481. texture.format = fullOptions.format;
  15482. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15483. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15484. this._internalTexturesCache.push(texture);
  15485. return texture;
  15486. };
  15487. /**
  15488. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15489. * @param rootUrl defines the url where the file to load is located
  15490. * @param scene defines the current scene
  15491. * @param lodScale defines scale to apply to the mip map selection
  15492. * @param lodOffset defines offset to apply to the mip map selection
  15493. * @param onLoad defines an optional callback raised when the texture is loaded
  15494. * @param onError defines an optional callback raised if there is an issue to load the texture
  15495. * @param format defines the format of the data
  15496. * @param forcedExtension defines the extension to use to pick the right loader
  15497. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15498. * @returns the cube texture as an InternalTexture
  15499. */
  15500. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15501. var _this = this;
  15502. if (onLoad === void 0) { onLoad = null; }
  15503. if (onError === void 0) { onError = null; }
  15504. if (forcedExtension === void 0) { forcedExtension = null; }
  15505. if (createPolynomials === void 0) { createPolynomials = true; }
  15506. var callback = function (loadData) {
  15507. if (!loadData) {
  15508. if (onLoad) {
  15509. onLoad(null);
  15510. }
  15511. return;
  15512. }
  15513. var texture = loadData.texture;
  15514. if (!createPolynomials) {
  15515. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15516. }
  15517. else if (loadData.info.sphericalPolynomial) {
  15518. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15519. }
  15520. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15521. if (_this._caps.textureLOD) {
  15522. // Do not add extra process if texture lod is supported.
  15523. if (onLoad) {
  15524. onLoad(texture);
  15525. }
  15526. return;
  15527. }
  15528. var mipSlices = 3;
  15529. var gl = _this._gl;
  15530. var width = loadData.width;
  15531. if (!width) {
  15532. return;
  15533. }
  15534. var textures = [];
  15535. for (var i = 0; i < mipSlices; i++) {
  15536. //compute LOD from even spacing in smoothness (matching shader calculation)
  15537. var smoothness = i / (mipSlices - 1);
  15538. var roughness = 1 - smoothness;
  15539. var minLODIndex = lodOffset; // roughness = 0
  15540. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15541. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15542. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15543. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15544. glTextureFromLod.type = texture.type;
  15545. glTextureFromLod.format = texture.format;
  15546. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  15547. glTextureFromLod.height = glTextureFromLod.width;
  15548. glTextureFromLod.isCube = true;
  15549. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15550. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15551. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15552. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15553. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15554. if (loadData.isDDS) {
  15555. var info = loadData.info;
  15556. var data = loadData.data;
  15557. _this._unpackFlipY(info.isCompressed);
  15558. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  15559. }
  15560. else {
  15561. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15562. }
  15563. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15564. // Wrap in a base texture for easy binding.
  15565. var lodTexture = new BABYLON.BaseTexture(scene);
  15566. lodTexture.isCube = true;
  15567. lodTexture._texture = glTextureFromLod;
  15568. glTextureFromLod.isReady = true;
  15569. textures.push(lodTexture);
  15570. }
  15571. texture._lodTextureHigh = textures[2];
  15572. texture._lodTextureMid = textures[1];
  15573. texture._lodTextureLow = textures[0];
  15574. if (onLoad) {
  15575. onLoad(texture);
  15576. }
  15577. };
  15578. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15579. };
  15580. /**
  15581. * Creates a cube texture
  15582. * @param rootUrl defines the url where the files to load is located
  15583. * @param scene defines the current scene
  15584. * @param files defines the list of files to load (1 per face)
  15585. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15586. * @param onLoad defines an optional callback raised when the texture is loaded
  15587. * @param onError defines an optional callback raised if there is an issue to load the texture
  15588. * @param format defines the format of the data
  15589. * @param forcedExtension defines the extension to use to pick the right loader
  15590. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15591. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15592. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15593. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  15594. * @returns the cube texture as an InternalTexture
  15595. */
  15596. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  15597. var _this = this;
  15598. if (onLoad === void 0) { onLoad = null; }
  15599. if (onError === void 0) { onError = null; }
  15600. if (forcedExtension === void 0) { forcedExtension = null; }
  15601. if (createPolynomials === void 0) { createPolynomials = false; }
  15602. if (lodScale === void 0) { lodScale = 0; }
  15603. if (lodOffset === void 0) { lodOffset = 0; }
  15604. if (fallback === void 0) { fallback = null; }
  15605. var gl = this._gl;
  15606. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15607. texture.isCube = true;
  15608. texture.url = rootUrl;
  15609. texture.generateMipMaps = !noMipmap;
  15610. texture._lodGenerationScale = lodScale;
  15611. texture._lodGenerationOffset = lodOffset;
  15612. if (!this._doNotHandleContextLost) {
  15613. texture._extension = forcedExtension;
  15614. texture._files = files;
  15615. }
  15616. var lastDot = rootUrl.lastIndexOf('.');
  15617. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15618. var loader = null;
  15619. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15620. var availableLoader = _a[_i];
  15621. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  15622. loader = availableLoader;
  15623. break;
  15624. }
  15625. }
  15626. var onInternalError = function (request, exception) {
  15627. if (loader) {
  15628. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  15629. if (fallbackUrl) {
  15630. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  15631. }
  15632. }
  15633. if (onError && request) {
  15634. onError(request.status + " " + request.statusText, exception);
  15635. }
  15636. };
  15637. if (loader) {
  15638. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  15639. var onloaddata = function (data) {
  15640. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15641. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  15642. };
  15643. if (files && files.length === 6) {
  15644. if (loader.supportCascades) {
  15645. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  15646. }
  15647. else if (onError) {
  15648. onError("Textures type does not support cascades.");
  15649. }
  15650. }
  15651. else {
  15652. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  15653. }
  15654. }
  15655. else {
  15656. if (!files) {
  15657. throw new Error("Cannot load cubemap because files were not defined");
  15658. }
  15659. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15660. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15661. var height = width;
  15662. _this._prepareWorkingCanvas();
  15663. if (!_this._workingCanvas || !_this._workingContext) {
  15664. return;
  15665. }
  15666. _this._workingCanvas.width = width;
  15667. _this._workingCanvas.height = height;
  15668. var faces = [
  15669. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15670. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15671. ];
  15672. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15673. _this._unpackFlipY(false);
  15674. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15675. for (var index = 0; index < faces.length; index++) {
  15676. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15677. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15678. }
  15679. if (!noMipmap) {
  15680. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15681. }
  15682. _this._setCubeMapTextureParams(!noMipmap);
  15683. texture.width = width;
  15684. texture.height = height;
  15685. texture.isReady = true;
  15686. if (format) {
  15687. texture.format = format;
  15688. }
  15689. texture.onLoadedObservable.notifyObservers(texture);
  15690. texture.onLoadedObservable.clear();
  15691. if (onLoad) {
  15692. onLoad();
  15693. }
  15694. }, files, onError);
  15695. }
  15696. this._internalTexturesCache.push(texture);
  15697. return texture;
  15698. };
  15699. /**
  15700. * @hidden
  15701. */
  15702. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  15703. var gl = this._gl;
  15704. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15705. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15706. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15707. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15708. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15709. // this.resetTextureCache();
  15710. };
  15711. /**
  15712. * Update a raw cube texture
  15713. * @param texture defines the texture to udpdate
  15714. * @param data defines the data to store
  15715. * @param format defines the data format
  15716. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15717. * @param invertY defines if data must be stored with Y axis inverted
  15718. * @param compression defines the compression used (null by default)
  15719. * @param level defines which level of the texture to update
  15720. */
  15721. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15722. if (compression === void 0) { compression = null; }
  15723. if (level === void 0) { level = 0; }
  15724. texture._bufferViewArray = data;
  15725. texture.format = format;
  15726. texture.type = type;
  15727. texture.invertY = invertY;
  15728. texture._compression = compression;
  15729. var gl = this._gl;
  15730. var textureType = this._getWebGLTextureType(type);
  15731. var internalFormat = this._getInternalFormat(format);
  15732. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15733. var needConversion = false;
  15734. if (internalFormat === gl.RGB) {
  15735. internalFormat = gl.RGBA;
  15736. needConversion = true;
  15737. }
  15738. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15739. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15740. if (texture.width % 4 !== 0) {
  15741. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15742. }
  15743. // Data are known to be in +X +Y +Z -X -Y -Z
  15744. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15745. var faceData = data[faceIndex];
  15746. if (compression) {
  15747. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15748. }
  15749. else {
  15750. if (needConversion) {
  15751. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15752. }
  15753. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15754. }
  15755. }
  15756. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15757. if (isPot && texture.generateMipMaps && level === 0) {
  15758. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15759. }
  15760. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15761. // this.resetTextureCache();
  15762. texture.isReady = true;
  15763. };
  15764. /**
  15765. * Creates a new raw cube texture
  15766. * @param data defines the array of data to use to create each face
  15767. * @param size defines the size of the textures
  15768. * @param format defines the format of the data
  15769. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15770. * @param generateMipMaps defines if the engine should generate the mip levels
  15771. * @param invertY defines if data must be stored with Y axis inverted
  15772. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15773. * @param compression defines the compression used (null by default)
  15774. * @returns the cube texture as an InternalTexture
  15775. */
  15776. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15777. if (compression === void 0) { compression = null; }
  15778. var gl = this._gl;
  15779. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15780. texture.isCube = true;
  15781. texture.format = format;
  15782. texture.type = type;
  15783. if (!this._doNotHandleContextLost) {
  15784. texture._bufferViewArray = data;
  15785. }
  15786. var textureType = this._getWebGLTextureType(type);
  15787. var internalFormat = this._getInternalFormat(format);
  15788. if (internalFormat === gl.RGB) {
  15789. internalFormat = gl.RGBA;
  15790. }
  15791. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  15792. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15793. generateMipMaps = false;
  15794. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15795. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15796. }
  15797. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15798. generateMipMaps = false;
  15799. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15800. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15801. }
  15802. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  15803. generateMipMaps = false;
  15804. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  15805. }
  15806. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  15807. generateMipMaps = false;
  15808. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  15809. }
  15810. var width = size;
  15811. var height = width;
  15812. texture.width = width;
  15813. texture.height = height;
  15814. // Double check on POT to generate Mips.
  15815. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15816. if (!isPot) {
  15817. generateMipMaps = false;
  15818. }
  15819. // Upload data if needed. The texture won't be ready until then.
  15820. if (data) {
  15821. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15822. }
  15823. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15824. // Filters
  15825. if (data && generateMipMaps) {
  15826. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15827. }
  15828. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15829. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15830. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15831. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15832. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15833. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15834. texture.generateMipMaps = generateMipMaps;
  15835. return texture;
  15836. };
  15837. /**
  15838. * Creates a new raw cube texture from a specified url
  15839. * @param url defines the url where the data is located
  15840. * @param scene defines the current scene
  15841. * @param size defines the size of the textures
  15842. * @param format defines the format of the data
  15843. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15844. * @param noMipmap defines if the engine should avoid generating the mip levels
  15845. * @param callback defines a callback used to extract texture data from loaded data
  15846. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15847. * @param onLoad defines a callback called when texture is loaded
  15848. * @param onError defines a callback called if there is an error
  15849. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15850. * @param invertY defines if data must be stored with Y axis inverted
  15851. * @returns the cube texture as an InternalTexture
  15852. */
  15853. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15854. var _this = this;
  15855. if (onLoad === void 0) { onLoad = null; }
  15856. if (onError === void 0) { onError = null; }
  15857. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15858. if (invertY === void 0) { invertY = false; }
  15859. var gl = this._gl;
  15860. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15861. scene._addPendingData(texture);
  15862. texture.url = url;
  15863. this._internalTexturesCache.push(texture);
  15864. var onerror = function (request, exception) {
  15865. scene._removePendingData(texture);
  15866. if (onError && request) {
  15867. onError(request.status + " " + request.statusText, exception);
  15868. }
  15869. };
  15870. var internalCallback = function (data) {
  15871. var width = texture.width;
  15872. var faceDataArrays = callback(data);
  15873. if (!faceDataArrays) {
  15874. return;
  15875. }
  15876. if (mipmapGenerator) {
  15877. var textureType = _this._getWebGLTextureType(type);
  15878. var internalFormat = _this._getInternalFormat(format);
  15879. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15880. var needConversion = false;
  15881. if (internalFormat === gl.RGB) {
  15882. internalFormat = gl.RGBA;
  15883. needConversion = true;
  15884. }
  15885. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15886. _this._unpackFlipY(false);
  15887. var mipData = mipmapGenerator(faceDataArrays);
  15888. for (var level = 0; level < mipData.length; level++) {
  15889. var mipSize = width >> level;
  15890. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15891. var mipFaceData = mipData[level][faceIndex];
  15892. if (needConversion) {
  15893. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15894. }
  15895. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15896. }
  15897. }
  15898. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15899. }
  15900. else {
  15901. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15902. }
  15903. texture.isReady = true;
  15904. // this.resetTextureCache();
  15905. scene._removePendingData(texture);
  15906. if (onLoad) {
  15907. onLoad();
  15908. }
  15909. };
  15910. this._loadFile(url, function (data) {
  15911. internalCallback(data);
  15912. }, undefined, scene.database, true, onerror);
  15913. return texture;
  15914. };
  15915. ;
  15916. /**
  15917. * Update a raw 3D texture
  15918. * @param texture defines the texture to update
  15919. * @param data defines the data to store
  15920. * @param format defines the data format
  15921. * @param invertY defines if data must be stored with Y axis inverted
  15922. * @param compression defines the used compression (can be null)
  15923. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  15924. */
  15925. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  15926. if (compression === void 0) { compression = null; }
  15927. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15928. var internalType = this._getWebGLTextureType(textureType);
  15929. var internalFormat = this._getInternalFormat(format);
  15930. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  15931. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15932. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15933. if (!this._doNotHandleContextLost) {
  15934. texture._bufferView = data;
  15935. texture.format = format;
  15936. texture.invertY = invertY;
  15937. texture._compression = compression;
  15938. }
  15939. if (texture.width % 4 !== 0) {
  15940. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15941. }
  15942. if (compression && data) {
  15943. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  15944. }
  15945. else {
  15946. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  15947. }
  15948. if (texture.generateMipMaps) {
  15949. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15950. }
  15951. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15952. // this.resetTextureCache();
  15953. texture.isReady = true;
  15954. };
  15955. /**
  15956. * Creates a new raw 3D texture
  15957. * @param data defines the data used to create the texture
  15958. * @param width defines the width of the texture
  15959. * @param height defines the height of the texture
  15960. * @param depth defines the depth of the texture
  15961. * @param format defines the format of the texture
  15962. * @param generateMipMaps defines if the engine must generate mip levels
  15963. * @param invertY defines if data must be stored with Y axis inverted
  15964. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15965. * @param compression defines the compressed used (can be null)
  15966. * @param textureType defines the compressed used (can be null)
  15967. * @returns a new raw 3D texture (stored in an InternalTexture)
  15968. */
  15969. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  15970. if (compression === void 0) { compression = null; }
  15971. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15972. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  15973. texture.baseWidth = width;
  15974. texture.baseHeight = height;
  15975. texture.baseDepth = depth;
  15976. texture.width = width;
  15977. texture.height = height;
  15978. texture.depth = depth;
  15979. texture.format = format;
  15980. texture.type = textureType;
  15981. texture.generateMipMaps = generateMipMaps;
  15982. texture.samplingMode = samplingMode;
  15983. texture.is3D = true;
  15984. if (!this._doNotHandleContextLost) {
  15985. texture._bufferView = data;
  15986. }
  15987. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  15988. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15989. // Filters
  15990. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15991. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15992. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15993. if (generateMipMaps) {
  15994. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15995. }
  15996. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15997. this._internalTexturesCache.push(texture);
  15998. return texture;
  15999. };
  16000. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16001. var gl = this._gl;
  16002. if (!gl) {
  16003. return;
  16004. }
  16005. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  16006. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16007. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16008. if (!noMipmap && !isCompressed) {
  16009. gl.generateMipmap(gl.TEXTURE_2D);
  16010. }
  16011. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16012. // this.resetTextureCache();
  16013. if (scene) {
  16014. scene._removePendingData(texture);
  16015. }
  16016. texture.onLoadedObservable.notifyObservers(texture);
  16017. texture.onLoadedObservable.clear();
  16018. };
  16019. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16020. var _this = this;
  16021. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16022. var maxTextureSize = this.getCaps().maxTextureSize;
  16023. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16024. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16025. var gl = this._gl;
  16026. if (!gl) {
  16027. return;
  16028. }
  16029. if (!texture._webGLTexture) {
  16030. // this.resetTextureCache();
  16031. if (scene) {
  16032. scene._removePendingData(texture);
  16033. }
  16034. return;
  16035. }
  16036. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16037. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16038. texture.baseWidth = width;
  16039. texture.baseHeight = height;
  16040. texture.width = potWidth;
  16041. texture.height = potHeight;
  16042. texture.isReady = true;
  16043. if (processFunction(potWidth, potHeight, function () {
  16044. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16045. })) {
  16046. // Returning as texture needs extra async steps
  16047. return;
  16048. }
  16049. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16050. };
  16051. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16052. // Create new RGBA data container.
  16053. var rgbaData;
  16054. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16055. rgbaData = new Float32Array(width * height * 4);
  16056. }
  16057. else {
  16058. rgbaData = new Uint32Array(width * height * 4);
  16059. }
  16060. // Convert each pixel.
  16061. for (var x = 0; x < width; x++) {
  16062. for (var y = 0; y < height; y++) {
  16063. var index = (y * width + x) * 3;
  16064. var newIndex = (y * width + x) * 4;
  16065. // Map Old Value to new value.
  16066. rgbaData[newIndex + 0] = rgbData[index + 0];
  16067. rgbaData[newIndex + 1] = rgbData[index + 1];
  16068. rgbaData[newIndex + 2] = rgbData[index + 2];
  16069. // Add fully opaque alpha channel.
  16070. rgbaData[newIndex + 3] = 1;
  16071. }
  16072. }
  16073. return rgbaData;
  16074. };
  16075. /** @hidden */
  16076. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16077. var gl = this._gl;
  16078. if (texture._framebuffer) {
  16079. gl.deleteFramebuffer(texture._framebuffer);
  16080. texture._framebuffer = null;
  16081. }
  16082. if (texture._depthStencilBuffer) {
  16083. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16084. texture._depthStencilBuffer = null;
  16085. }
  16086. if (texture._MSAAFramebuffer) {
  16087. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16088. texture._MSAAFramebuffer = null;
  16089. }
  16090. if (texture._MSAARenderBuffer) {
  16091. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16092. texture._MSAARenderBuffer = null;
  16093. }
  16094. };
  16095. /** @hidden */
  16096. Engine.prototype._releaseTexture = function (texture) {
  16097. var gl = this._gl;
  16098. this._releaseFramebufferObjects(texture);
  16099. gl.deleteTexture(texture._webGLTexture);
  16100. // Unbind channels
  16101. this.unbindAllTextures();
  16102. var index = this._internalTexturesCache.indexOf(texture);
  16103. if (index !== -1) {
  16104. this._internalTexturesCache.splice(index, 1);
  16105. }
  16106. // Integrated fixed lod samplers.
  16107. if (texture._lodTextureHigh) {
  16108. texture._lodTextureHigh.dispose();
  16109. }
  16110. if (texture._lodTextureMid) {
  16111. texture._lodTextureMid.dispose();
  16112. }
  16113. if (texture._lodTextureLow) {
  16114. texture._lodTextureLow.dispose();
  16115. }
  16116. // Set output texture of post process to null if the texture has been released/disposed
  16117. this.scenes.forEach(function (scene) {
  16118. scene.postProcesses.forEach(function (postProcess) {
  16119. if (postProcess._outputTexture == texture) {
  16120. postProcess._outputTexture = null;
  16121. }
  16122. });
  16123. scene.cameras.forEach(function (camera) {
  16124. camera._postProcesses.forEach(function (postProcess) {
  16125. if (postProcess) {
  16126. if (postProcess._outputTexture == texture) {
  16127. postProcess._outputTexture = null;
  16128. }
  16129. }
  16130. });
  16131. });
  16132. });
  16133. };
  16134. Engine.prototype.setProgram = function (program) {
  16135. if (this._currentProgram !== program) {
  16136. this._gl.useProgram(program);
  16137. this._currentProgram = program;
  16138. }
  16139. };
  16140. /**
  16141. * Binds an effect to the webGL context
  16142. * @param effect defines the effect to bind
  16143. */
  16144. Engine.prototype.bindSamplers = function (effect) {
  16145. this.setProgram(effect.getProgram());
  16146. var samplers = effect.getSamplers();
  16147. for (var index = 0; index < samplers.length; index++) {
  16148. var uniform = effect.getUniform(samplers[index]);
  16149. if (uniform) {
  16150. this._boundUniforms[index] = uniform;
  16151. }
  16152. }
  16153. this._currentEffect = null;
  16154. };
  16155. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16156. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16157. return;
  16158. }
  16159. // Remove
  16160. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16161. // Bind last to it
  16162. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16163. // Bind to dummy
  16164. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16165. };
  16166. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16167. if (!internalTexture) {
  16168. return -1;
  16169. }
  16170. internalTexture._initialSlot = channel;
  16171. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16172. if (channel !== internalTexture._designatedSlot) {
  16173. this._textureCollisions.addCount(1, false);
  16174. }
  16175. }
  16176. else {
  16177. if (channel !== internalTexture._designatedSlot) {
  16178. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16179. return internalTexture._designatedSlot;
  16180. }
  16181. else {
  16182. // No slot for this texture, let's pick a new one (if we find a free slot)
  16183. if (this._nextFreeTextureSlots.length) {
  16184. return this._nextFreeTextureSlots[0];
  16185. }
  16186. // We need to recycle the oldest bound texture, sorry.
  16187. this._textureCollisions.addCount(1, false);
  16188. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16189. }
  16190. }
  16191. }
  16192. return channel;
  16193. };
  16194. Engine.prototype._linkTrackers = function (previous, next) {
  16195. previous.next = next;
  16196. next.previous = previous;
  16197. };
  16198. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16199. var currentSlot = internalTexture._designatedSlot;
  16200. if (currentSlot === -1) {
  16201. return -1;
  16202. }
  16203. internalTexture._designatedSlot = -1;
  16204. if (this.disableTextureBindingOptimization) {
  16205. return -1;
  16206. }
  16207. // Remove from bound list
  16208. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16209. // Free the slot
  16210. this._boundTexturesCache[currentSlot] = null;
  16211. this._nextFreeTextureSlots.push(currentSlot);
  16212. return currentSlot;
  16213. };
  16214. Engine.prototype._activateCurrentTexture = function () {
  16215. if (this._currentTextureChannel !== this._activeChannel) {
  16216. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16217. this._currentTextureChannel = this._activeChannel;
  16218. }
  16219. };
  16220. /** @hidden */
  16221. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16222. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16223. if (force === void 0) { force = false; }
  16224. var wasPreviouslyBound = false;
  16225. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16226. this._activeChannel = texture._designatedSlot;
  16227. }
  16228. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16229. var isTextureForRendering = texture && texture._initialSlot > -1;
  16230. if (currentTextureBound !== texture || force) {
  16231. if (currentTextureBound) {
  16232. this._removeDesignatedSlot(currentTextureBound);
  16233. }
  16234. this._activateCurrentTexture();
  16235. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16236. this._boundTexturesCache[this._activeChannel] = texture;
  16237. if (texture) {
  16238. if (!this.disableTextureBindingOptimization) {
  16239. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16240. if (slotIndex > -1) {
  16241. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16242. }
  16243. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16244. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16245. }
  16246. texture._designatedSlot = this._activeChannel;
  16247. }
  16248. }
  16249. else if (forTextureDataUpdate) {
  16250. wasPreviouslyBound = true;
  16251. this._activateCurrentTexture();
  16252. }
  16253. if (isTextureForRendering && !forTextureDataUpdate) {
  16254. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16255. }
  16256. return wasPreviouslyBound;
  16257. };
  16258. /** @hidden */
  16259. Engine.prototype._bindTexture = function (channel, texture) {
  16260. if (channel < 0) {
  16261. return;
  16262. }
  16263. if (texture) {
  16264. channel = this._getCorrectTextureChannel(channel, texture);
  16265. }
  16266. this._activeChannel = channel;
  16267. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16268. };
  16269. /**
  16270. * Sets a texture to the webGL context from a postprocess
  16271. * @param channel defines the channel to use
  16272. * @param postProcess defines the source postprocess
  16273. */
  16274. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16275. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16276. };
  16277. /**
  16278. * Binds the output of the passed in post process to the texture channel specified
  16279. * @param channel The channel the texture should be bound to
  16280. * @param postProcess The post process which's output should be bound
  16281. */
  16282. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16283. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16284. };
  16285. /**
  16286. * Unbind all textures from the webGL context
  16287. */
  16288. Engine.prototype.unbindAllTextures = function () {
  16289. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16290. this._activeChannel = channel;
  16291. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16292. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16293. if (this.webGLVersion > 1) {
  16294. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16295. }
  16296. }
  16297. };
  16298. /**
  16299. * Sets a texture to the according uniform.
  16300. * @param channel The texture channel
  16301. * @param uniform The uniform to set
  16302. * @param texture The texture to apply
  16303. */
  16304. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16305. if (channel < 0) {
  16306. return;
  16307. }
  16308. if (uniform) {
  16309. this._boundUniforms[channel] = uniform;
  16310. }
  16311. this._setTexture(channel, texture);
  16312. };
  16313. /**
  16314. * Sets a depth stencil texture from a render target to the according uniform.
  16315. * @param channel The texture channel
  16316. * @param uniform The uniform to set
  16317. * @param texture The render target texture containing the depth stencil texture to apply
  16318. */
  16319. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16320. if (channel < 0) {
  16321. return;
  16322. }
  16323. if (uniform) {
  16324. this._boundUniforms[channel] = uniform;
  16325. }
  16326. if (!texture || !texture.depthStencilTexture) {
  16327. this._setTexture(channel, null);
  16328. }
  16329. else {
  16330. this._setTexture(channel, texture, false, true);
  16331. }
  16332. };
  16333. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16334. var uniform = this._boundUniforms[sourceSlot];
  16335. if (uniform._currentState === destination) {
  16336. return;
  16337. }
  16338. this._gl.uniform1i(uniform, destination);
  16339. uniform._currentState = destination;
  16340. };
  16341. Engine.prototype._getTextureWrapMode = function (mode) {
  16342. switch (mode) {
  16343. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  16344. return this._gl.REPEAT;
  16345. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  16346. return this._gl.CLAMP_TO_EDGE;
  16347. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  16348. return this._gl.MIRRORED_REPEAT;
  16349. }
  16350. return this._gl.REPEAT;
  16351. };
  16352. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16353. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16354. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16355. // Not ready?
  16356. if (!texture) {
  16357. if (this._boundTexturesCache[channel] != null) {
  16358. this._activeChannel = channel;
  16359. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16360. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16361. if (this.webGLVersion > 1) {
  16362. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16363. }
  16364. }
  16365. return false;
  16366. }
  16367. // Video
  16368. if (texture.video) {
  16369. this._activeChannel = channel;
  16370. texture.update();
  16371. }
  16372. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16373. texture.delayLoad();
  16374. return false;
  16375. }
  16376. var internalTexture;
  16377. if (depthStencilTexture) {
  16378. internalTexture = texture.depthStencilTexture;
  16379. }
  16380. else if (texture.isReady()) {
  16381. internalTexture = texture.getInternalTexture();
  16382. }
  16383. else if (texture.isCube) {
  16384. internalTexture = this.emptyCubeTexture;
  16385. }
  16386. else if (texture.is3D) {
  16387. internalTexture = this.emptyTexture3D;
  16388. }
  16389. else {
  16390. internalTexture = this.emptyTexture;
  16391. }
  16392. if (!isPartOfTextureArray) {
  16393. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16394. }
  16395. var needToBind = true;
  16396. if (this._boundTexturesCache[channel] === internalTexture) {
  16397. this._moveBoundTextureOnTop(internalTexture);
  16398. if (!isPartOfTextureArray) {
  16399. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16400. }
  16401. needToBind = false;
  16402. }
  16403. this._activeChannel = channel;
  16404. if (internalTexture && internalTexture.is3D) {
  16405. if (needToBind) {
  16406. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16407. }
  16408. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16409. internalTexture._cachedWrapU = texture.wrapU;
  16410. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16411. }
  16412. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16413. internalTexture._cachedWrapV = texture.wrapV;
  16414. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16415. }
  16416. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16417. internalTexture._cachedWrapR = texture.wrapR;
  16418. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16419. }
  16420. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16421. }
  16422. else if (internalTexture && internalTexture.isCube) {
  16423. if (needToBind) {
  16424. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16425. }
  16426. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16427. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16428. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16429. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16430. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16431. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16432. }
  16433. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16434. }
  16435. else {
  16436. if (needToBind) {
  16437. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16438. }
  16439. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16440. internalTexture._cachedWrapU = texture.wrapU;
  16441. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16442. }
  16443. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16444. internalTexture._cachedWrapV = texture.wrapV;
  16445. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16446. }
  16447. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16448. }
  16449. return true;
  16450. };
  16451. /**
  16452. * Sets an array of texture to the webGL context
  16453. * @param channel defines the channel where the texture array must be set
  16454. * @param uniform defines the associated uniform location
  16455. * @param textures defines the array of textures to bind
  16456. */
  16457. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16458. if (channel < 0 || !uniform) {
  16459. return;
  16460. }
  16461. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16462. this._textureUnits = new Int32Array(textures.length);
  16463. }
  16464. for (var i = 0; i < textures.length; i++) {
  16465. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16466. }
  16467. this._gl.uniform1iv(uniform, this._textureUnits);
  16468. for (var index = 0; index < textures.length; index++) {
  16469. this._setTexture(this._textureUnits[index], textures[index], true);
  16470. }
  16471. };
  16472. /** @hidden */
  16473. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16474. var internalTexture = texture.getInternalTexture();
  16475. if (!internalTexture) {
  16476. return;
  16477. }
  16478. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16479. var value = texture.anisotropicFilteringLevel;
  16480. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  16481. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  16482. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  16483. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16484. }
  16485. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16486. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16487. internalTexture._cachedAnisotropicFilteringLevel = value;
  16488. }
  16489. };
  16490. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16491. this._bindTextureDirectly(target, texture, true, true);
  16492. this._gl.texParameterf(target, parameter, value);
  16493. };
  16494. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16495. if (texture) {
  16496. this._bindTextureDirectly(target, texture, true, true);
  16497. }
  16498. this._gl.texParameteri(target, parameter, value);
  16499. };
  16500. /**
  16501. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16502. * @param x defines the x coordinate of the rectangle where pixels must be read
  16503. * @param y defines the y coordinate of the rectangle where pixels must be read
  16504. * @param width defines the width of the rectangle where pixels must be read
  16505. * @param height defines the height of the rectangle where pixels must be read
  16506. * @returns a Uint8Array containing RGBA colors
  16507. */
  16508. Engine.prototype.readPixels = function (x, y, width, height) {
  16509. var data = new Uint8Array(height * width * 4);
  16510. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16511. return data;
  16512. };
  16513. /**
  16514. * Add an externaly attached data from its key.
  16515. * This method call will fail and return false, if such key already exists.
  16516. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16517. * @param key the unique key that identifies the data
  16518. * @param data the data object to associate to the key for this Engine instance
  16519. * @return true if no such key were already present and the data was added successfully, false otherwise
  16520. */
  16521. Engine.prototype.addExternalData = function (key, data) {
  16522. if (!this._externalData) {
  16523. this._externalData = new BABYLON.StringDictionary();
  16524. }
  16525. return this._externalData.add(key, data);
  16526. };
  16527. /**
  16528. * Get an externaly attached data from its key
  16529. * @param key the unique key that identifies the data
  16530. * @return the associated data, if present (can be null), or undefined if not present
  16531. */
  16532. Engine.prototype.getExternalData = function (key) {
  16533. if (!this._externalData) {
  16534. this._externalData = new BABYLON.StringDictionary();
  16535. }
  16536. return this._externalData.get(key);
  16537. };
  16538. /**
  16539. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16540. * @param key the unique key that identifies the data
  16541. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16542. * @return the associated data, can be null if the factory returned null.
  16543. */
  16544. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16545. if (!this._externalData) {
  16546. this._externalData = new BABYLON.StringDictionary();
  16547. }
  16548. return this._externalData.getOrAddWithFactory(key, factory);
  16549. };
  16550. /**
  16551. * Remove an externaly attached data from the Engine instance
  16552. * @param key the unique key that identifies the data
  16553. * @return true if the data was successfully removed, false if it doesn't exist
  16554. */
  16555. Engine.prototype.removeExternalData = function (key) {
  16556. if (!this._externalData) {
  16557. this._externalData = new BABYLON.StringDictionary();
  16558. }
  16559. return this._externalData.remove(key);
  16560. };
  16561. /**
  16562. * Unbind all vertex attributes from the webGL context
  16563. */
  16564. Engine.prototype.unbindAllAttributes = function () {
  16565. if (this._mustWipeVertexAttributes) {
  16566. this._mustWipeVertexAttributes = false;
  16567. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16568. this._gl.disableVertexAttribArray(i);
  16569. this._vertexAttribArraysEnabled[i] = false;
  16570. this._currentBufferPointers[i].active = false;
  16571. }
  16572. return;
  16573. }
  16574. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16575. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16576. continue;
  16577. }
  16578. this._gl.disableVertexAttribArray(i);
  16579. this._vertexAttribArraysEnabled[i] = false;
  16580. this._currentBufferPointers[i].active = false;
  16581. }
  16582. };
  16583. /**
  16584. * 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
  16585. */
  16586. Engine.prototype.releaseEffects = function () {
  16587. for (var name in this._compiledEffects) {
  16588. this._deleteProgram(this._compiledEffects[name]._program);
  16589. }
  16590. this._compiledEffects = {};
  16591. };
  16592. /**
  16593. * Dispose and release all associated resources
  16594. */
  16595. Engine.prototype.dispose = function () {
  16596. this.hideLoadingUI();
  16597. this.stopRenderLoop();
  16598. // Release postProcesses
  16599. while (this.postProcesses.length) {
  16600. this.postProcesses[0].dispose();
  16601. }
  16602. // Empty texture
  16603. if (this._emptyTexture) {
  16604. this._releaseTexture(this._emptyTexture);
  16605. this._emptyTexture = null;
  16606. }
  16607. if (this._emptyCubeTexture) {
  16608. this._releaseTexture(this._emptyCubeTexture);
  16609. this._emptyCubeTexture = null;
  16610. }
  16611. // Rescale PP
  16612. if (this._rescalePostProcess) {
  16613. this._rescalePostProcess.dispose();
  16614. }
  16615. // Release scenes
  16616. while (this.scenes.length) {
  16617. this.scenes[0].dispose();
  16618. }
  16619. // Release audio engine
  16620. if (Engine.audioEngine) {
  16621. Engine.audioEngine.dispose();
  16622. }
  16623. // Release effects
  16624. this.releaseEffects();
  16625. // Unbind
  16626. this.unbindAllAttributes();
  16627. this._boundUniforms = [];
  16628. if (this._dummyFramebuffer) {
  16629. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16630. }
  16631. //WebVR
  16632. this.disableVR();
  16633. // Events
  16634. if (BABYLON.Tools.IsWindowObjectExist()) {
  16635. window.removeEventListener("blur", this._onBlur);
  16636. window.removeEventListener("focus", this._onFocus);
  16637. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16638. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16639. if (this._renderingCanvas) {
  16640. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16641. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16642. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16643. if (!this._doNotHandleContextLost) {
  16644. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16645. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16646. }
  16647. }
  16648. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16649. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16650. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16651. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16652. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16653. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16654. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16655. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16656. if (this._onVrDisplayConnect) {
  16657. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16658. if (this._onVrDisplayDisconnect) {
  16659. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16660. }
  16661. if (this._onVrDisplayPresentChange) {
  16662. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16663. }
  16664. this._onVrDisplayConnect = null;
  16665. this._onVrDisplayDisconnect = null;
  16666. }
  16667. }
  16668. // Remove from Instances
  16669. var index = Engine.Instances.indexOf(this);
  16670. if (index >= 0) {
  16671. Engine.Instances.splice(index, 1);
  16672. }
  16673. this._workingCanvas = null;
  16674. this._workingContext = null;
  16675. this._currentBufferPointers = [];
  16676. this._renderingCanvas = null;
  16677. this._currentProgram = null;
  16678. this._bindedRenderFunction = null;
  16679. this.onResizeObservable.clear();
  16680. this.onCanvasBlurObservable.clear();
  16681. this.onCanvasFocusObservable.clear();
  16682. this.onCanvasPointerOutObservable.clear();
  16683. this.onBeginFrameObservable.clear();
  16684. this.onEndFrameObservable.clear();
  16685. BABYLON.Effect.ResetCache();
  16686. // Abort active requests
  16687. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16688. var request = _a[_i];
  16689. request.abort();
  16690. }
  16691. };
  16692. // Loading screen
  16693. /**
  16694. * Display the loading screen
  16695. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16696. */
  16697. Engine.prototype.displayLoadingUI = function () {
  16698. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16699. return;
  16700. }
  16701. var loadingScreen = this.loadingScreen;
  16702. if (loadingScreen) {
  16703. loadingScreen.displayLoadingUI();
  16704. }
  16705. };
  16706. /**
  16707. * Hide the loading screen
  16708. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16709. */
  16710. Engine.prototype.hideLoadingUI = function () {
  16711. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16712. return;
  16713. }
  16714. var loadingScreen = this.loadingScreen;
  16715. if (loadingScreen) {
  16716. loadingScreen.hideLoadingUI();
  16717. }
  16718. };
  16719. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16720. /**
  16721. * Gets the current loading screen object
  16722. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16723. */
  16724. get: function () {
  16725. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16726. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16727. return this._loadingScreen;
  16728. },
  16729. /**
  16730. * Sets the current loading screen object
  16731. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16732. */
  16733. set: function (loadingScreen) {
  16734. this._loadingScreen = loadingScreen;
  16735. },
  16736. enumerable: true,
  16737. configurable: true
  16738. });
  16739. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16740. /**
  16741. * Sets the current loading screen text
  16742. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16743. */
  16744. set: function (text) {
  16745. this.loadingScreen.loadingUIText = text;
  16746. },
  16747. enumerable: true,
  16748. configurable: true
  16749. });
  16750. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16751. /**
  16752. * Sets the current loading screen background color
  16753. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16754. */
  16755. set: function (color) {
  16756. this.loadingScreen.loadingUIBackgroundColor = color;
  16757. },
  16758. enumerable: true,
  16759. configurable: true
  16760. });
  16761. /**
  16762. * Attach a new callback raised when context lost event is fired
  16763. * @param callback defines the callback to call
  16764. */
  16765. Engine.prototype.attachContextLostEvent = function (callback) {
  16766. if (this._renderingCanvas) {
  16767. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16768. }
  16769. };
  16770. /**
  16771. * Attach a new callback raised when context restored event is fired
  16772. * @param callback defines the callback to call
  16773. */
  16774. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16775. if (this._renderingCanvas) {
  16776. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16777. }
  16778. };
  16779. /**
  16780. * Gets the source code of the vertex shader associated with a specific webGL program
  16781. * @param program defines the program to use
  16782. * @returns a string containing the source code of the vertex shader associated with the program
  16783. */
  16784. Engine.prototype.getVertexShaderSource = function (program) {
  16785. var shaders = this._gl.getAttachedShaders(program);
  16786. if (!shaders) {
  16787. return null;
  16788. }
  16789. return this._gl.getShaderSource(shaders[0]);
  16790. };
  16791. /**
  16792. * Gets the source code of the fragment shader associated with a specific webGL program
  16793. * @param program defines the program to use
  16794. * @returns a string containing the source code of the fragment shader associated with the program
  16795. */
  16796. Engine.prototype.getFragmentShaderSource = function (program) {
  16797. var shaders = this._gl.getAttachedShaders(program);
  16798. if (!shaders) {
  16799. return null;
  16800. }
  16801. return this._gl.getShaderSource(shaders[1]);
  16802. };
  16803. /**
  16804. * Get the current error code of the webGL context
  16805. * @returns the error code
  16806. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16807. */
  16808. Engine.prototype.getError = function () {
  16809. return this._gl.getError();
  16810. };
  16811. // FPS
  16812. /**
  16813. * Gets the current framerate
  16814. * @returns a number representing the framerate
  16815. */
  16816. Engine.prototype.getFps = function () {
  16817. return this._fps;
  16818. };
  16819. /**
  16820. * Gets the time spent between current and previous frame
  16821. * @returns a number representing the delta time in ms
  16822. */
  16823. Engine.prototype.getDeltaTime = function () {
  16824. return this._deltaTime;
  16825. };
  16826. Engine.prototype._measureFps = function () {
  16827. this._performanceMonitor.sampleFrame();
  16828. this._fps = this._performanceMonitor.averageFPS;
  16829. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16830. };
  16831. /** @hidden */
  16832. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  16833. if (faceIndex === void 0) { faceIndex = -1; }
  16834. if (level === void 0) { level = 0; }
  16835. var gl = this._gl;
  16836. if (!this._dummyFramebuffer) {
  16837. var dummy = gl.createFramebuffer();
  16838. if (!dummy) {
  16839. throw new Error("Unable to create dummy framebuffer");
  16840. }
  16841. this._dummyFramebuffer = dummy;
  16842. }
  16843. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16844. if (faceIndex > -1) {
  16845. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  16846. }
  16847. else {
  16848. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  16849. }
  16850. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16851. var buffer;
  16852. switch (readType) {
  16853. case gl.UNSIGNED_BYTE:
  16854. buffer = new Uint8Array(4 * width * height);
  16855. readType = gl.UNSIGNED_BYTE;
  16856. break;
  16857. default:
  16858. buffer = new Float32Array(4 * width * height);
  16859. readType = gl.FLOAT;
  16860. break;
  16861. }
  16862. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16863. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16864. return buffer;
  16865. };
  16866. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16867. if (this._webGLVersion > 1) {
  16868. return this._caps.colorBufferFloat;
  16869. }
  16870. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16871. };
  16872. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16873. if (this._webGLVersion > 1) {
  16874. return this._caps.colorBufferFloat;
  16875. }
  16876. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16877. };
  16878. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16879. Engine.prototype._canRenderToFramebuffer = function (type) {
  16880. var gl = this._gl;
  16881. //clear existing errors
  16882. while (gl.getError() !== gl.NO_ERROR) { }
  16883. var successful = true;
  16884. var texture = gl.createTexture();
  16885. gl.bindTexture(gl.TEXTURE_2D, texture);
  16886. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16887. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16888. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16889. var fb = gl.createFramebuffer();
  16890. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16891. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16892. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16893. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16894. successful = successful && (gl.getError() === gl.NO_ERROR);
  16895. //try render by clearing frame buffer's color buffer
  16896. if (successful) {
  16897. gl.clear(gl.COLOR_BUFFER_BIT);
  16898. successful = successful && (gl.getError() === gl.NO_ERROR);
  16899. }
  16900. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16901. if (successful) {
  16902. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16903. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16904. var readFormat = gl.RGBA;
  16905. var readType = gl.UNSIGNED_BYTE;
  16906. var buffer = new Uint8Array(4);
  16907. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16908. successful = successful && (gl.getError() === gl.NO_ERROR);
  16909. }
  16910. //clean up
  16911. gl.deleteTexture(texture);
  16912. gl.deleteFramebuffer(fb);
  16913. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16914. //clear accumulated errors
  16915. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16916. return successful;
  16917. };
  16918. /** @hidden */
  16919. Engine.prototype._getWebGLTextureType = function (type) {
  16920. if (this._webGLVersion === 1) {
  16921. switch (type) {
  16922. case Engine.TEXTURETYPE_FLOAT:
  16923. return this._gl.FLOAT;
  16924. case Engine.TEXTURETYPE_HALF_FLOAT:
  16925. return this._gl.HALF_FLOAT_OES;
  16926. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  16927. return this._gl.UNSIGNED_BYTE;
  16928. }
  16929. return this._gl.UNSIGNED_BYTE;
  16930. }
  16931. switch (type) {
  16932. case Engine.TEXTURETYPE_BYTE:
  16933. return this._gl.BYTE;
  16934. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  16935. return this._gl.UNSIGNED_BYTE;
  16936. case Engine.TEXTURETYPE_SHORT:
  16937. return this._gl.SHORT;
  16938. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  16939. return this._gl.UNSIGNED_SHORT;
  16940. case Engine.TEXTURETYPE_INT:
  16941. return this._gl.INT;
  16942. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  16943. return this._gl.UNSIGNED_INT;
  16944. case Engine.TEXTURETYPE_FLOAT:
  16945. return this._gl.FLOAT;
  16946. case Engine.TEXTURETYPE_HALF_FLOAT:
  16947. return this._gl.HALF_FLOAT;
  16948. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  16949. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  16950. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  16951. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  16952. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  16953. return this._gl.UNSIGNED_SHORT_5_6_5;
  16954. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  16955. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  16956. case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
  16957. return this._gl.UNSIGNED_INT_24_8;
  16958. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  16959. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  16960. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  16961. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  16962. case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  16963. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  16964. }
  16965. return this._gl.UNSIGNED_BYTE;
  16966. };
  16967. ;
  16968. Engine.prototype._getInternalFormat = function (format) {
  16969. var internalFormat = this._gl.RGBA;
  16970. switch (format) {
  16971. case Engine.TEXTUREFORMAT_ALPHA:
  16972. internalFormat = this._gl.ALPHA;
  16973. break;
  16974. case Engine.TEXTUREFORMAT_LUMINANCE:
  16975. internalFormat = this._gl.LUMINANCE;
  16976. break;
  16977. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16978. internalFormat = this._gl.LUMINANCE_ALPHA;
  16979. break;
  16980. case Engine.TEXTUREFORMAT_RED:
  16981. internalFormat = this._gl.RED;
  16982. break;
  16983. case Engine.TEXTUREFORMAT_RG:
  16984. internalFormat = this._gl.RG;
  16985. break;
  16986. case Engine.TEXTUREFORMAT_RGB:
  16987. internalFormat = this._gl.RGB;
  16988. break;
  16989. case Engine.TEXTUREFORMAT_RGBA:
  16990. internalFormat = this._gl.RGBA;
  16991. break;
  16992. }
  16993. if (this._webGLVersion > 1) {
  16994. switch (format) {
  16995. case Engine.TEXTUREFORMAT_RED_INTEGER:
  16996. internalFormat = this._gl.RED_INTEGER;
  16997. break;
  16998. case Engine.TEXTUREFORMAT_RG_INTEGER:
  16999. internalFormat = this._gl.RG_INTEGER;
  17000. break;
  17001. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17002. internalFormat = this._gl.RGB_INTEGER;
  17003. break;
  17004. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17005. internalFormat = this._gl.RGBA_INTEGER;
  17006. break;
  17007. }
  17008. }
  17009. return internalFormat;
  17010. };
  17011. /** @hidden */
  17012. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17013. if (this._webGLVersion === 1) {
  17014. if (format !== undefined) {
  17015. switch (format) {
  17016. case Engine.TEXTUREFORMAT_ALPHA:
  17017. return this._gl.ALPHA;
  17018. case Engine.TEXTUREFORMAT_LUMINANCE:
  17019. return this._gl.LUMINANCE;
  17020. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17021. return this._gl.LUMINANCE_ALPHA;
  17022. }
  17023. }
  17024. return this._gl.RGBA;
  17025. }
  17026. switch (type) {
  17027. case Engine.TEXTURETYPE_BYTE:
  17028. switch (format) {
  17029. case Engine.TEXTUREFORMAT_RED:
  17030. return this._gl.R8_SNORM;
  17031. case Engine.TEXTUREFORMAT_RG:
  17032. return this._gl.RG8_SNORM;
  17033. case Engine.TEXTUREFORMAT_RGB:
  17034. return this._gl.RGB8_SNORM;
  17035. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17036. return this._gl.R8I;
  17037. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17038. return this._gl.RG8I;
  17039. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17040. return this._gl.RGB8I;
  17041. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17042. return this._gl.RGBA8I;
  17043. default:
  17044. return this._gl.RGBA8_SNORM;
  17045. }
  17046. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17047. switch (format) {
  17048. case Engine.TEXTUREFORMAT_RED:
  17049. return this._gl.R8;
  17050. case Engine.TEXTUREFORMAT_RG:
  17051. return this._gl.RG8;
  17052. case Engine.TEXTUREFORMAT_RGB:
  17053. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  17054. case Engine.TEXTUREFORMAT_RGBA:
  17055. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  17056. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17057. return this._gl.R8UI;
  17058. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17059. return this._gl.RG8UI;
  17060. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17061. return this._gl.RGB8UI;
  17062. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17063. return this._gl.RGBA8UI;
  17064. default:
  17065. return this._gl.RGBA8;
  17066. }
  17067. case Engine.TEXTURETYPE_SHORT:
  17068. switch (format) {
  17069. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17070. return this._gl.R16I;
  17071. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17072. return this._gl.RG16I;
  17073. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17074. return this._gl.RGB16I;
  17075. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17076. return this._gl.RGBA16I;
  17077. default:
  17078. return this._gl.RGBA16I;
  17079. }
  17080. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17081. switch (format) {
  17082. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17083. return this._gl.R16UI;
  17084. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17085. return this._gl.RG16UI;
  17086. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17087. return this._gl.RGB16UI;
  17088. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17089. return this._gl.RGBA16UI;
  17090. default:
  17091. return this._gl.RGBA16UI;
  17092. }
  17093. case Engine.TEXTURETYPE_INT:
  17094. switch (format) {
  17095. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17096. return this._gl.R32I;
  17097. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17098. return this._gl.RG32I;
  17099. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17100. return this._gl.RGB32I;
  17101. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17102. return this._gl.RGBA32I;
  17103. default:
  17104. return this._gl.RGBA32I;
  17105. }
  17106. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17107. switch (format) {
  17108. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17109. return this._gl.R32UI;
  17110. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17111. return this._gl.RG32UI;
  17112. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17113. return this._gl.RGB32UI;
  17114. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17115. return this._gl.RGBA32UI;
  17116. default:
  17117. return this._gl.RGBA32UI;
  17118. }
  17119. case Engine.TEXTURETYPE_FLOAT:
  17120. switch (format) {
  17121. case Engine.TEXTUREFORMAT_RED:
  17122. return this._gl.R32F; // By default. Other possibility is R16F.
  17123. case Engine.TEXTUREFORMAT_RG:
  17124. return this._gl.RG32F; // By default. Other possibility is RG16F.
  17125. case Engine.TEXTUREFORMAT_RGB:
  17126. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  17127. case Engine.TEXTUREFORMAT_RGBA:
  17128. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  17129. default:
  17130. return this._gl.RGBA32F;
  17131. }
  17132. case Engine.TEXTURETYPE_HALF_FLOAT:
  17133. switch (format) {
  17134. case Engine.TEXTUREFORMAT_RED:
  17135. return this._gl.R16F;
  17136. case Engine.TEXTUREFORMAT_RG:
  17137. return this._gl.RG16F;
  17138. case Engine.TEXTUREFORMAT_RGB:
  17139. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  17140. case Engine.TEXTUREFORMAT_RGBA:
  17141. return this._gl.RGBA16F;
  17142. default:
  17143. return this._gl.RGBA16F;
  17144. }
  17145. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17146. return this._gl.RGB565;
  17147. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17148. return this._gl.R11F_G11F_B10F;
  17149. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17150. return this._gl.RGB9_E5;
  17151. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17152. return this._gl.RGBA4;
  17153. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17154. return this._gl.RGB5_A1;
  17155. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17156. switch (format) {
  17157. case Engine.TEXTUREFORMAT_RGBA:
  17158. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  17159. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17160. return this._gl.RGB10_A2UI;
  17161. default:
  17162. return this._gl.RGB10_A2;
  17163. }
  17164. }
  17165. return this._gl.RGBA8;
  17166. };
  17167. ;
  17168. /** @hidden */
  17169. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17170. if (type === Engine.TEXTURETYPE_FLOAT) {
  17171. return this._gl.RGBA32F;
  17172. }
  17173. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17174. return this._gl.RGBA16F;
  17175. }
  17176. return this._gl.RGBA8;
  17177. };
  17178. ;
  17179. /** @hidden */
  17180. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17181. var _this = this;
  17182. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17183. this._activeRequests.push(request);
  17184. request.onCompleteObservable.add(function (request) {
  17185. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17186. });
  17187. return request;
  17188. };
  17189. /** @hidden */
  17190. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17191. var _this = this;
  17192. return new Promise(function (resolve, reject) {
  17193. _this._loadFile(url, function (data) {
  17194. resolve(data);
  17195. }, undefined, database, useArrayBuffer, function (request, exception) {
  17196. reject(exception);
  17197. });
  17198. });
  17199. };
  17200. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17201. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17202. var onload = function (data) {
  17203. loadedFiles[index] = data;
  17204. loadedFiles._internalCount++;
  17205. if (loadedFiles._internalCount === 6) {
  17206. onfinish(loadedFiles);
  17207. }
  17208. };
  17209. var onerror = function (request, exception) {
  17210. if (onErrorCallBack && request) {
  17211. onErrorCallBack(request.status + " " + request.statusText, exception);
  17212. }
  17213. };
  17214. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17215. };
  17216. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17217. if (onError === void 0) { onError = null; }
  17218. var loadedFiles = [];
  17219. loadedFiles._internalCount = 0;
  17220. for (var index = 0; index < 6; index++) {
  17221. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17222. }
  17223. };
  17224. // Statics
  17225. /**
  17226. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17227. * @returns true if the engine can be created
  17228. * @ignorenaming
  17229. */
  17230. Engine.isSupported = function () {
  17231. try {
  17232. var tempcanvas = document.createElement("canvas");
  17233. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17234. return gl != null && !!window.WebGLRenderingContext;
  17235. }
  17236. catch (e) {
  17237. return false;
  17238. }
  17239. };
  17240. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17241. Engine.ExceptionList = [
  17242. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17243. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17244. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17245. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17246. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17247. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17248. ];
  17249. /** Gets the list of created engines */
  17250. Engine.Instances = new Array();
  17251. /**
  17252. * Hidden
  17253. */
  17254. Engine._TextureLoaders = [];
  17255. // Const statics
  17256. /** Defines that alpha blending is disabled */
  17257. Engine.ALPHA_DISABLE = 0;
  17258. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  17259. Engine.ALPHA_ADD = 1;
  17260. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  17261. Engine.ALPHA_COMBINE = 2;
  17262. /** Defines that alpha blending to DEST - SRC * DEST */
  17263. Engine.ALPHA_SUBTRACT = 3;
  17264. /** Defines that alpha blending to SRC * DEST */
  17265. Engine.ALPHA_MULTIPLY = 4;
  17266. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  17267. Engine.ALPHA_MAXIMIZED = 5;
  17268. /** Defines that alpha blending to SRC + DEST */
  17269. Engine.ALPHA_ONEONE = 6;
  17270. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  17271. Engine.ALPHA_PREMULTIPLIED = 7;
  17272. /**
  17273. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  17274. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  17275. */
  17276. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17277. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  17278. Engine.ALPHA_INTERPOLATE = 9;
  17279. /**
  17280. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  17281. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  17282. */
  17283. Engine.ALPHA_SCREENMODE = 10;
  17284. /** Defines that the ressource is not delayed*/
  17285. Engine.DELAYLOADSTATE_NONE = 0;
  17286. /** Defines that the ressource was successfully delay loaded */
  17287. Engine.DELAYLOADSTATE_LOADED = 1;
  17288. /** Defines that the ressource is currently delay loading */
  17289. Engine.DELAYLOADSTATE_LOADING = 2;
  17290. /** Defines that the ressource is delayed and has not started loading */
  17291. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  17292. // Depht or Stencil test Constants.
  17293. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  17294. Engine.NEVER = 0x0200;
  17295. /** 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 */
  17296. Engine.ALWAYS = 0x0207;
  17297. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  17298. Engine.LESS = 0x0201;
  17299. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  17300. Engine.EQUAL = 0x0202;
  17301. /** 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 */
  17302. Engine.LEQUAL = 0x0203;
  17303. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  17304. Engine.GREATER = 0x0204;
  17305. /** 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 */
  17306. Engine.GEQUAL = 0x0206;
  17307. /** 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 */
  17308. Engine.NOTEQUAL = 0x0205;
  17309. // Stencil Actions Constants.
  17310. /** Passed to stencilOperation to specify that stencil value must be kept */
  17311. Engine.KEEP = 0x1E00;
  17312. /** Passed to stencilOperation to specify that stencil value must be replaced */
  17313. Engine.REPLACE = 0x1E01;
  17314. /** Passed to stencilOperation to specify that stencil value must be incremented */
  17315. Engine.INCR = 0x1E02;
  17316. /** Passed to stencilOperation to specify that stencil value must be decremented */
  17317. Engine.DECR = 0x1E03;
  17318. /** Passed to stencilOperation to specify that stencil value must be inverted */
  17319. Engine.INVERT = 0x150A;
  17320. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  17321. Engine.INCR_WRAP = 0x8507;
  17322. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  17323. Engine.DECR_WRAP = 0x8508;
  17324. /** Texture is not repeating outside of 0..1 UVs */
  17325. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  17326. /** Texture is repeating outside of 0..1 UVs */
  17327. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  17328. /** Texture is repeating and mirrored */
  17329. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  17330. /** ALPHA */
  17331. Engine.TEXTUREFORMAT_ALPHA = 0;
  17332. /** LUMINANCE */
  17333. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  17334. /** LUMINANCE_ALPHA */
  17335. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17336. /** RGB */
  17337. Engine.TEXTUREFORMAT_RGB = 4;
  17338. /** RGBA */
  17339. Engine.TEXTUREFORMAT_RGBA = 5;
  17340. /** RED */
  17341. Engine.TEXTUREFORMAT_RED = 6;
  17342. /** RED (2nd reference) */
  17343. Engine.TEXTUREFORMAT_R = 6;
  17344. /** RG */
  17345. Engine.TEXTUREFORMAT_RG = 7;
  17346. /** RED_INTEGER */
  17347. Engine.TEXTUREFORMAT_RED_INTEGER = 8;
  17348. /** RED_INTEGER (2nd reference) */
  17349. Engine.TEXTUREFORMAT_R_INTEGER = 8;
  17350. /** RG_INTEGER */
  17351. Engine.TEXTUREFORMAT_RG_INTEGER = 9;
  17352. /** RGB_INTEGER */
  17353. Engine.TEXTUREFORMAT_RGB_INTEGER = 10;
  17354. /** RGBA_INTEGER */
  17355. Engine.TEXTUREFORMAT_RGBA_INTEGER = 11;
  17356. /** UNSIGNED_BYTE */
  17357. Engine.TEXTURETYPE_UNSIGNED_BYTE = 0;
  17358. /** UNSIGNED_BYTE (2nd reference) */
  17359. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  17360. /** FLOAT */
  17361. Engine.TEXTURETYPE_FLOAT = 1;
  17362. /** HALF_FLOAT */
  17363. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  17364. /** BYTE */
  17365. Engine.TEXTURETYPE_BYTE = 3;
  17366. /** SHORT */
  17367. Engine.TEXTURETYPE_SHORT = 4;
  17368. /** UNSIGNED_SHORT */
  17369. Engine.TEXTURETYPE_UNSIGNED_SHORT = 5;
  17370. /** INT */
  17371. Engine.TEXTURETYPE_INT = 6;
  17372. /** UNSIGNED_INT */
  17373. Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7;
  17374. /** UNSIGNED_SHORT_4_4_4_4 */
  17375. Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
  17376. /** UNSIGNED_SHORT_5_5_5_1 */
  17377. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
  17378. /** UNSIGNED_SHORT_5_6_5 */
  17379. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
  17380. /** UNSIGNED_INT_2_10_10_10_REV */
  17381. Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
  17382. /** UNSIGNED_INT_24_8 */
  17383. Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
  17384. /** UNSIGNED_INT_10F_11F_11F_REV */
  17385. Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
  17386. /** UNSIGNED_INT_5_9_9_9_REV */
  17387. Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
  17388. /** FLOAT_32_UNSIGNED_INT_24_8_REV */
  17389. Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
  17390. /** nearest is mag = nearest and min = nearest and mip = linear */
  17391. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  17392. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17393. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  17394. /** Trilinear is mag = linear and min = linear and mip = linear */
  17395. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  17396. /** nearest is mag = nearest and min = nearest and mip = linear */
  17397. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  17398. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17399. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  17400. /** Trilinear is mag = linear and min = linear and mip = linear */
  17401. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  17402. /** mag = nearest and min = nearest and mip = nearest */
  17403. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  17404. /** mag = nearest and min = linear and mip = nearest */
  17405. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  17406. /** mag = nearest and min = linear and mip = linear */
  17407. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  17408. /** mag = nearest and min = linear and mip = none */
  17409. Engine.TEXTURE_NEAREST_LINEAR = 7;
  17410. /** mag = nearest and min = nearest and mip = none */
  17411. Engine.TEXTURE_NEAREST_NEAREST = 8;
  17412. /** mag = linear and min = nearest and mip = nearest */
  17413. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  17414. /** mag = linear and min = nearest and mip = linear */
  17415. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  17416. /** mag = linear and min = linear and mip = none */
  17417. Engine.TEXTURE_LINEAR_LINEAR = 11;
  17418. /** mag = linear and min = nearest and mip = none */
  17419. Engine.TEXTURE_LINEAR_NEAREST = 12;
  17420. /** Explicit coordinates mode */
  17421. Engine.TEXTURE_EXPLICIT_MODE = 0;
  17422. /** Spherical coordinates mode */
  17423. Engine.TEXTURE_SPHERICAL_MODE = 1;
  17424. /** Planar coordinates mode */
  17425. Engine.TEXTURE_PLANAR_MODE = 2;
  17426. /** Cubic coordinates mode */
  17427. Engine.TEXTURE_CUBIC_MODE = 3;
  17428. /** Projection coordinates mode */
  17429. Engine.TEXTURE_PROJECTION_MODE = 4;
  17430. /** Skybox coordinates mode */
  17431. Engine.TEXTURE_SKYBOX_MODE = 5;
  17432. /** Inverse Cubic coordinates mode */
  17433. Engine.TEXTURE_INVCUBIC_MODE = 6;
  17434. /** Equirectangular coordinates mode */
  17435. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  17436. /** Equirectangular Fixed coordinates mode */
  17437. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  17438. /** Equirectangular Fixed Mirrored coordinates mode */
  17439. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  17440. // Texture rescaling mode
  17441. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  17442. Engine.SCALEMODE_FLOOR = 1;
  17443. /** Defines that texture rescaling will look for the nearest power of 2 size */
  17444. Engine.SCALEMODE_NEAREST = 2;
  17445. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  17446. Engine.SCALEMODE_CEILING = 3;
  17447. // Updatable statics so stick with vars here
  17448. /**
  17449. * Gets or sets the epsilon value used by collision engine
  17450. */
  17451. Engine.CollisionsEpsilon = 0.001;
  17452. /**
  17453. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17454. */
  17455. Engine.CodeRepository = "src/";
  17456. /**
  17457. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17458. */
  17459. Engine.ShadersRepository = "src/Shaders/";
  17460. return Engine;
  17461. }());
  17462. BABYLON.Engine = Engine;
  17463. })(BABYLON || (BABYLON = {}));
  17464. //# sourceMappingURL=babylon.engine.js.map
  17465. var BABYLON;
  17466. (function (BABYLON) {
  17467. /**
  17468. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17469. */
  17470. var Node = /** @class */ (function () {
  17471. /**
  17472. * Creates a new Node
  17473. * @param {string} name - the name and id to be given to this node
  17474. * @param {BABYLON.Scene} the scene this node will be added to
  17475. */
  17476. function Node(name, scene) {
  17477. if (scene === void 0) { scene = null; }
  17478. /**
  17479. * Gets or sets a string used to store user defined state for the node
  17480. */
  17481. this.state = "";
  17482. /**
  17483. * Gets or sets an object used to store user defined information for the node
  17484. */
  17485. this.metadata = null;
  17486. /**
  17487. * Gets or sets a boolean used to define if the node must be serialized
  17488. */
  17489. this.doNotSerialize = false;
  17490. /** @hidden */
  17491. this._isDisposed = false;
  17492. /**
  17493. * Gets a list of Animations associated with the node
  17494. */
  17495. this.animations = new Array();
  17496. this._ranges = {};
  17497. this._isEnabled = true;
  17498. this._isReady = true;
  17499. /** @hidden */
  17500. this._currentRenderId = -1;
  17501. this._parentRenderId = -1;
  17502. this._childRenderId = -1;
  17503. this._animationPropertiesOverride = null;
  17504. /**
  17505. * An event triggered when the mesh is disposed
  17506. */
  17507. this.onDisposeObservable = new BABYLON.Observable();
  17508. // Behaviors
  17509. this._behaviors = new Array();
  17510. this.name = name;
  17511. this.id = name;
  17512. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17513. this.uniqueId = this._scene.getUniqueId();
  17514. this._initCache();
  17515. }
  17516. /**
  17517. * Add a new node constructor
  17518. * @param type defines the type name of the node to construct
  17519. * @param constructorFunc defines the constructor function
  17520. */
  17521. Node.AddNodeConstructor = function (type, constructorFunc) {
  17522. this._NodeConstructors[type] = constructorFunc;
  17523. };
  17524. /**
  17525. * Returns a node constructor based on type name
  17526. * @param type defines the type name
  17527. * @param name defines the new node name
  17528. * @param scene defines the hosting scene
  17529. * @param options defines optional options to transmit to constructors
  17530. * @returns the new constructor or null
  17531. */
  17532. Node.Construct = function (type, name, scene, options) {
  17533. var constructorFunc = this._NodeConstructors[type];
  17534. if (!constructorFunc) {
  17535. return null;
  17536. }
  17537. return constructorFunc(name, scene, options);
  17538. };
  17539. /**
  17540. * Gets a boolean indicating if the node has been disposed
  17541. * @returns true if the node was disposed
  17542. */
  17543. Node.prototype.isDisposed = function () {
  17544. return this._isDisposed;
  17545. };
  17546. Object.defineProperty(Node.prototype, "parent", {
  17547. get: function () {
  17548. return this._parentNode;
  17549. },
  17550. /**
  17551. * Gets or sets the parent of the node
  17552. */
  17553. set: function (parent) {
  17554. if (this._parentNode === parent) {
  17555. return;
  17556. }
  17557. // Remove self from list of children of parent
  17558. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17559. var index = this._parentNode._children.indexOf(this);
  17560. if (index !== -1) {
  17561. this._parentNode._children.splice(index, 1);
  17562. }
  17563. }
  17564. // Store new parent
  17565. this._parentNode = parent;
  17566. // Add as child to new parent
  17567. if (this._parentNode) {
  17568. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17569. this._parentNode._children = new Array();
  17570. }
  17571. this._parentNode._children.push(this);
  17572. }
  17573. },
  17574. enumerable: true,
  17575. configurable: true
  17576. });
  17577. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17578. /**
  17579. * Gets or sets the animation properties override
  17580. */
  17581. get: function () {
  17582. if (!this._animationPropertiesOverride) {
  17583. return this._scene.animationPropertiesOverride;
  17584. }
  17585. return this._animationPropertiesOverride;
  17586. },
  17587. set: function (value) {
  17588. this._animationPropertiesOverride = value;
  17589. },
  17590. enumerable: true,
  17591. configurable: true
  17592. });
  17593. /**
  17594. * Gets a string idenfifying the name of the class
  17595. * @returns "Node" string
  17596. */
  17597. Node.prototype.getClassName = function () {
  17598. return "Node";
  17599. };
  17600. Object.defineProperty(Node.prototype, "onDispose", {
  17601. /**
  17602. * Sets a callback that will be raised when the node will be disposed
  17603. */
  17604. set: function (callback) {
  17605. if (this._onDisposeObserver) {
  17606. this.onDisposeObservable.remove(this._onDisposeObserver);
  17607. }
  17608. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17609. },
  17610. enumerable: true,
  17611. configurable: true
  17612. });
  17613. /**
  17614. * Gets the scene of the node
  17615. * @returns a {BABYLON.Scene}
  17616. */
  17617. Node.prototype.getScene = function () {
  17618. return this._scene;
  17619. };
  17620. /**
  17621. * Gets the engine of the node
  17622. * @returns a {BABYLON.Engine}
  17623. */
  17624. Node.prototype.getEngine = function () {
  17625. return this._scene.getEngine();
  17626. };
  17627. /**
  17628. * Attach a behavior to the node
  17629. * @see http://doc.babylonjs.com/features/behaviour
  17630. * @param behavior defines the behavior to attach
  17631. * @returns the current Node
  17632. */
  17633. Node.prototype.addBehavior = function (behavior) {
  17634. var _this = this;
  17635. var index = this._behaviors.indexOf(behavior);
  17636. if (index !== -1) {
  17637. return this;
  17638. }
  17639. behavior.init();
  17640. if (this._scene.isLoading) {
  17641. // We defer the attach when the scene will be loaded
  17642. this._scene.onDataLoadedObservable.addOnce(function () {
  17643. behavior.attach(_this);
  17644. });
  17645. }
  17646. else {
  17647. behavior.attach(this);
  17648. }
  17649. this._behaviors.push(behavior);
  17650. return this;
  17651. };
  17652. /**
  17653. * Remove an attached behavior
  17654. * @see http://doc.babylonjs.com/features/behaviour
  17655. * @param behavior defines the behavior to attach
  17656. * @returns the current Node
  17657. */
  17658. Node.prototype.removeBehavior = function (behavior) {
  17659. var index = this._behaviors.indexOf(behavior);
  17660. if (index === -1) {
  17661. return this;
  17662. }
  17663. this._behaviors[index].detach();
  17664. this._behaviors.splice(index, 1);
  17665. return this;
  17666. };
  17667. Object.defineProperty(Node.prototype, "behaviors", {
  17668. /**
  17669. * Gets the list of attached behaviors
  17670. * @see http://doc.babylonjs.com/features/behaviour
  17671. */
  17672. get: function () {
  17673. return this._behaviors;
  17674. },
  17675. enumerable: true,
  17676. configurable: true
  17677. });
  17678. /**
  17679. * Gets an attached behavior by name
  17680. * @param name defines the name of the behavior to look for
  17681. * @see http://doc.babylonjs.com/features/behaviour
  17682. * @returns null if behavior was not found else the requested behavior
  17683. */
  17684. Node.prototype.getBehaviorByName = function (name) {
  17685. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17686. var behavior = _a[_i];
  17687. if (behavior.name === name) {
  17688. return behavior;
  17689. }
  17690. }
  17691. return null;
  17692. };
  17693. /**
  17694. * Returns the world matrix of the node
  17695. * @returns a matrix containing the node's world matrix
  17696. */
  17697. Node.prototype.getWorldMatrix = function () {
  17698. return BABYLON.Matrix.Identity();
  17699. };
  17700. /** @hidden */
  17701. Node.prototype._getWorldMatrixDeterminant = function () {
  17702. return 1;
  17703. };
  17704. // override it in derived class if you add new variables to the cache
  17705. // and call the parent class method
  17706. /** @hidden */
  17707. Node.prototype._initCache = function () {
  17708. this._cache = {};
  17709. this._cache.parent = undefined;
  17710. };
  17711. /** @hidden */
  17712. Node.prototype.updateCache = function (force) {
  17713. if (!force && this.isSynchronized())
  17714. return;
  17715. this._cache.parent = this.parent;
  17716. this._updateCache();
  17717. };
  17718. // override it in derived class if you add new variables to the cache
  17719. // and call the parent class method if !ignoreParentClass
  17720. /** @hidden */
  17721. Node.prototype._updateCache = function (ignoreParentClass) {
  17722. };
  17723. // override it in derived class if you add new variables to the cache
  17724. /** @hidden */
  17725. Node.prototype._isSynchronized = function () {
  17726. return true;
  17727. };
  17728. /** @hidden */
  17729. Node.prototype._markSyncedWithParent = function () {
  17730. if (this.parent) {
  17731. this._parentRenderId = this.parent._childRenderId;
  17732. }
  17733. };
  17734. /** @hidden */
  17735. Node.prototype.isSynchronizedWithParent = function () {
  17736. if (!this.parent) {
  17737. return true;
  17738. }
  17739. if (this._parentRenderId !== this.parent._childRenderId) {
  17740. return false;
  17741. }
  17742. return this.parent.isSynchronized();
  17743. };
  17744. /** @hidden */
  17745. Node.prototype.isSynchronized = function (updateCache) {
  17746. var check = this.hasNewParent();
  17747. check = check || !this.isSynchronizedWithParent();
  17748. check = check || !this._isSynchronized();
  17749. if (updateCache)
  17750. this.updateCache(true);
  17751. return !check;
  17752. };
  17753. /** @hidden */
  17754. Node.prototype.hasNewParent = function (update) {
  17755. if (this._cache.parent === this.parent)
  17756. return false;
  17757. if (update)
  17758. this._cache.parent = this.parent;
  17759. return true;
  17760. };
  17761. /**
  17762. * Is this node ready to be used/rendered
  17763. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17764. * @return true if the node is ready
  17765. */
  17766. Node.prototype.isReady = function (completeCheck) {
  17767. if (completeCheck === void 0) { completeCheck = false; }
  17768. return this._isReady;
  17769. };
  17770. /**
  17771. * Is this node enabled?
  17772. * 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
  17773. * @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
  17774. * @return whether this node (and its parent) is enabled
  17775. */
  17776. Node.prototype.isEnabled = function (checkAncestors) {
  17777. if (checkAncestors === void 0) { checkAncestors = true; }
  17778. if (checkAncestors === false) {
  17779. return this._isEnabled;
  17780. }
  17781. if (this._isEnabled === false) {
  17782. return false;
  17783. }
  17784. if (this.parent !== undefined && this.parent !== null) {
  17785. return this.parent.isEnabled(checkAncestors);
  17786. }
  17787. return true;
  17788. };
  17789. /**
  17790. * Set the enabled state of this node
  17791. * @param value defines the new enabled state
  17792. */
  17793. Node.prototype.setEnabled = function (value) {
  17794. this._isEnabled = value;
  17795. };
  17796. /**
  17797. * Is this node a descendant of the given node?
  17798. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17799. * @param ancestor defines the parent node to inspect
  17800. * @returns a boolean indicating if this node is a descendant of the given node
  17801. */
  17802. Node.prototype.isDescendantOf = function (ancestor) {
  17803. if (this.parent) {
  17804. if (this.parent === ancestor) {
  17805. return true;
  17806. }
  17807. return this.parent.isDescendantOf(ancestor);
  17808. }
  17809. return false;
  17810. };
  17811. /** @hidden */
  17812. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17813. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17814. if (!this._children) {
  17815. return;
  17816. }
  17817. for (var index = 0; index < this._children.length; index++) {
  17818. var item = this._children[index];
  17819. if (!predicate || predicate(item)) {
  17820. results.push(item);
  17821. }
  17822. if (!directDescendantsOnly) {
  17823. item._getDescendants(results, false, predicate);
  17824. }
  17825. }
  17826. };
  17827. /**
  17828. * Will return all nodes that have this node as ascendant
  17829. * @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
  17830. * @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
  17831. * @return all children nodes of all types
  17832. */
  17833. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17834. var results = new Array();
  17835. this._getDescendants(results, directDescendantsOnly, predicate);
  17836. return results;
  17837. };
  17838. /**
  17839. * Get all child-meshes of this node
  17840. * @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
  17841. * @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
  17842. * @returns an array of {BABYLON.AbstractMesh}
  17843. */
  17844. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17845. var results = [];
  17846. this._getDescendants(results, directDescendantsOnly, function (node) {
  17847. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17848. });
  17849. return results;
  17850. };
  17851. /**
  17852. * Get all child-transformNodes of this node
  17853. * @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
  17854. * @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
  17855. * @returns an array of {BABYLON.TransformNode}
  17856. */
  17857. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17858. var results = [];
  17859. this._getDescendants(results, directDescendantsOnly, function (node) {
  17860. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17861. });
  17862. return results;
  17863. };
  17864. /**
  17865. * Get all direct children of this node
  17866. * @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
  17867. * @returns an array of {BABYLON.Node}
  17868. */
  17869. Node.prototype.getChildren = function (predicate) {
  17870. return this.getDescendants(true, predicate);
  17871. };
  17872. /** @hidden */
  17873. Node.prototype._setReady = function (state) {
  17874. if (state === this._isReady) {
  17875. return;
  17876. }
  17877. if (!state) {
  17878. this._isReady = false;
  17879. return;
  17880. }
  17881. if (this.onReady) {
  17882. this.onReady(this);
  17883. }
  17884. this._isReady = true;
  17885. };
  17886. /**
  17887. * Get an animation by name
  17888. * @param name defines the name of the animation to look for
  17889. * @returns null if not found else the requested animation
  17890. */
  17891. Node.prototype.getAnimationByName = function (name) {
  17892. for (var i = 0; i < this.animations.length; i++) {
  17893. var animation = this.animations[i];
  17894. if (animation.name === name) {
  17895. return animation;
  17896. }
  17897. }
  17898. return null;
  17899. };
  17900. /**
  17901. * Creates an animation range for this node
  17902. * @param name defines the name of the range
  17903. * @param from defines the starting key
  17904. * @param to defines the end key
  17905. */
  17906. Node.prototype.createAnimationRange = function (name, from, to) {
  17907. // check name not already in use
  17908. if (!this._ranges[name]) {
  17909. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17910. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17911. if (this.animations[i]) {
  17912. this.animations[i].createRange(name, from, to);
  17913. }
  17914. }
  17915. }
  17916. };
  17917. /**
  17918. * Delete a specific animation range
  17919. * @param name defines the name of the range to delete
  17920. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17921. */
  17922. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17923. if (deleteFrames === void 0) { deleteFrames = true; }
  17924. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17925. if (this.animations[i]) {
  17926. this.animations[i].deleteRange(name, deleteFrames);
  17927. }
  17928. }
  17929. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17930. };
  17931. /**
  17932. * Get an animation range by name
  17933. * @param name defines the name of the animation range to look for
  17934. * @returns null if not found else the requested animation range
  17935. */
  17936. Node.prototype.getAnimationRange = function (name) {
  17937. return this._ranges[name];
  17938. };
  17939. /**
  17940. * Will start the animation sequence
  17941. * @param name defines the range frames for animation sequence
  17942. * @param loop defines if the animation should loop (false by default)
  17943. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17944. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17945. * @returns the object created for this animation. If range does not exist, it will return null
  17946. */
  17947. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17948. var range = this.getAnimationRange(name);
  17949. if (!range) {
  17950. return null;
  17951. }
  17952. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17953. };
  17954. /**
  17955. * Serialize animation ranges into a JSON compatible object
  17956. * @returns serialization object
  17957. */
  17958. Node.prototype.serializeAnimationRanges = function () {
  17959. var serializationRanges = [];
  17960. for (var name in this._ranges) {
  17961. var localRange = this._ranges[name];
  17962. if (!localRange) {
  17963. continue;
  17964. }
  17965. var range = {};
  17966. range.name = name;
  17967. range.from = localRange.from;
  17968. range.to = localRange.to;
  17969. serializationRanges.push(range);
  17970. }
  17971. return serializationRanges;
  17972. };
  17973. /**
  17974. * Computes the world matrix of the node
  17975. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17976. * @returns the world matrix
  17977. */
  17978. Node.prototype.computeWorldMatrix = function (force) {
  17979. return BABYLON.Matrix.Identity();
  17980. };
  17981. /**
  17982. * Releases resources associated with this node.
  17983. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17984. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17985. */
  17986. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17987. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17988. if (!doNotRecurse) {
  17989. var nodes = this.getDescendants(true);
  17990. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17991. var node = nodes_1[_i];
  17992. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17993. }
  17994. }
  17995. else {
  17996. var transformNodes = this.getChildTransformNodes(true);
  17997. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17998. var transformNode = transformNodes_1[_a];
  17999. transformNode.parent = null;
  18000. transformNode.computeWorldMatrix(true);
  18001. }
  18002. }
  18003. this.parent = null;
  18004. // Callback
  18005. this.onDisposeObservable.notifyObservers(this);
  18006. this.onDisposeObservable.clear();
  18007. // Behaviors
  18008. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18009. var behavior = _c[_b];
  18010. behavior.detach();
  18011. }
  18012. this._behaviors = [];
  18013. this._isDisposed = true;
  18014. };
  18015. /**
  18016. * Parse animation range data from a serialization object and store them into a given node
  18017. * @param node defines where to store the animation ranges
  18018. * @param parsedNode defines the serialization object to read data from
  18019. * @param scene defines the hosting scene
  18020. */
  18021. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18022. if (parsedNode.ranges) {
  18023. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18024. var data = parsedNode.ranges[index];
  18025. node.createAnimationRange(data.name, data.from, data.to);
  18026. }
  18027. }
  18028. };
  18029. Node._NodeConstructors = {};
  18030. __decorate([
  18031. BABYLON.serialize()
  18032. ], Node.prototype, "name", void 0);
  18033. __decorate([
  18034. BABYLON.serialize()
  18035. ], Node.prototype, "id", void 0);
  18036. __decorate([
  18037. BABYLON.serialize()
  18038. ], Node.prototype, "uniqueId", void 0);
  18039. __decorate([
  18040. BABYLON.serialize()
  18041. ], Node.prototype, "state", void 0);
  18042. __decorate([
  18043. BABYLON.serialize()
  18044. ], Node.prototype, "metadata", void 0);
  18045. return Node;
  18046. }());
  18047. BABYLON.Node = Node;
  18048. })(BABYLON || (BABYLON = {}));
  18049. //# sourceMappingURL=babylon.node.js.map
  18050. var BABYLON;
  18051. (function (BABYLON) {
  18052. // This matrix is used as a value to reset the bounding box.
  18053. var _identityMatrix = BABYLON.Matrix.Identity();
  18054. var _tempRadiusVector = new BABYLON.Vector3(0, 0, 0);
  18055. var BoundingSphere = /** @class */ (function () {
  18056. /**
  18057. * Creates a new bounding sphere
  18058. * @param min defines the minimum vector (in local space)
  18059. * @param max defines the maximum vector (in local space)
  18060. */
  18061. function BoundingSphere(min, max) {
  18062. this.center = BABYLON.Vector3.Zero();
  18063. this.centerWorld = BABYLON.Vector3.Zero();
  18064. this.reConstruct(min, max);
  18065. }
  18066. /**
  18067. * Recreates the entire bounding sphere from scratch
  18068. * @param min defines the new minimum vector (in local space)
  18069. * @param max defines the new maximum vector (in local space)
  18070. */
  18071. BoundingSphere.prototype.reConstruct = function (min, max) {
  18072. this.minimum = min.clone();
  18073. this.maximum = max.clone();
  18074. var distance = BABYLON.Vector3.Distance(min, max);
  18075. BABYLON.Vector3.LerpToRef(min, max, 0.5, this.center);
  18076. this.radius = distance * 0.5;
  18077. this.centerWorld.set(0, 0, 0);
  18078. this._update(_identityMatrix);
  18079. };
  18080. /**
  18081. * Scale the current bounding sphere by applying a scale factor
  18082. * @param factor defines the scale factor to apply
  18083. * @returns the current bounding box
  18084. */
  18085. BoundingSphere.prototype.scale = function (factor) {
  18086. var newRadius = this.radius * factor;
  18087. _tempRadiusVector.set(newRadius, newRadius, newRadius);
  18088. var min = this.center.subtract(_tempRadiusVector);
  18089. var max = this.center.add(_tempRadiusVector);
  18090. this.reConstruct(min, max);
  18091. return this;
  18092. };
  18093. // Methods
  18094. /** @hidden */
  18095. BoundingSphere.prototype._update = function (world) {
  18096. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18097. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, _tempRadiusVector);
  18098. this.radiusWorld = Math.max(Math.abs(_tempRadiusVector.x), Math.abs(_tempRadiusVector.y), Math.abs(_tempRadiusVector.z)) * this.radius;
  18099. };
  18100. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18101. for (var i = 0; i < 6; i++) {
  18102. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18103. return false;
  18104. }
  18105. return true;
  18106. };
  18107. BoundingSphere.prototype.intersectsPoint = function (point) {
  18108. var x = this.centerWorld.x - point.x;
  18109. var y = this.centerWorld.y - point.y;
  18110. var z = this.centerWorld.z - point.z;
  18111. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18112. if (this.radiusWorld < distance)
  18113. return false;
  18114. return true;
  18115. };
  18116. // Statics
  18117. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18118. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18119. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18120. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18121. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18122. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18123. return false;
  18124. return true;
  18125. };
  18126. return BoundingSphere;
  18127. }());
  18128. BABYLON.BoundingSphere = BoundingSphere;
  18129. })(BABYLON || (BABYLON = {}));
  18130. //# sourceMappingURL=babylon.boundingSphere.js.map
  18131. var BABYLON;
  18132. (function (BABYLON) {
  18133. var BoundingBox = /** @class */ (function () {
  18134. /**
  18135. * Creates a new bounding box
  18136. * @param min defines the minimum vector (in local space)
  18137. * @param max defines the maximum vector (in local space)
  18138. */
  18139. function BoundingBox(min, max) {
  18140. this.vectorsWorld = new Array();
  18141. this.reConstruct(min, max);
  18142. }
  18143. // Methods
  18144. /**
  18145. * Recreates the entire bounding box from scratch
  18146. * @param min defines the new minimum vector (in local space)
  18147. * @param max defines the new maximum vector (in local space)
  18148. */
  18149. BoundingBox.prototype.reConstruct = function (min, max) {
  18150. this.minimum = min.clone();
  18151. this.maximum = max.clone();
  18152. // Bounding vectors
  18153. this.vectors = [
  18154. this.minimum.clone(),
  18155. this.maximum.clone(),
  18156. this.minimum.clone(),
  18157. this.minimum.clone(),
  18158. this.minimum.clone(),
  18159. this.maximum.clone(),
  18160. this.maximum.clone(),
  18161. this.maximum.clone()
  18162. ];
  18163. this.vectors[2].x = this.maximum.x;
  18164. this.vectors[3].y = this.maximum.y;
  18165. this.vectors[4].z = this.maximum.z;
  18166. this.vectors[5].z = this.minimum.z;
  18167. this.vectors[6].x = this.minimum.x;
  18168. this.vectors[7].y = this.minimum.y;
  18169. // OBB
  18170. this.center = this.maximum.add(this.minimum).scale(0.5);
  18171. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18172. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18173. // World
  18174. for (var index = 0; index < this.vectors.length; index++) {
  18175. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18176. }
  18177. this.minimumWorld = BABYLON.Vector3.Zero();
  18178. this.maximumWorld = BABYLON.Vector3.Zero();
  18179. this.centerWorld = BABYLON.Vector3.Zero();
  18180. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18181. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18182. };
  18183. /**
  18184. * Scale the current bounding box by applying a scale factor
  18185. * @param factor defines the scale factor to apply
  18186. * @returns the current bounding box
  18187. */
  18188. BoundingBox.prototype.scale = function (factor) {
  18189. var diff = this.maximum.subtract(this.minimum);
  18190. var distance = diff.length() * factor;
  18191. diff.normalize();
  18192. var newRadius = diff.scale(distance / 2);
  18193. var min = this.center.subtract(newRadius);
  18194. var max = this.center.add(newRadius);
  18195. this.reConstruct(min, max);
  18196. return this;
  18197. };
  18198. BoundingBox.prototype.getWorldMatrix = function () {
  18199. return this._worldMatrix;
  18200. };
  18201. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18202. this._worldMatrix.copyFrom(matrix);
  18203. return this;
  18204. };
  18205. /** @hidden */
  18206. BoundingBox.prototype._update = function (world) {
  18207. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18208. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18209. for (var index = 0; index < this.vectors.length; index++) {
  18210. var v = this.vectorsWorld[index];
  18211. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18212. if (v.x < this.minimumWorld.x)
  18213. this.minimumWorld.x = v.x;
  18214. if (v.y < this.minimumWorld.y)
  18215. this.minimumWorld.y = v.y;
  18216. if (v.z < this.minimumWorld.z)
  18217. this.minimumWorld.z = v.z;
  18218. if (v.x > this.maximumWorld.x)
  18219. this.maximumWorld.x = v.x;
  18220. if (v.y > this.maximumWorld.y)
  18221. this.maximumWorld.y = v.y;
  18222. if (v.z > this.maximumWorld.z)
  18223. this.maximumWorld.z = v.z;
  18224. }
  18225. // Extend
  18226. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18227. this.extendSizeWorld.scaleInPlace(0.5);
  18228. // OBB
  18229. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18230. this.centerWorld.scaleInPlace(0.5);
  18231. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18232. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18233. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18234. this._worldMatrix = world;
  18235. };
  18236. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18237. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18238. };
  18239. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18240. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18241. };
  18242. BoundingBox.prototype.intersectsPoint = function (point) {
  18243. var delta = -BABYLON.Epsilon;
  18244. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18245. return false;
  18246. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18247. return false;
  18248. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18249. return false;
  18250. return true;
  18251. };
  18252. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18253. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18254. };
  18255. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18256. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18257. return false;
  18258. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18259. return false;
  18260. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18261. return false;
  18262. return true;
  18263. };
  18264. // Statics
  18265. BoundingBox.Intersects = function (box0, box1) {
  18266. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18267. return false;
  18268. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18269. return false;
  18270. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18271. return false;
  18272. return true;
  18273. };
  18274. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18275. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18276. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18277. return (num <= (sphereRadius * sphereRadius));
  18278. };
  18279. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18280. for (var p = 0; p < 6; p++) {
  18281. for (var i = 0; i < 8; i++) {
  18282. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18283. return false;
  18284. }
  18285. }
  18286. }
  18287. return true;
  18288. };
  18289. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18290. for (var p = 0; p < 6; p++) {
  18291. var inCount = 8;
  18292. for (var i = 0; i < 8; i++) {
  18293. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18294. --inCount;
  18295. }
  18296. else {
  18297. break;
  18298. }
  18299. }
  18300. if (inCount === 0)
  18301. return false;
  18302. }
  18303. return true;
  18304. };
  18305. return BoundingBox;
  18306. }());
  18307. BABYLON.BoundingBox = BoundingBox;
  18308. })(BABYLON || (BABYLON = {}));
  18309. //# sourceMappingURL=babylon.boundingBox.js.map
  18310. var BABYLON;
  18311. (function (BABYLON) {
  18312. var computeBoxExtents = function (axis, box) {
  18313. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18314. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18315. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18316. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18317. var r = r0 + r1 + r2;
  18318. return {
  18319. min: p - r,
  18320. max: p + r
  18321. };
  18322. };
  18323. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18324. var axisOverlap = function (axis, box0, box1) {
  18325. var result0 = computeBoxExtents(axis, box0);
  18326. var result1 = computeBoxExtents(axis, box1);
  18327. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18328. };
  18329. var BoundingInfo = /** @class */ (function () {
  18330. function BoundingInfo(minimum, maximum) {
  18331. this.minimum = minimum;
  18332. this.maximum = maximum;
  18333. this._isLocked = false;
  18334. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18335. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18336. }
  18337. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18338. get: function () {
  18339. return this._isLocked;
  18340. },
  18341. set: function (value) {
  18342. this._isLocked = value;
  18343. },
  18344. enumerable: true,
  18345. configurable: true
  18346. });
  18347. // Methods
  18348. BoundingInfo.prototype.update = function (world) {
  18349. if (this._isLocked) {
  18350. return;
  18351. }
  18352. this.boundingBox._update(world);
  18353. this.boundingSphere._update(world);
  18354. };
  18355. /**
  18356. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18357. * @param center New center of the bounding info
  18358. * @param extend New extend of the bounding info
  18359. */
  18360. BoundingInfo.prototype.centerOn = function (center, extend) {
  18361. this.minimum = center.subtract(extend);
  18362. this.maximum = center.add(extend);
  18363. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18364. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18365. return this;
  18366. };
  18367. /**
  18368. * Scale the current bounding info by applying a scale factor
  18369. * @param factor defines the scale factor to apply
  18370. * @returns the current bounding info
  18371. */
  18372. BoundingInfo.prototype.scale = function (factor) {
  18373. this.boundingBox.scale(factor);
  18374. this.boundingSphere.scale(factor);
  18375. return this;
  18376. };
  18377. /**
  18378. * Returns `true` if the bounding info is within the frustum defined by the passed array of planes.
  18379. * @param frustumPlanes defines the frustum to test
  18380. * @param strategy defines the strategy to use for the culling (default is BABYLON.Scene.CULLINGSTRATEGY_STANDARD)
  18381. * @returns true if the bounding info is in the frustum planes
  18382. */
  18383. BoundingInfo.prototype.isInFrustum = function (frustumPlanes, strategy) {
  18384. if (strategy === void 0) { strategy = BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD; }
  18385. if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
  18386. return false;
  18387. }
  18388. if (strategy === BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY) {
  18389. return true;
  18390. }
  18391. return this.boundingBox.isInFrustum(frustumPlanes);
  18392. };
  18393. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18394. /**
  18395. * Gets the world distance between the min and max points of the bounding box
  18396. */
  18397. get: function () {
  18398. var boundingBox = this.boundingBox;
  18399. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18400. return size.length();
  18401. },
  18402. enumerable: true,
  18403. configurable: true
  18404. });
  18405. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18406. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18407. };
  18408. /** @hidden */
  18409. BoundingInfo.prototype._checkCollision = function (collider) {
  18410. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18411. };
  18412. BoundingInfo.prototype.intersectsPoint = function (point) {
  18413. if (!this.boundingSphere.centerWorld) {
  18414. return false;
  18415. }
  18416. if (!this.boundingSphere.intersectsPoint(point)) {
  18417. return false;
  18418. }
  18419. if (!this.boundingBox.intersectsPoint(point)) {
  18420. return false;
  18421. }
  18422. return true;
  18423. };
  18424. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18425. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18426. return false;
  18427. }
  18428. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18429. return false;
  18430. }
  18431. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18432. return false;
  18433. }
  18434. if (!precise) {
  18435. return true;
  18436. }
  18437. var box0 = this.boundingBox;
  18438. var box1 = boundingInfo.boundingBox;
  18439. if (!axisOverlap(box0.directions[0], box0, box1))
  18440. return false;
  18441. if (!axisOverlap(box0.directions[1], box0, box1))
  18442. return false;
  18443. if (!axisOverlap(box0.directions[2], box0, box1))
  18444. return false;
  18445. if (!axisOverlap(box1.directions[0], box0, box1))
  18446. return false;
  18447. if (!axisOverlap(box1.directions[1], box0, box1))
  18448. return false;
  18449. if (!axisOverlap(box1.directions[2], box0, box1))
  18450. return false;
  18451. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18452. return false;
  18453. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18454. return false;
  18455. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18456. return false;
  18457. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18458. return false;
  18459. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18460. return false;
  18461. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18462. return false;
  18463. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18464. return false;
  18465. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18466. return false;
  18467. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18468. return false;
  18469. return true;
  18470. };
  18471. return BoundingInfo;
  18472. }());
  18473. BABYLON.BoundingInfo = BoundingInfo;
  18474. })(BABYLON || (BABYLON = {}));
  18475. //# sourceMappingURL=babylon.boundingInfo.js.map
  18476. var BABYLON;
  18477. (function (BABYLON) {
  18478. var TransformNode = /** @class */ (function (_super) {
  18479. __extends(TransformNode, _super);
  18480. function TransformNode(name, scene, isPure) {
  18481. if (scene === void 0) { scene = null; }
  18482. if (isPure === void 0) { isPure = true; }
  18483. var _this = _super.call(this, name, scene) || this;
  18484. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18485. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18486. _this._up = new BABYLON.Vector3(0, 1, 0);
  18487. _this._right = new BABYLON.Vector3(1, 0, 0);
  18488. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18489. // Properties
  18490. _this._rotation = BABYLON.Vector3.Zero();
  18491. _this._scaling = BABYLON.Vector3.One();
  18492. _this._isDirty = false;
  18493. /**
  18494. * Set the billboard mode. Default is 0.
  18495. *
  18496. * | Value | Type | Description |
  18497. * | --- | --- | --- |
  18498. * | 0 | BILLBOARDMODE_NONE | |
  18499. * | 1 | BILLBOARDMODE_X | |
  18500. * | 2 | BILLBOARDMODE_Y | |
  18501. * | 4 | BILLBOARDMODE_Z | |
  18502. * | 7 | BILLBOARDMODE_ALL | |
  18503. *
  18504. */
  18505. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18506. _this.scalingDeterminant = 1;
  18507. _this.infiniteDistance = false;
  18508. /**
  18509. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18510. * By default the system will update normals to compensate
  18511. */
  18512. _this.ignoreNonUniformScaling = false;
  18513. _this.position = BABYLON.Vector3.Zero();
  18514. _this._localWorld = BABYLON.Matrix.Zero();
  18515. /** @hidden */
  18516. _this._worldMatrix = BABYLON.Matrix.Zero();
  18517. /** @hidden */
  18518. _this._worldMatrixDeterminant = 0;
  18519. _this._absolutePosition = BABYLON.Vector3.Zero();
  18520. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18521. _this._postMultiplyPivotMatrix = false;
  18522. _this._isWorldMatrixFrozen = false;
  18523. /**
  18524. * An event triggered after the world matrix is updated
  18525. */
  18526. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18527. _this._nonUniformScaling = false;
  18528. if (isPure) {
  18529. _this.getScene().addTransformNode(_this);
  18530. }
  18531. return _this;
  18532. }
  18533. /**
  18534. * Gets a string identifying the name of the class
  18535. * @returns "TransformNode" string
  18536. */
  18537. TransformNode.prototype.getClassName = function () {
  18538. return "TransformNode";
  18539. };
  18540. Object.defineProperty(TransformNode.prototype, "rotation", {
  18541. /**
  18542. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18543. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18544. * Default : (0.0, 0.0, 0.0)
  18545. */
  18546. get: function () {
  18547. return this._rotation;
  18548. },
  18549. set: function (newRotation) {
  18550. this._rotation = newRotation;
  18551. },
  18552. enumerable: true,
  18553. configurable: true
  18554. });
  18555. Object.defineProperty(TransformNode.prototype, "scaling", {
  18556. /**
  18557. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18558. * Default : (1.0, 1.0, 1.0)
  18559. */
  18560. get: function () {
  18561. return this._scaling;
  18562. },
  18563. /**
  18564. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18565. * Default : (1.0, 1.0, 1.0)
  18566. */
  18567. set: function (newScaling) {
  18568. this._scaling = newScaling;
  18569. },
  18570. enumerable: true,
  18571. configurable: true
  18572. });
  18573. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18574. /**
  18575. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18576. * It's null by default.
  18577. * 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)
  18578. */
  18579. get: function () {
  18580. return this._rotationQuaternion;
  18581. },
  18582. set: function (quaternion) {
  18583. this._rotationQuaternion = quaternion;
  18584. //reset the rotation vector.
  18585. if (quaternion && this.rotation.length()) {
  18586. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18587. }
  18588. },
  18589. enumerable: true,
  18590. configurable: true
  18591. });
  18592. Object.defineProperty(TransformNode.prototype, "forward", {
  18593. /**
  18594. * The forward direction of that transform in world space.
  18595. */
  18596. get: function () {
  18597. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18598. },
  18599. enumerable: true,
  18600. configurable: true
  18601. });
  18602. Object.defineProperty(TransformNode.prototype, "up", {
  18603. /**
  18604. * The up direction of that transform in world space.
  18605. */
  18606. get: function () {
  18607. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18608. },
  18609. enumerable: true,
  18610. configurable: true
  18611. });
  18612. Object.defineProperty(TransformNode.prototype, "right", {
  18613. /**
  18614. * The right direction of that transform in world space.
  18615. */
  18616. get: function () {
  18617. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18618. },
  18619. enumerable: true,
  18620. configurable: true
  18621. });
  18622. /**
  18623. * Returns the latest update of the World matrix
  18624. * Returns a Matrix.
  18625. */
  18626. TransformNode.prototype.getWorldMatrix = function () {
  18627. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18628. this.computeWorldMatrix();
  18629. }
  18630. return this._worldMatrix;
  18631. };
  18632. /** @hidden */
  18633. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18634. return this._worldMatrixDeterminant;
  18635. };
  18636. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18637. /**
  18638. * Returns directly the latest state of the mesh World matrix.
  18639. * A Matrix is returned.
  18640. */
  18641. get: function () {
  18642. return this._worldMatrix;
  18643. },
  18644. enumerable: true,
  18645. configurable: true
  18646. });
  18647. /**
  18648. * Copies the parameter passed Matrix into the mesh Pose matrix.
  18649. * Returns the TransformNode.
  18650. */
  18651. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18652. this._poseMatrix.copyFrom(matrix);
  18653. return this;
  18654. };
  18655. /**
  18656. * Returns the mesh Pose matrix.
  18657. * Returned object : Matrix
  18658. */
  18659. TransformNode.prototype.getPoseMatrix = function () {
  18660. return this._poseMatrix;
  18661. };
  18662. /** @hidden */
  18663. TransformNode.prototype._isSynchronized = function () {
  18664. if (this._isDirty) {
  18665. return false;
  18666. }
  18667. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18668. return false;
  18669. if (this._cache.pivotMatrixUpdated) {
  18670. return false;
  18671. }
  18672. if (this.infiniteDistance) {
  18673. return false;
  18674. }
  18675. if (!this._cache.position.equals(this.position))
  18676. return false;
  18677. if (this._rotationQuaternion) {
  18678. if (!this._cache.rotationQuaternion.equals(this._rotationQuaternion))
  18679. return false;
  18680. }
  18681. if (!this._cache.rotation.equals(this.rotation))
  18682. return false;
  18683. if (!this._cache.scaling.equals(this.scaling))
  18684. return false;
  18685. return true;
  18686. };
  18687. /** @hidden */
  18688. TransformNode.prototype._initCache = function () {
  18689. _super.prototype._initCache.call(this);
  18690. this._cache.localMatrixUpdated = false;
  18691. this._cache.position = BABYLON.Vector3.Zero();
  18692. this._cache.scaling = BABYLON.Vector3.Zero();
  18693. this._cache.rotation = BABYLON.Vector3.Zero();
  18694. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18695. this._cache.billboardMode = -1;
  18696. };
  18697. TransformNode.prototype.markAsDirty = function (property) {
  18698. if (property === "rotation") {
  18699. this.rotationQuaternion = null;
  18700. }
  18701. this._currentRenderId = Number.MAX_VALUE;
  18702. this._isDirty = true;
  18703. return this;
  18704. };
  18705. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18706. /**
  18707. * Returns the current mesh absolute position.
  18708. * Returns a Vector3.
  18709. */
  18710. get: function () {
  18711. return this._absolutePosition;
  18712. },
  18713. enumerable: true,
  18714. configurable: true
  18715. });
  18716. /**
  18717. * Sets a new matrix to apply before all other transformation
  18718. * @param matrix defines the transform matrix
  18719. * @returns the current TransformNode
  18720. */
  18721. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18722. return this.setPivotMatrix(matrix, false);
  18723. };
  18724. /**
  18725. * Sets a new pivot matrix to the current node
  18726. * @param matrix defines the new pivot matrix to use
  18727. * @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
  18728. * @returns the current TransformNode
  18729. */
  18730. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18731. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18732. this._pivotMatrix = matrix.clone();
  18733. this._cache.pivotMatrixUpdated = true;
  18734. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18735. if (this._postMultiplyPivotMatrix) {
  18736. if (!this._pivotMatrixInverse) {
  18737. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18738. }
  18739. else {
  18740. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18741. }
  18742. }
  18743. return this;
  18744. };
  18745. /**
  18746. * Returns the mesh pivot matrix.
  18747. * Default : Identity.
  18748. * A Matrix is returned.
  18749. */
  18750. TransformNode.prototype.getPivotMatrix = function () {
  18751. return this._pivotMatrix;
  18752. };
  18753. /**
  18754. * Prevents the World matrix to be computed any longer.
  18755. * Returns the TransformNode.
  18756. */
  18757. TransformNode.prototype.freezeWorldMatrix = function () {
  18758. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18759. this.computeWorldMatrix(true);
  18760. this._isWorldMatrixFrozen = true;
  18761. return this;
  18762. };
  18763. /**
  18764. * Allows back the World matrix computation.
  18765. * Returns the TransformNode.
  18766. */
  18767. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18768. this._isWorldMatrixFrozen = false;
  18769. this.computeWorldMatrix(true);
  18770. return this;
  18771. };
  18772. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18773. /**
  18774. * True if the World matrix has been frozen.
  18775. * Returns a boolean.
  18776. */
  18777. get: function () {
  18778. return this._isWorldMatrixFrozen;
  18779. },
  18780. enumerable: true,
  18781. configurable: true
  18782. });
  18783. /**
  18784. * Retuns the mesh absolute position in the World.
  18785. * Returns a Vector3.
  18786. */
  18787. TransformNode.prototype.getAbsolutePosition = function () {
  18788. this.computeWorldMatrix();
  18789. return this._absolutePosition;
  18790. };
  18791. /**
  18792. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18793. * Returns the TransformNode.
  18794. */
  18795. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18796. if (!absolutePosition) {
  18797. return this;
  18798. }
  18799. var absolutePositionX;
  18800. var absolutePositionY;
  18801. var absolutePositionZ;
  18802. if (absolutePosition.x === undefined) {
  18803. if (arguments.length < 3) {
  18804. return this;
  18805. }
  18806. absolutePositionX = arguments[0];
  18807. absolutePositionY = arguments[1];
  18808. absolutePositionZ = arguments[2];
  18809. }
  18810. else {
  18811. absolutePositionX = absolutePosition.x;
  18812. absolutePositionY = absolutePosition.y;
  18813. absolutePositionZ = absolutePosition.z;
  18814. }
  18815. if (this.parent) {
  18816. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18817. invertParentWorldMatrix.invert();
  18818. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18819. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18820. }
  18821. else {
  18822. this.position.x = absolutePositionX;
  18823. this.position.y = absolutePositionY;
  18824. this.position.z = absolutePositionZ;
  18825. }
  18826. return this;
  18827. };
  18828. /**
  18829. * Sets the mesh position in its local space.
  18830. * Returns the TransformNode.
  18831. */
  18832. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18833. this.computeWorldMatrix();
  18834. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18835. return this;
  18836. };
  18837. /**
  18838. * Returns the mesh position in the local space from the current World matrix values.
  18839. * Returns a new Vector3.
  18840. */
  18841. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18842. this.computeWorldMatrix();
  18843. var invLocalWorldMatrix = this._localWorld.clone();
  18844. invLocalWorldMatrix.invert();
  18845. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18846. };
  18847. /**
  18848. * Translates the mesh along the passed Vector3 in its local space.
  18849. * Returns the TransformNode.
  18850. */
  18851. TransformNode.prototype.locallyTranslate = function (vector3) {
  18852. this.computeWorldMatrix(true);
  18853. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18854. return this;
  18855. };
  18856. /**
  18857. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18858. * @param targetPoint the position (must be in same space as current mesh) to look at
  18859. * @param yawCor optional yaw (y-axis) correction in radians
  18860. * @param pitchCor optional pitch (x-axis) correction in radians
  18861. * @param rollCor optional roll (z-axis) correction in radians
  18862. * @param space the choosen space of the target
  18863. * @returns the TransformNode.
  18864. */
  18865. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18866. if (yawCor === void 0) { yawCor = 0; }
  18867. if (pitchCor === void 0) { pitchCor = 0; }
  18868. if (rollCor === void 0) { rollCor = 0; }
  18869. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18870. var dv = TransformNode._lookAtVectorCache;
  18871. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18872. targetPoint.subtractToRef(pos, dv);
  18873. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18874. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18875. var pitch = Math.atan2(dv.y, len);
  18876. if (this.rotationQuaternion) {
  18877. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18878. }
  18879. else {
  18880. this.rotation.x = pitch + pitchCor;
  18881. this.rotation.y = yaw + yawCor;
  18882. this.rotation.z = rollCor;
  18883. }
  18884. return this;
  18885. };
  18886. /**
  18887. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18888. * This Vector3 is expressed in the World space.
  18889. */
  18890. TransformNode.prototype.getDirection = function (localAxis) {
  18891. var result = BABYLON.Vector3.Zero();
  18892. this.getDirectionToRef(localAxis, result);
  18893. return result;
  18894. };
  18895. /**
  18896. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18897. * localAxis is expressed in the mesh local space.
  18898. * result is computed in the Wordl space from the mesh World matrix.
  18899. * Returns the TransformNode.
  18900. */
  18901. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18902. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18903. return this;
  18904. };
  18905. /**
  18906. * Sets a new pivot point to the current node
  18907. * @param point defines the new pivot point to use
  18908. * @param space defines if the point is in world or local space (local by default)
  18909. * @returns the current TransformNode
  18910. */
  18911. TransformNode.prototype.setPivotPoint = function (point, space) {
  18912. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18913. if (this.getScene().getRenderId() == 0) {
  18914. this.computeWorldMatrix(true);
  18915. }
  18916. var wm = this.getWorldMatrix();
  18917. if (space == BABYLON.Space.WORLD) {
  18918. var tmat = BABYLON.Tmp.Matrix[0];
  18919. wm.invertToRef(tmat);
  18920. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18921. }
  18922. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18923. };
  18924. /**
  18925. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18926. */
  18927. TransformNode.prototype.getPivotPoint = function () {
  18928. var point = BABYLON.Vector3.Zero();
  18929. this.getPivotPointToRef(point);
  18930. return point;
  18931. };
  18932. /**
  18933. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18934. * Returns the TransformNode.
  18935. */
  18936. TransformNode.prototype.getPivotPointToRef = function (result) {
  18937. result.x = -this._pivotMatrix.m[12];
  18938. result.y = -this._pivotMatrix.m[13];
  18939. result.z = -this._pivotMatrix.m[14];
  18940. return this;
  18941. };
  18942. /**
  18943. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18944. */
  18945. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18946. var point = BABYLON.Vector3.Zero();
  18947. this.getAbsolutePivotPointToRef(point);
  18948. return point;
  18949. };
  18950. /**
  18951. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18952. * Returns the TransformNode.
  18953. */
  18954. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18955. result.x = this._pivotMatrix.m[12];
  18956. result.y = this._pivotMatrix.m[13];
  18957. result.z = this._pivotMatrix.m[14];
  18958. this.getPivotPointToRef(result);
  18959. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18960. return this;
  18961. };
  18962. /**
  18963. * Defines the passed node as the parent of the current node.
  18964. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18965. * Returns the TransformNode.
  18966. */
  18967. TransformNode.prototype.setParent = function (node) {
  18968. if (!node && !this.parent) {
  18969. return this;
  18970. }
  18971. if (!node) {
  18972. var rotation = BABYLON.Tmp.Quaternion[0];
  18973. var position = BABYLON.Tmp.Vector3[0];
  18974. var scale = BABYLON.Tmp.Vector3[1];
  18975. if (this.parent && this.parent.computeWorldMatrix) {
  18976. this.parent.computeWorldMatrix(true);
  18977. }
  18978. this.computeWorldMatrix(true);
  18979. this.getWorldMatrix().decompose(scale, rotation, position);
  18980. if (this.rotationQuaternion) {
  18981. this.rotationQuaternion.copyFrom(rotation);
  18982. }
  18983. else {
  18984. rotation.toEulerAnglesToRef(this.rotation);
  18985. }
  18986. this.scaling.x = scale.x;
  18987. this.scaling.y = scale.y;
  18988. this.scaling.z = scale.z;
  18989. this.position.x = position.x;
  18990. this.position.y = position.y;
  18991. this.position.z = position.z;
  18992. }
  18993. else {
  18994. var rotation = BABYLON.Tmp.Quaternion[0];
  18995. var position = BABYLON.Tmp.Vector3[0];
  18996. var scale = BABYLON.Tmp.Vector3[1];
  18997. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18998. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18999. this.computeWorldMatrix(true);
  19000. node.computeWorldMatrix(true);
  19001. node.getWorldMatrix().invertToRef(invParentMatrix);
  19002. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  19003. diffMatrix.decompose(scale, rotation, position);
  19004. if (this.rotationQuaternion) {
  19005. this.rotationQuaternion.copyFrom(rotation);
  19006. }
  19007. else {
  19008. rotation.toEulerAnglesToRef(this.rotation);
  19009. }
  19010. this.position.x = position.x;
  19011. this.position.y = position.y;
  19012. this.position.z = position.z;
  19013. this.scaling.x = scale.x;
  19014. this.scaling.y = scale.y;
  19015. this.scaling.z = scale.z;
  19016. }
  19017. this.parent = node;
  19018. return this;
  19019. };
  19020. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19021. get: function () {
  19022. return this._nonUniformScaling;
  19023. },
  19024. enumerable: true,
  19025. configurable: true
  19026. });
  19027. /** @hidden */
  19028. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19029. if (this._nonUniformScaling === value) {
  19030. return false;
  19031. }
  19032. this._nonUniformScaling = value;
  19033. return true;
  19034. };
  19035. /**
  19036. * Attach the current TransformNode to another TransformNode associated with a bone
  19037. * @param bone Bone affecting the TransformNode
  19038. * @param affectedTransformNode TransformNode associated with the bone
  19039. */
  19040. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19041. this._transformToBoneReferal = affectedTransformNode;
  19042. this.parent = bone;
  19043. if (bone.getWorldMatrix().determinant() < 0) {
  19044. this.scalingDeterminant *= -1;
  19045. }
  19046. return this;
  19047. };
  19048. TransformNode.prototype.detachFromBone = function () {
  19049. if (!this.parent) {
  19050. return this;
  19051. }
  19052. if (this.parent.getWorldMatrix().determinant() < 0) {
  19053. this.scalingDeterminant *= -1;
  19054. }
  19055. this._transformToBoneReferal = null;
  19056. this.parent = null;
  19057. return this;
  19058. };
  19059. /**
  19060. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19061. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19062. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19063. * The passed axis is also normalized.
  19064. * Returns the TransformNode.
  19065. */
  19066. TransformNode.prototype.rotate = function (axis, amount, space) {
  19067. axis.normalize();
  19068. if (!this.rotationQuaternion) {
  19069. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19070. this.rotation = BABYLON.Vector3.Zero();
  19071. }
  19072. var rotationQuaternion;
  19073. if (!space || space === BABYLON.Space.LOCAL) {
  19074. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19075. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19076. }
  19077. else {
  19078. if (this.parent) {
  19079. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19080. invertParentWorldMatrix.invert();
  19081. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19082. }
  19083. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19084. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19085. }
  19086. return this;
  19087. };
  19088. /**
  19089. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19090. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19091. * The passed axis is also normalized.
  19092. * Returns the TransformNode.
  19093. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19094. */
  19095. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19096. axis.normalize();
  19097. if (!this.rotationQuaternion) {
  19098. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19099. this.rotation.copyFromFloats(0, 0, 0);
  19100. }
  19101. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19102. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19103. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19104. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19105. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19106. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19107. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19108. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19109. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19110. return this;
  19111. };
  19112. /**
  19113. * Translates the mesh along the axis vector for the passed distance in the given space.
  19114. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19115. * Returns the TransformNode.
  19116. */
  19117. TransformNode.prototype.translate = function (axis, distance, space) {
  19118. var displacementVector = axis.scale(distance);
  19119. if (!space || space === BABYLON.Space.LOCAL) {
  19120. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19121. this.setPositionWithLocalVector(tempV3);
  19122. }
  19123. else {
  19124. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19125. }
  19126. return this;
  19127. };
  19128. /**
  19129. * Adds a rotation step to the mesh current rotation.
  19130. * x, y, z are Euler angles expressed in radians.
  19131. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19132. * This means this rotation is made in the mesh local space only.
  19133. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19134. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19135. * ```javascript
  19136. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19137. * ```
  19138. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19139. * 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.
  19140. * Returns the TransformNode.
  19141. */
  19142. TransformNode.prototype.addRotation = function (x, y, z) {
  19143. var rotationQuaternion;
  19144. if (this.rotationQuaternion) {
  19145. rotationQuaternion = this.rotationQuaternion;
  19146. }
  19147. else {
  19148. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19149. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19150. }
  19151. var accumulation = BABYLON.Tmp.Quaternion[0];
  19152. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19153. rotationQuaternion.multiplyInPlace(accumulation);
  19154. if (!this.rotationQuaternion) {
  19155. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19156. }
  19157. return this;
  19158. };
  19159. /**
  19160. * Computes the mesh World matrix and returns it.
  19161. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19162. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19163. * If the parameter `force`is set to `true`, the actual computation is done.
  19164. * Returns the mesh World Matrix.
  19165. */
  19166. TransformNode.prototype.computeWorldMatrix = function (force) {
  19167. if (this._isWorldMatrixFrozen) {
  19168. return this._worldMatrix;
  19169. }
  19170. if (!force && this.isSynchronized(true)) {
  19171. this._currentRenderId = this.getScene().getRenderId();
  19172. return this._worldMatrix;
  19173. }
  19174. this._cache.position.copyFrom(this.position);
  19175. this._cache.scaling.copyFrom(this.scaling);
  19176. this._cache.pivotMatrixUpdated = false;
  19177. this._cache.billboardMode = this.billboardMode;
  19178. this._currentRenderId = this.getScene().getRenderId();
  19179. this._childRenderId = this.getScene().getRenderId();
  19180. this._isDirty = false;
  19181. // Scaling
  19182. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19183. // Rotation
  19184. //rotate, if quaternion is set and rotation was used
  19185. if (this.rotationQuaternion) {
  19186. var len = this.rotation.length();
  19187. if (len) {
  19188. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19189. this.rotation.copyFromFloats(0, 0, 0);
  19190. }
  19191. }
  19192. if (this.rotationQuaternion) {
  19193. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19194. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19195. }
  19196. else {
  19197. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19198. this._cache.rotation.copyFrom(this.rotation);
  19199. }
  19200. // Translation
  19201. var camera = this.getScene().activeCamera;
  19202. if (this.infiniteDistance && !this.parent && camera) {
  19203. var cameraWorldMatrix = camera.getWorldMatrix();
  19204. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19205. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19206. }
  19207. else {
  19208. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19209. }
  19210. // Composing transformations
  19211. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19212. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19213. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19214. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19215. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19216. // Need to decompose each rotation here
  19217. var currentPosition = BABYLON.Tmp.Vector3[3];
  19218. if (this.parent && this.parent.getWorldMatrix) {
  19219. if (this._transformToBoneReferal) {
  19220. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19221. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19222. }
  19223. else {
  19224. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19225. }
  19226. }
  19227. else {
  19228. currentPosition.copyFrom(this.position);
  19229. }
  19230. currentPosition.subtractInPlace(camera.globalPosition);
  19231. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19232. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19233. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19234. }
  19235. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19236. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19237. }
  19238. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19239. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19240. }
  19241. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19242. }
  19243. else {
  19244. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19245. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19246. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19247. }
  19248. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19249. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19250. }
  19251. // Post multiply inverse of pivotMatrix
  19252. if (this._postMultiplyPivotMatrix) {
  19253. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  19254. }
  19255. // Local world
  19256. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19257. // Parent
  19258. if (this.parent && this.parent.getWorldMatrix) {
  19259. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19260. if (this._transformToBoneReferal) {
  19261. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19262. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19263. }
  19264. else {
  19265. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19266. }
  19267. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19268. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19269. this._worldMatrix.copyFrom(this._localWorld);
  19270. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19271. }
  19272. else {
  19273. if (this._transformToBoneReferal) {
  19274. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19275. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19276. }
  19277. else {
  19278. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19279. }
  19280. }
  19281. this._markSyncedWithParent();
  19282. }
  19283. else {
  19284. this._worldMatrix.copyFrom(this._localWorld);
  19285. }
  19286. // Normal matrix
  19287. if (!this.ignoreNonUniformScaling) {
  19288. if (this.scaling.isNonUniform) {
  19289. this._updateNonUniformScalingState(true);
  19290. }
  19291. else if (this.parent && this.parent._nonUniformScaling) {
  19292. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19293. }
  19294. else {
  19295. this._updateNonUniformScalingState(false);
  19296. }
  19297. }
  19298. else {
  19299. this._updateNonUniformScalingState(false);
  19300. }
  19301. this._afterComputeWorldMatrix();
  19302. // Absolute position
  19303. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19304. // Callbacks
  19305. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19306. if (!this._poseMatrix) {
  19307. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19308. }
  19309. // Cache the determinant
  19310. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19311. return this._worldMatrix;
  19312. };
  19313. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19314. };
  19315. /**
  19316. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19317. * @param func: callback function to add
  19318. *
  19319. * Returns the TransformNode.
  19320. */
  19321. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19322. this.onAfterWorldMatrixUpdateObservable.add(func);
  19323. return this;
  19324. };
  19325. /**
  19326. * Removes a registered callback function.
  19327. * Returns the TransformNode.
  19328. */
  19329. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19330. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19331. return this;
  19332. };
  19333. /**
  19334. * Clone the current transform node
  19335. * Returns the new transform node
  19336. * @param name Name of the new clone
  19337. * @param newParent New parent for the clone
  19338. * @param doNotCloneChildren Do not clone children hierarchy
  19339. */
  19340. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19341. var _this = this;
  19342. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19343. result.name = name;
  19344. result.id = name;
  19345. if (newParent) {
  19346. result.parent = newParent;
  19347. }
  19348. if (!doNotCloneChildren) {
  19349. // Children
  19350. var directDescendants = this.getDescendants(true);
  19351. for (var index = 0; index < directDescendants.length; index++) {
  19352. var child = directDescendants[index];
  19353. if (child.clone) {
  19354. child.clone(name + "." + child.name, result);
  19355. }
  19356. }
  19357. }
  19358. return result;
  19359. };
  19360. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19361. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19362. serializationObject.type = this.getClassName();
  19363. // Parent
  19364. if (this.parent) {
  19365. serializationObject.parentId = this.parent.id;
  19366. }
  19367. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19368. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19369. }
  19370. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19371. serializationObject.isEnabled = this.isEnabled();
  19372. // Parent
  19373. if (this.parent) {
  19374. serializationObject.parentId = this.parent.id;
  19375. }
  19376. return serializationObject;
  19377. };
  19378. // Statics
  19379. /**
  19380. * Returns a new TransformNode object parsed from the source provided.
  19381. * The parameter `parsedMesh` is the source.
  19382. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19383. */
  19384. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19385. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19386. if (BABYLON.Tags) {
  19387. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19388. }
  19389. if (parsedTransformNode.localMatrix) {
  19390. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19391. }
  19392. else if (parsedTransformNode.pivotMatrix) {
  19393. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19394. }
  19395. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19396. // Parent
  19397. if (parsedTransformNode.parentId) {
  19398. transformNode._waitingParentId = parsedTransformNode.parentId;
  19399. }
  19400. return transformNode;
  19401. };
  19402. /**
  19403. * Releases resources associated with this transform node.
  19404. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19405. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19406. */
  19407. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19408. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19409. // Animations
  19410. this.getScene().stopAnimation(this);
  19411. // Remove from scene
  19412. this.getScene().removeTransformNode(this);
  19413. this.onAfterWorldMatrixUpdateObservable.clear();
  19414. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19415. };
  19416. // Statics
  19417. TransformNode.BILLBOARDMODE_NONE = 0;
  19418. TransformNode.BILLBOARDMODE_X = 1;
  19419. TransformNode.BILLBOARDMODE_Y = 2;
  19420. TransformNode.BILLBOARDMODE_Z = 4;
  19421. TransformNode.BILLBOARDMODE_ALL = 7;
  19422. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19423. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19424. __decorate([
  19425. BABYLON.serializeAsVector3()
  19426. ], TransformNode.prototype, "_rotation", void 0);
  19427. __decorate([
  19428. BABYLON.serializeAsQuaternion()
  19429. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19430. __decorate([
  19431. BABYLON.serializeAsVector3()
  19432. ], TransformNode.prototype, "_scaling", void 0);
  19433. __decorate([
  19434. BABYLON.serialize()
  19435. ], TransformNode.prototype, "billboardMode", void 0);
  19436. __decorate([
  19437. BABYLON.serialize()
  19438. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19439. __decorate([
  19440. BABYLON.serialize()
  19441. ], TransformNode.prototype, "infiniteDistance", void 0);
  19442. __decorate([
  19443. BABYLON.serialize()
  19444. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19445. __decorate([
  19446. BABYLON.serializeAsVector3()
  19447. ], TransformNode.prototype, "position", void 0);
  19448. return TransformNode;
  19449. }(BABYLON.Node));
  19450. BABYLON.TransformNode = TransformNode;
  19451. })(BABYLON || (BABYLON = {}));
  19452. //# sourceMappingURL=babylon.transformNode.js.map
  19453. var BABYLON;
  19454. (function (BABYLON) {
  19455. /**
  19456. * Class used to store all common mesh properties
  19457. */
  19458. var AbstractMesh = /** @class */ (function (_super) {
  19459. __extends(AbstractMesh, _super);
  19460. // Constructor
  19461. /**
  19462. * Creates a new AbstractMesh
  19463. * @param name defines the name of the mesh
  19464. * @param scene defines the hosting scene
  19465. */
  19466. function AbstractMesh(name, scene) {
  19467. if (scene === void 0) { scene = null; }
  19468. var _this = _super.call(this, name, scene, false) || this;
  19469. _this._facetNb = 0; // facet number
  19470. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19471. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19472. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19473. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19474. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19475. _this._subDiv = {
  19476. max: 1,
  19477. X: 1,
  19478. Y: 1,
  19479. Z: 1
  19480. };
  19481. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19482. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19483. /** Gets ot sets the culling strategy to use to find visible meshes */
  19484. _this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_STANDARD;
  19485. // Events
  19486. /**
  19487. * An event triggered when this mesh collides with another one
  19488. */
  19489. _this.onCollideObservable = new BABYLON.Observable();
  19490. /**
  19491. * An event triggered when the collision's position changes
  19492. */
  19493. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19494. /**
  19495. * An event triggered when material is changed
  19496. */
  19497. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19498. // Properties
  19499. /**
  19500. * Gets or sets the orientation for POV movement & rotation
  19501. */
  19502. _this.definedFacingForward = true;
  19503. /**
  19504. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19505. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19506. * * 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.
  19507. * @see http://doc.babylonjs.com/features/occlusionquery
  19508. */
  19509. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19510. /**
  19511. * 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:
  19512. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19513. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19514. * * 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.
  19515. * @see http://doc.babylonjs.com/features/occlusionquery
  19516. */
  19517. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19518. /**
  19519. * 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.
  19520. * The default value is -1 which means don't break the query and wait till the result
  19521. * @see http://doc.babylonjs.com/features/occlusionquery
  19522. */
  19523. _this.occlusionRetryCount = -1;
  19524. /** @hidden */
  19525. _this._occlusionInternalRetryCounter = 0;
  19526. /** @hidden */
  19527. _this._isOccluded = false;
  19528. /** @hidden */
  19529. _this._isOcclusionQueryInProgress = false;
  19530. _this._visibility = 1.0;
  19531. /** Gets or sets the alpha index used to sort transparent meshes
  19532. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19533. */
  19534. _this.alphaIndex = Number.MAX_VALUE;
  19535. /**
  19536. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19537. */
  19538. _this.isVisible = true;
  19539. /**
  19540. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19541. */
  19542. _this.isPickable = true;
  19543. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19544. _this.showSubMeshesBoundingBox = false;
  19545. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19546. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19547. */
  19548. _this.isBlocker = false;
  19549. /**
  19550. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19551. */
  19552. _this.enablePointerMoveEvents = false;
  19553. /**
  19554. * Specifies the rendering group id for this mesh (0 by default)
  19555. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19556. */
  19557. _this.renderingGroupId = 0;
  19558. _this._receiveShadows = false;
  19559. /**
  19560. * Gets or sets a boolean indicating if the outline must be rendered as well
  19561. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19562. */
  19563. _this.renderOutline = false;
  19564. /** Defines color to use when rendering outline */
  19565. _this.outlineColor = BABYLON.Color3.Red();
  19566. /** Define width to use when rendering outline */
  19567. _this.outlineWidth = 0.02;
  19568. /**
  19569. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19570. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19571. */
  19572. _this.renderOverlay = false;
  19573. /** Defines color to use when rendering overlay */
  19574. _this.overlayColor = BABYLON.Color3.Red();
  19575. /** Defines alpha to use when rendering overlay */
  19576. _this.overlayAlpha = 0.5;
  19577. _this._hasVertexAlpha = false;
  19578. _this._useVertexColors = true;
  19579. _this._computeBonesUsingShaders = true;
  19580. _this._numBoneInfluencers = 4;
  19581. _this._applyFog = true;
  19582. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19583. _this.useOctreeForRenderingSelection = true;
  19584. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19585. _this.useOctreeForPicking = true;
  19586. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19587. _this.useOctreeForCollisions = true;
  19588. _this._layerMask = 0x0FFFFFFF;
  19589. /**
  19590. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19591. */
  19592. _this.alwaysSelectAsActiveMesh = false;
  19593. /**
  19594. * Gets or sets the current action manager
  19595. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19596. */
  19597. _this.actionManager = null;
  19598. /**
  19599. * Gets or sets impostor used for physic simulation
  19600. * @see http://doc.babylonjs.com/features/physics_engine
  19601. */
  19602. _this.physicsImpostor = null;
  19603. // Collisions
  19604. _this._checkCollisions = false;
  19605. _this._collisionMask = -1;
  19606. _this._collisionGroup = -1;
  19607. /**
  19608. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19609. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19610. */
  19611. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19612. /**
  19613. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19614. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19615. */
  19616. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19617. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19618. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19619. // Edges
  19620. /**
  19621. * Defines edge width used when edgesRenderer is enabled
  19622. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19623. */
  19624. _this.edgesWidth = 1;
  19625. /**
  19626. * Defines edge color used when edgesRenderer is enabled
  19627. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19628. */
  19629. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19630. // Cache
  19631. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19632. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19633. /** @hidden */
  19634. _this._renderId = 0;
  19635. /** @hidden */
  19636. _this._intersectionsInProgress = new Array();
  19637. /** @hidden */
  19638. _this._unIndexed = false;
  19639. /** @hidden */
  19640. _this._lightSources = new Array();
  19641. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19642. if (collidedMesh === void 0) { collidedMesh = null; }
  19643. //TODO move this to the collision coordinator!
  19644. if (_this.getScene().workerCollisions)
  19645. newPosition.multiplyInPlace(_this._collider._radius);
  19646. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19647. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19648. _this.position.addInPlace(_this._diffPositionForCollisions);
  19649. }
  19650. if (collidedMesh) {
  19651. _this.onCollideObservable.notifyObservers(collidedMesh);
  19652. }
  19653. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19654. };
  19655. _this.getScene().addMesh(_this);
  19656. _this._resyncLightSources();
  19657. return _this;
  19658. }
  19659. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19660. /**
  19661. * No billboard
  19662. */
  19663. get: function () {
  19664. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19665. },
  19666. enumerable: true,
  19667. configurable: true
  19668. });
  19669. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19670. /** Billboard on X axis */
  19671. get: function () {
  19672. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19673. },
  19674. enumerable: true,
  19675. configurable: true
  19676. });
  19677. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19678. /** Billboard on Y axis */
  19679. get: function () {
  19680. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19681. },
  19682. enumerable: true,
  19683. configurable: true
  19684. });
  19685. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19686. /** Billboard on Z axis */
  19687. get: function () {
  19688. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19689. },
  19690. enumerable: true,
  19691. configurable: true
  19692. });
  19693. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19694. /** Billboard on all axes */
  19695. get: function () {
  19696. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19697. },
  19698. enumerable: true,
  19699. configurable: true
  19700. });
  19701. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19702. /**
  19703. * Gets the number of facets in the mesh
  19704. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19705. */
  19706. get: function () {
  19707. return this._facetNb;
  19708. },
  19709. enumerable: true,
  19710. configurable: true
  19711. });
  19712. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19713. /**
  19714. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19715. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19716. */
  19717. get: function () {
  19718. return this._partitioningSubdivisions;
  19719. },
  19720. set: function (nb) {
  19721. this._partitioningSubdivisions = nb;
  19722. },
  19723. enumerable: true,
  19724. configurable: true
  19725. });
  19726. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19727. /**
  19728. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19729. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19730. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19731. */
  19732. get: function () {
  19733. return this._partitioningBBoxRatio;
  19734. },
  19735. set: function (ratio) {
  19736. this._partitioningBBoxRatio = ratio;
  19737. },
  19738. enumerable: true,
  19739. configurable: true
  19740. });
  19741. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19742. /**
  19743. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19744. * Works only for updatable meshes.
  19745. * Doesn't work with multi-materials
  19746. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19747. */
  19748. get: function () {
  19749. return this._facetDepthSort;
  19750. },
  19751. set: function (sort) {
  19752. this._facetDepthSort = sort;
  19753. },
  19754. enumerable: true,
  19755. configurable: true
  19756. });
  19757. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19758. /**
  19759. * The location (Vector3) where the facet depth sort must be computed from.
  19760. * By default, the active camera position.
  19761. * Used only when facet depth sort is enabled
  19762. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19763. */
  19764. get: function () {
  19765. return this._facetDepthSortFrom;
  19766. },
  19767. set: function (location) {
  19768. this._facetDepthSortFrom = location;
  19769. },
  19770. enumerable: true,
  19771. configurable: true
  19772. });
  19773. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19774. /**
  19775. * gets a boolean indicating if facetData is enabled
  19776. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19777. */
  19778. get: function () {
  19779. return this._facetDataEnabled;
  19780. },
  19781. enumerable: true,
  19782. configurable: true
  19783. });
  19784. /** @hidden */
  19785. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19786. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19787. return false;
  19788. }
  19789. this._markSubMeshesAsMiscDirty();
  19790. return true;
  19791. };
  19792. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19793. /** Set a function to call when this mesh collides with another one */
  19794. set: function (callback) {
  19795. if (this._onCollideObserver) {
  19796. this.onCollideObservable.remove(this._onCollideObserver);
  19797. }
  19798. this._onCollideObserver = this.onCollideObservable.add(callback);
  19799. },
  19800. enumerable: true,
  19801. configurable: true
  19802. });
  19803. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19804. /** Set a function to call when the collision's position changes */
  19805. set: function (callback) {
  19806. if (this._onCollisionPositionChangeObserver) {
  19807. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19808. }
  19809. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19810. },
  19811. enumerable: true,
  19812. configurable: true
  19813. });
  19814. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19815. /**
  19816. * 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
  19817. * @see http://doc.babylonjs.com/features/occlusionquery
  19818. */
  19819. get: function () {
  19820. return this._isOccluded;
  19821. },
  19822. set: function (value) {
  19823. this._isOccluded = value;
  19824. },
  19825. enumerable: true,
  19826. configurable: true
  19827. });
  19828. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19829. /**
  19830. * Flag to check the progress status of the query
  19831. * @see http://doc.babylonjs.com/features/occlusionquery
  19832. */
  19833. get: function () {
  19834. return this._isOcclusionQueryInProgress;
  19835. },
  19836. enumerable: true,
  19837. configurable: true
  19838. });
  19839. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19840. /**
  19841. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19842. */
  19843. get: function () {
  19844. return this._visibility;
  19845. },
  19846. /**
  19847. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19848. */
  19849. set: function (value) {
  19850. if (this._visibility === value) {
  19851. return;
  19852. }
  19853. this._visibility = value;
  19854. this._markSubMeshesAsMiscDirty();
  19855. },
  19856. enumerable: true,
  19857. configurable: true
  19858. });
  19859. Object.defineProperty(AbstractMesh.prototype, "material", {
  19860. /** Gets or sets current material */
  19861. get: function () {
  19862. return this._material;
  19863. },
  19864. set: function (value) {
  19865. if (this._material === value) {
  19866. return;
  19867. }
  19868. this._material = value;
  19869. if (this.onMaterialChangedObservable.hasObservers) {
  19870. this.onMaterialChangedObservable.notifyObservers(this);
  19871. }
  19872. if (!this.subMeshes) {
  19873. return;
  19874. }
  19875. this._unBindEffect();
  19876. },
  19877. enumerable: true,
  19878. configurable: true
  19879. });
  19880. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19881. /**
  19882. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19883. * @see http://doc.babylonjs.com/babylon101/shadows
  19884. */
  19885. get: function () {
  19886. return this._receiveShadows;
  19887. },
  19888. set: function (value) {
  19889. if (this._receiveShadows === value) {
  19890. return;
  19891. }
  19892. this._receiveShadows = value;
  19893. this._markSubMeshesAsLightDirty();
  19894. },
  19895. enumerable: true,
  19896. configurable: true
  19897. });
  19898. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19899. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19900. get: function () {
  19901. return this._hasVertexAlpha;
  19902. },
  19903. set: function (value) {
  19904. if (this._hasVertexAlpha === value) {
  19905. return;
  19906. }
  19907. this._hasVertexAlpha = value;
  19908. this._markSubMeshesAsAttributesDirty();
  19909. this._markSubMeshesAsMiscDirty();
  19910. },
  19911. enumerable: true,
  19912. configurable: true
  19913. });
  19914. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19915. /** 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) */
  19916. get: function () {
  19917. return this._useVertexColors;
  19918. },
  19919. set: function (value) {
  19920. if (this._useVertexColors === value) {
  19921. return;
  19922. }
  19923. this._useVertexColors = value;
  19924. this._markSubMeshesAsAttributesDirty();
  19925. },
  19926. enumerable: true,
  19927. configurable: true
  19928. });
  19929. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19930. /**
  19931. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19932. */
  19933. get: function () {
  19934. return this._computeBonesUsingShaders;
  19935. },
  19936. set: function (value) {
  19937. if (this._computeBonesUsingShaders === value) {
  19938. return;
  19939. }
  19940. this._computeBonesUsingShaders = value;
  19941. this._markSubMeshesAsAttributesDirty();
  19942. },
  19943. enumerable: true,
  19944. configurable: true
  19945. });
  19946. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19947. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19948. get: function () {
  19949. return this._numBoneInfluencers;
  19950. },
  19951. set: function (value) {
  19952. if (this._numBoneInfluencers === value) {
  19953. return;
  19954. }
  19955. this._numBoneInfluencers = value;
  19956. this._markSubMeshesAsAttributesDirty();
  19957. },
  19958. enumerable: true,
  19959. configurable: true
  19960. });
  19961. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19962. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19963. get: function () {
  19964. return this._applyFog;
  19965. },
  19966. set: function (value) {
  19967. if (this._applyFog === value) {
  19968. return;
  19969. }
  19970. this._applyFog = value;
  19971. this._markSubMeshesAsMiscDirty();
  19972. },
  19973. enumerable: true,
  19974. configurable: true
  19975. });
  19976. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19977. /**
  19978. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19979. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19980. */
  19981. get: function () {
  19982. return this._layerMask;
  19983. },
  19984. set: function (value) {
  19985. if (value === this._layerMask) {
  19986. return;
  19987. }
  19988. this._layerMask = value;
  19989. this._resyncLightSources();
  19990. },
  19991. enumerable: true,
  19992. configurable: true
  19993. });
  19994. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19995. /**
  19996. * Gets or sets a collision mask used to mask collisions (default is -1).
  19997. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19998. */
  19999. get: function () {
  20000. return this._collisionMask;
  20001. },
  20002. set: function (mask) {
  20003. this._collisionMask = !isNaN(mask) ? mask : -1;
  20004. },
  20005. enumerable: true,
  20006. configurable: true
  20007. });
  20008. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20009. /**
  20010. * Gets or sets the current collision group mask (-1 by default).
  20011. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20012. */
  20013. get: function () {
  20014. return this._collisionGroup;
  20015. },
  20016. set: function (mask) {
  20017. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20018. },
  20019. enumerable: true,
  20020. configurable: true
  20021. });
  20022. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20023. /** @hidden */
  20024. get: function () {
  20025. return null;
  20026. },
  20027. enumerable: true,
  20028. configurable: true
  20029. });
  20030. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20031. get: function () {
  20032. return this._skeleton;
  20033. },
  20034. /**
  20035. * Gets or sets a skeleton to apply skining transformations
  20036. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20037. */
  20038. set: function (value) {
  20039. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20040. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20041. }
  20042. if (value && value.needInitialSkinMatrix) {
  20043. value._registerMeshWithPoseMatrix(this);
  20044. }
  20045. this._skeleton = value;
  20046. if (!this._skeleton) {
  20047. this._bonesTransformMatrices = null;
  20048. }
  20049. this._markSubMeshesAsAttributesDirty();
  20050. },
  20051. enumerable: true,
  20052. configurable: true
  20053. });
  20054. /**
  20055. * Returns the string "AbstractMesh"
  20056. * @returns "AbstractMesh"
  20057. */
  20058. AbstractMesh.prototype.getClassName = function () {
  20059. return "AbstractMesh";
  20060. };
  20061. /**
  20062. * Gets a string representation of the current mesh
  20063. * @param fullDetails defines a boolean indicating if full details must be included
  20064. * @returns a string representation of the current mesh
  20065. */
  20066. AbstractMesh.prototype.toString = function (fullDetails) {
  20067. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20068. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20069. if (this._skeleton) {
  20070. ret += ", skeleton: " + this._skeleton.name;
  20071. }
  20072. if (fullDetails) {
  20073. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20074. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20075. }
  20076. return ret;
  20077. };
  20078. /** @hidden */
  20079. AbstractMesh.prototype._rebuild = function () {
  20080. if (this._occlusionQuery) {
  20081. this._occlusionQuery = null;
  20082. }
  20083. if (this._edgesRenderer) {
  20084. this._edgesRenderer._rebuild();
  20085. }
  20086. if (!this.subMeshes) {
  20087. return;
  20088. }
  20089. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20090. var subMesh = _a[_i];
  20091. subMesh._rebuild();
  20092. }
  20093. };
  20094. /** @hidden */
  20095. AbstractMesh.prototype._resyncLightSources = function () {
  20096. this._lightSources.length = 0;
  20097. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20098. var light = _a[_i];
  20099. if (!light.isEnabled()) {
  20100. continue;
  20101. }
  20102. if (light.canAffectMesh(this)) {
  20103. this._lightSources.push(light);
  20104. }
  20105. }
  20106. this._markSubMeshesAsLightDirty();
  20107. };
  20108. /** @hidden */
  20109. AbstractMesh.prototype._resyncLighSource = function (light) {
  20110. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20111. var index = this._lightSources.indexOf(light);
  20112. if (index === -1) {
  20113. if (!isIn) {
  20114. return;
  20115. }
  20116. this._lightSources.push(light);
  20117. }
  20118. else {
  20119. if (isIn) {
  20120. return;
  20121. }
  20122. this._lightSources.splice(index, 1);
  20123. }
  20124. this._markSubMeshesAsLightDirty();
  20125. };
  20126. /** @hidden */
  20127. AbstractMesh.prototype._unBindEffect = function () {
  20128. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20129. var subMesh = _a[_i];
  20130. subMesh.setEffect(null);
  20131. }
  20132. };
  20133. /** @hidden */
  20134. AbstractMesh.prototype._removeLightSource = function (light) {
  20135. var index = this._lightSources.indexOf(light);
  20136. if (index === -1) {
  20137. return;
  20138. }
  20139. this._lightSources.splice(index, 1);
  20140. this._markSubMeshesAsLightDirty();
  20141. };
  20142. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20143. if (!this.subMeshes) {
  20144. return;
  20145. }
  20146. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20147. var subMesh = _a[_i];
  20148. if (subMesh._materialDefines) {
  20149. func(subMesh._materialDefines);
  20150. }
  20151. }
  20152. };
  20153. /** @hidden */
  20154. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20155. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20156. };
  20157. /** @hidden */
  20158. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20159. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20160. };
  20161. /** @hidden */
  20162. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20163. if (!this.subMeshes) {
  20164. return;
  20165. }
  20166. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20167. var subMesh = _a[_i];
  20168. var material = subMesh.getMaterial();
  20169. if (material) {
  20170. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20171. }
  20172. }
  20173. };
  20174. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20175. /**
  20176. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20177. */
  20178. get: function () {
  20179. return this._scaling;
  20180. },
  20181. set: function (newScaling) {
  20182. this._scaling = newScaling;
  20183. if (this.physicsImpostor) {
  20184. this.physicsImpostor.forceUpdate();
  20185. }
  20186. },
  20187. enumerable: true,
  20188. configurable: true
  20189. });
  20190. // Methods
  20191. /**
  20192. * Disables the mesh edge rendering mode
  20193. * @returns the currentAbstractMesh
  20194. */
  20195. AbstractMesh.prototype.disableEdgesRendering = function () {
  20196. if (this._edgesRenderer) {
  20197. this._edgesRenderer.dispose();
  20198. this._edgesRenderer = null;
  20199. }
  20200. return this;
  20201. };
  20202. /**
  20203. * Enables the edge rendering mode on the mesh.
  20204. * This mode makes the mesh edges visible
  20205. * @param epsilon defines the maximal distance between two angles to detect a face
  20206. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20207. * @returns the currentAbstractMesh
  20208. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20209. */
  20210. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20211. if (epsilon === void 0) { epsilon = 0.95; }
  20212. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20213. this.disableEdgesRendering();
  20214. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20215. return this;
  20216. };
  20217. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  20218. /**
  20219. * Gets the edgesRenderer associated with the mesh
  20220. */
  20221. get: function () {
  20222. return this._edgesRenderer;
  20223. },
  20224. enumerable: true,
  20225. configurable: true
  20226. });
  20227. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20228. /**
  20229. * Returns true if the mesh is blocked. Implemented by child classes
  20230. */
  20231. get: function () {
  20232. return false;
  20233. },
  20234. enumerable: true,
  20235. configurable: true
  20236. });
  20237. /**
  20238. * Returns the mesh itself by default. Implemented by child classes
  20239. * @param camera defines the camera to use to pick the right LOD level
  20240. * @returns the currentAbstractMesh
  20241. */
  20242. AbstractMesh.prototype.getLOD = function (camera) {
  20243. return this;
  20244. };
  20245. /**
  20246. * Returns 0 by default. Implemented by child classes
  20247. * @returns an integer
  20248. */
  20249. AbstractMesh.prototype.getTotalVertices = function () {
  20250. return 0;
  20251. };
  20252. /**
  20253. * Returns null by default. Implemented by child classes
  20254. * @returns null
  20255. */
  20256. AbstractMesh.prototype.getIndices = function () {
  20257. return null;
  20258. };
  20259. /**
  20260. * Returns the array of the requested vertex data kind. Implemented by child classes
  20261. * @param kind defines the vertex data kind to use
  20262. * @returns null
  20263. */
  20264. AbstractMesh.prototype.getVerticesData = function (kind) {
  20265. return null;
  20266. };
  20267. /**
  20268. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20269. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20270. * Note that a new underlying VertexBuffer object is created each call.
  20271. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20272. * @param kind defines vertex data kind:
  20273. * * BABYLON.VertexBuffer.PositionKind
  20274. * * BABYLON.VertexBuffer.UVKind
  20275. * * BABYLON.VertexBuffer.UV2Kind
  20276. * * BABYLON.VertexBuffer.UV3Kind
  20277. * * BABYLON.VertexBuffer.UV4Kind
  20278. * * BABYLON.VertexBuffer.UV5Kind
  20279. * * BABYLON.VertexBuffer.UV6Kind
  20280. * * BABYLON.VertexBuffer.ColorKind
  20281. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20282. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20283. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20284. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20285. * @param data defines the data source
  20286. * @param updatable defines if the data must be flagged as updatable (or static)
  20287. * @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
  20288. * @returns the current mesh
  20289. */
  20290. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20291. return this;
  20292. };
  20293. /**
  20294. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20295. * If the mesh has no geometry, it is simply returned as it is.
  20296. * @param kind defines vertex data kind:
  20297. * * BABYLON.VertexBuffer.PositionKind
  20298. * * BABYLON.VertexBuffer.UVKind
  20299. * * BABYLON.VertexBuffer.UV2Kind
  20300. * * BABYLON.VertexBuffer.UV3Kind
  20301. * * BABYLON.VertexBuffer.UV4Kind
  20302. * * BABYLON.VertexBuffer.UV5Kind
  20303. * * BABYLON.VertexBuffer.UV6Kind
  20304. * * BABYLON.VertexBuffer.ColorKind
  20305. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20306. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20307. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20308. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20309. * @param data defines the data source
  20310. * @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
  20311. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20312. * @returns the current mesh
  20313. */
  20314. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20315. return this;
  20316. };
  20317. /**
  20318. * Sets the mesh indices,
  20319. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20320. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20321. * @param totalVertices Defines the total number of vertices
  20322. * @returns the current mesh
  20323. */
  20324. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20325. return this;
  20326. };
  20327. /**
  20328. * Gets a boolean indicating if specific vertex data is present
  20329. * @param kind defines the vertex data kind to use
  20330. * @returns true is data kind is present
  20331. */
  20332. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20333. return false;
  20334. };
  20335. /**
  20336. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20337. * @returns a BoundingInfo
  20338. */
  20339. AbstractMesh.prototype.getBoundingInfo = function () {
  20340. if (this._masterMesh) {
  20341. return this._masterMesh.getBoundingInfo();
  20342. }
  20343. if (!this._boundingInfo) {
  20344. // this._boundingInfo is being created here
  20345. this._updateBoundingInfo();
  20346. }
  20347. // cannot be null.
  20348. return this._boundingInfo;
  20349. };
  20350. /**
  20351. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20352. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20353. * @returns the current mesh
  20354. */
  20355. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20356. if (includeDescendants === void 0) { includeDescendants = true; }
  20357. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20358. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20359. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20360. if (maxDimension === 0) {
  20361. return this;
  20362. }
  20363. var scale = 1 / maxDimension;
  20364. this.scaling.scaleInPlace(scale);
  20365. return this;
  20366. };
  20367. /**
  20368. * Overwrite the current bounding info
  20369. * @param boundingInfo defines the new bounding info
  20370. * @returns the current mesh
  20371. */
  20372. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20373. this._boundingInfo = boundingInfo;
  20374. return this;
  20375. };
  20376. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20377. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20378. get: function () {
  20379. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20380. },
  20381. enumerable: true,
  20382. configurable: true
  20383. });
  20384. /** @hidden */
  20385. AbstractMesh.prototype._preActivate = function () {
  20386. };
  20387. /** @hidden */
  20388. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20389. };
  20390. /** @hidden */
  20391. AbstractMesh.prototype._activate = function (renderId) {
  20392. this._renderId = renderId;
  20393. };
  20394. /**
  20395. * Gets the current world matrix
  20396. * @returns a Matrix
  20397. */
  20398. AbstractMesh.prototype.getWorldMatrix = function () {
  20399. if (this._masterMesh) {
  20400. return this._masterMesh.getWorldMatrix();
  20401. }
  20402. return _super.prototype.getWorldMatrix.call(this);
  20403. };
  20404. /** @hidden */
  20405. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20406. if (this._masterMesh) {
  20407. return this._masterMesh._getWorldMatrixDeterminant();
  20408. }
  20409. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20410. };
  20411. // ================================== Point of View Movement =================================
  20412. /**
  20413. * Perform relative position change from the point of view of behind the front of the mesh.
  20414. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20415. * Supports definition of mesh facing forward or backward
  20416. * @param amountRight defines the distance on the right axis
  20417. * @param amountUp defines the distance on the up axis
  20418. * @param amountForward defines the distance on the forward axis
  20419. * @returns the current mesh
  20420. */
  20421. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20422. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20423. return this;
  20424. };
  20425. /**
  20426. * Calculate relative position change from the point of view of behind the front of the mesh.
  20427. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20428. * Supports definition of mesh facing forward or backward
  20429. * @param amountRight defines the distance on the right axis
  20430. * @param amountUp defines the distance on the up axis
  20431. * @param amountForward defines the distance on the forward axis
  20432. * @returns the new displacement vector
  20433. */
  20434. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20435. var rotMatrix = new BABYLON.Matrix();
  20436. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20437. rotQuaternion.toRotationMatrix(rotMatrix);
  20438. var translationDelta = BABYLON.Vector3.Zero();
  20439. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20440. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20441. return translationDelta;
  20442. };
  20443. // ================================== Point of View Rotation =================================
  20444. /**
  20445. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20446. * Supports definition of mesh facing forward or backward
  20447. * @param flipBack defines the flip
  20448. * @param twirlClockwise defines the twirl
  20449. * @param tiltRight defines the tilt
  20450. * @returns the current mesh
  20451. */
  20452. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20453. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20454. return this;
  20455. };
  20456. /**
  20457. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20458. * Supports definition of mesh facing forward or backward.
  20459. * @param flipBack defines the flip
  20460. * @param twirlClockwise defines the twirl
  20461. * @param tiltRight defines the tilt
  20462. * @returns the new rotation vector
  20463. */
  20464. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20465. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20466. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20467. };
  20468. /**
  20469. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20470. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20471. * @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
  20472. * @returns the new bounding vectors
  20473. */
  20474. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20475. if (includeDescendants === void 0) { includeDescendants = true; }
  20476. if (predicate === void 0) { predicate = null; }
  20477. // Ensures that all world matrix will be recomputed.
  20478. this.getScene().incrementRenderId();
  20479. this.computeWorldMatrix(true);
  20480. var min;
  20481. var max;
  20482. var boundingInfo = this.getBoundingInfo();
  20483. if (!this.subMeshes) {
  20484. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20485. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20486. }
  20487. else {
  20488. min = boundingInfo.boundingBox.minimumWorld;
  20489. max = boundingInfo.boundingBox.maximumWorld;
  20490. }
  20491. if (includeDescendants) {
  20492. var descendants = this.getDescendants(false);
  20493. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20494. var descendant = descendants_1[_i];
  20495. var childMesh = descendant;
  20496. childMesh.computeWorldMatrix(true);
  20497. // Filters meshes based on custom predicate function.
  20498. if (predicate && !predicate(childMesh)) {
  20499. continue;
  20500. }
  20501. //make sure we have the needed params to get mix and max
  20502. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20503. continue;
  20504. }
  20505. var childBoundingInfo = childMesh.getBoundingInfo();
  20506. var boundingBox = childBoundingInfo.boundingBox;
  20507. var minBox = boundingBox.minimumWorld;
  20508. var maxBox = boundingBox.maximumWorld;
  20509. BABYLON.Tools.CheckExtends(minBox, min, max);
  20510. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20511. }
  20512. }
  20513. return {
  20514. min: min,
  20515. max: max
  20516. };
  20517. };
  20518. /** @hidden */
  20519. AbstractMesh.prototype._updateBoundingInfo = function () {
  20520. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20521. this._boundingInfo.update(this.worldMatrixFromCache);
  20522. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20523. return this;
  20524. };
  20525. /** @hidden */
  20526. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20527. if (!this.subMeshes) {
  20528. return this;
  20529. }
  20530. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20531. var subMesh = this.subMeshes[subIndex];
  20532. if (!subMesh.IsGlobal) {
  20533. subMesh.updateBoundingInfo(matrix);
  20534. }
  20535. }
  20536. return this;
  20537. };
  20538. /** @hidden */
  20539. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20540. // Bounding info
  20541. this._updateBoundingInfo();
  20542. };
  20543. /**
  20544. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20545. * A mesh is in the frustum if its bounding box intersects the frustum
  20546. * @param frustumPlanes defines the frustum to test
  20547. * @returns true if the mesh is in the frustum planes
  20548. */
  20549. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20550. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);
  20551. };
  20552. /**
  20553. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20554. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20555. * @param frustumPlanes defines the frustum to test
  20556. * @returns true if the mesh is completely in the frustum planes
  20557. */
  20558. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20559. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20560. };
  20561. /**
  20562. * True if the mesh intersects another mesh or a SolidParticle object
  20563. * @param mesh defines a target mesh or SolidParticle to test
  20564. * @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)
  20565. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20566. * @returns true if there is an intersection
  20567. */
  20568. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20569. if (precise === void 0) { precise = false; }
  20570. if (!this._boundingInfo || !mesh._boundingInfo) {
  20571. return false;
  20572. }
  20573. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20574. return true;
  20575. }
  20576. if (includeDescendants) {
  20577. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20578. var child = _a[_i];
  20579. if (child.intersectsMesh(mesh, precise, true)) {
  20580. return true;
  20581. }
  20582. }
  20583. }
  20584. return false;
  20585. };
  20586. /**
  20587. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20588. * @param point defines the point to test
  20589. * @returns true if there is an intersection
  20590. */
  20591. AbstractMesh.prototype.intersectsPoint = function (point) {
  20592. if (!this._boundingInfo) {
  20593. return false;
  20594. }
  20595. return this._boundingInfo.intersectsPoint(point);
  20596. };
  20597. /**
  20598. * Gets the current physics impostor
  20599. * @see http://doc.babylonjs.com/features/physics_engine
  20600. * @returns a physics impostor or null
  20601. */
  20602. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20603. return this.physicsImpostor;
  20604. };
  20605. /**
  20606. * Gets the position of the current mesh in camera space
  20607. * @param camera defines the camera to use
  20608. * @returns a position
  20609. */
  20610. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20611. if (camera === void 0) { camera = null; }
  20612. if (!camera) {
  20613. camera = this.getScene().activeCamera;
  20614. }
  20615. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20616. };
  20617. /**
  20618. * Returns the distance from the mesh to the active camera
  20619. * @param camera defines the camera to use
  20620. * @returns the distance
  20621. */
  20622. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20623. if (camera === void 0) { camera = null; }
  20624. if (!camera) {
  20625. camera = this.getScene().activeCamera;
  20626. }
  20627. return this.absolutePosition.subtract(camera.position).length();
  20628. };
  20629. /**
  20630. * Apply a physic impulse to the mesh
  20631. * @param force defines the force to apply
  20632. * @param contactPoint defines where to apply the force
  20633. * @returns the current mesh
  20634. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20635. */
  20636. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20637. if (!this.physicsImpostor) {
  20638. return this;
  20639. }
  20640. this.physicsImpostor.applyImpulse(force, contactPoint);
  20641. return this;
  20642. };
  20643. /**
  20644. * Creates a physic joint between two meshes
  20645. * @param otherMesh defines the other mesh to use
  20646. * @param pivot1 defines the pivot to use on this mesh
  20647. * @param pivot2 defines the pivot to use on the other mesh
  20648. * @param options defines additional options (can be plugin dependent)
  20649. * @returns the current mesh
  20650. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20651. */
  20652. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20653. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20654. return this;
  20655. }
  20656. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20657. mainPivot: pivot1,
  20658. connectedPivot: pivot2,
  20659. nativeParams: options
  20660. });
  20661. return this;
  20662. };
  20663. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20664. // Collisions
  20665. /**
  20666. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20667. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20668. */
  20669. get: function () {
  20670. return this._checkCollisions;
  20671. },
  20672. set: function (collisionEnabled) {
  20673. this._checkCollisions = collisionEnabled;
  20674. if (this.getScene().workerCollisions) {
  20675. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20676. }
  20677. },
  20678. enumerable: true,
  20679. configurable: true
  20680. });
  20681. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20682. /**
  20683. * Gets Collider object used to compute collisions (not physics)
  20684. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20685. */
  20686. get: function () {
  20687. return this._collider;
  20688. },
  20689. enumerable: true,
  20690. configurable: true
  20691. });
  20692. /**
  20693. * Move the mesh using collision engine
  20694. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20695. * @param displacement defines the requested displacement vector
  20696. * @returns the current mesh
  20697. */
  20698. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20699. var globalPosition = this.getAbsolutePosition();
  20700. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20701. if (!this._collider) {
  20702. this._collider = new BABYLON.Collider();
  20703. }
  20704. this._collider._radius = this.ellipsoid;
  20705. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20706. return this;
  20707. };
  20708. // Submeshes octree
  20709. /**
  20710. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20711. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20712. * @param maxCapacity defines the maximum size of each block (64 by default)
  20713. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20714. * @returns the new octree
  20715. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20716. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20717. */
  20718. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20719. if (maxCapacity === void 0) { maxCapacity = 64; }
  20720. if (maxDepth === void 0) { maxDepth = 2; }
  20721. if (!this._submeshesOctree) {
  20722. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20723. }
  20724. this.computeWorldMatrix(true);
  20725. var boundingInfo = this.getBoundingInfo();
  20726. // Update octree
  20727. var bbox = boundingInfo.boundingBox;
  20728. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20729. return this._submeshesOctree;
  20730. };
  20731. // Collisions
  20732. /** @hidden */
  20733. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20734. this._generatePointsArray();
  20735. if (!this._positions) {
  20736. return this;
  20737. }
  20738. // Transformation
  20739. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20740. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20741. subMesh._lastColliderWorldVertices = [];
  20742. subMesh._trianglePlanes = [];
  20743. var start = subMesh.verticesStart;
  20744. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20745. for (var i = start; i < end; i++) {
  20746. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20747. }
  20748. }
  20749. // Collide
  20750. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20751. if (collider.collisionFound) {
  20752. collider.collidedMesh = this;
  20753. }
  20754. return this;
  20755. };
  20756. /** @hidden */
  20757. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20758. var subMeshes;
  20759. var len;
  20760. // Octrees
  20761. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20762. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20763. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20764. len = intersections.length;
  20765. subMeshes = intersections.data;
  20766. }
  20767. else {
  20768. subMeshes = this.subMeshes;
  20769. len = subMeshes.length;
  20770. }
  20771. for (var index = 0; index < len; index++) {
  20772. var subMesh = subMeshes[index];
  20773. // Bounding test
  20774. if (len > 1 && !subMesh._checkCollision(collider))
  20775. continue;
  20776. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20777. }
  20778. return this;
  20779. };
  20780. /** @hidden */
  20781. AbstractMesh.prototype._checkCollision = function (collider) {
  20782. // Bounding box test
  20783. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20784. return this;
  20785. // Transformation matrix
  20786. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20787. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20788. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20789. return this;
  20790. };
  20791. // Picking
  20792. /** @hidden */
  20793. AbstractMesh.prototype._generatePointsArray = function () {
  20794. return false;
  20795. };
  20796. /**
  20797. * Checks if the passed Ray intersects with the mesh
  20798. * @param ray defines the ray to use
  20799. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20800. * @returns the picking info
  20801. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20802. */
  20803. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20804. var pickingInfo = new BABYLON.PickingInfo();
  20805. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20806. return pickingInfo;
  20807. }
  20808. if (!this._generatePointsArray()) {
  20809. return pickingInfo;
  20810. }
  20811. var intersectInfo = null;
  20812. // Octrees
  20813. var subMeshes;
  20814. var len;
  20815. if (this._submeshesOctree && this.useOctreeForPicking) {
  20816. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20817. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20818. len = intersections.length;
  20819. subMeshes = intersections.data;
  20820. }
  20821. else {
  20822. subMeshes = this.subMeshes;
  20823. len = subMeshes.length;
  20824. }
  20825. for (var index = 0; index < len; index++) {
  20826. var subMesh = subMeshes[index];
  20827. // Bounding test
  20828. if (len > 1 && !subMesh.canIntersects(ray))
  20829. continue;
  20830. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20831. if (currentIntersectInfo) {
  20832. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20833. intersectInfo = currentIntersectInfo;
  20834. intersectInfo.subMeshId = index;
  20835. if (fastCheck) {
  20836. break;
  20837. }
  20838. }
  20839. }
  20840. }
  20841. if (intersectInfo) {
  20842. // Get picked point
  20843. var world = this.getWorldMatrix();
  20844. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20845. var direction = ray.direction.clone();
  20846. direction = direction.scale(intersectInfo.distance);
  20847. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20848. var pickedPoint = worldOrigin.add(worldDirection);
  20849. // Return result
  20850. pickingInfo.hit = true;
  20851. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20852. pickingInfo.pickedPoint = pickedPoint;
  20853. pickingInfo.pickedMesh = this;
  20854. pickingInfo.bu = intersectInfo.bu || 0;
  20855. pickingInfo.bv = intersectInfo.bv || 0;
  20856. pickingInfo.faceId = intersectInfo.faceId;
  20857. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20858. return pickingInfo;
  20859. }
  20860. return pickingInfo;
  20861. };
  20862. /**
  20863. * Clones the current mesh
  20864. * @param name defines the mesh name
  20865. * @param newParent defines the new mesh parent
  20866. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20867. * @returns the new mesh
  20868. */
  20869. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20870. return null;
  20871. };
  20872. /**
  20873. * Disposes all the submeshes of the current meshnp
  20874. * @returns the current mesh
  20875. */
  20876. AbstractMesh.prototype.releaseSubMeshes = function () {
  20877. if (this.subMeshes) {
  20878. while (this.subMeshes.length) {
  20879. this.subMeshes[0].dispose();
  20880. }
  20881. }
  20882. else {
  20883. this.subMeshes = new Array();
  20884. }
  20885. return this;
  20886. };
  20887. /**
  20888. * Releases resources associated with this abstract mesh.
  20889. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20890. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20891. */
  20892. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20893. var _this = this;
  20894. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20895. var index;
  20896. // Smart Array Retainers.
  20897. this.getScene().freeActiveMeshes();
  20898. this.getScene().freeRenderingGroups();
  20899. // Action manager
  20900. if (this.actionManager !== undefined && this.actionManager !== null) {
  20901. this.actionManager.dispose();
  20902. this.actionManager = null;
  20903. }
  20904. // Skeleton
  20905. this._skeleton = null;
  20906. // Physics
  20907. if (this.physicsImpostor) {
  20908. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20909. }
  20910. // Intersections in progress
  20911. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20912. var other = this._intersectionsInProgress[index];
  20913. var pos = other._intersectionsInProgress.indexOf(this);
  20914. other._intersectionsInProgress.splice(pos, 1);
  20915. }
  20916. this._intersectionsInProgress = [];
  20917. // Lights
  20918. var lights = this.getScene().lights;
  20919. lights.forEach(function (light) {
  20920. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20921. if (meshIndex !== -1) {
  20922. light.includedOnlyMeshes.splice(meshIndex, 1);
  20923. }
  20924. meshIndex = light.excludedMeshes.indexOf(_this);
  20925. if (meshIndex !== -1) {
  20926. light.excludedMeshes.splice(meshIndex, 1);
  20927. }
  20928. // Shadow generators
  20929. var generator = light.getShadowGenerator();
  20930. if (generator) {
  20931. var shadowMap = generator.getShadowMap();
  20932. if (shadowMap && shadowMap.renderList) {
  20933. meshIndex = shadowMap.renderList.indexOf(_this);
  20934. if (meshIndex !== -1) {
  20935. shadowMap.renderList.splice(meshIndex, 1);
  20936. }
  20937. }
  20938. }
  20939. });
  20940. // Edges
  20941. if (this._edgesRenderer) {
  20942. this._edgesRenderer.dispose();
  20943. this._edgesRenderer = null;
  20944. }
  20945. // SubMeshes
  20946. if (this.getClassName() !== "InstancedMesh") {
  20947. this.releaseSubMeshes();
  20948. }
  20949. // Octree
  20950. var sceneOctree = this.getScene().selectionOctree;
  20951. if (sceneOctree !== undefined && sceneOctree !== null) {
  20952. var index = sceneOctree.dynamicContent.indexOf(this);
  20953. if (index !== -1) {
  20954. sceneOctree.dynamicContent.splice(index, 1);
  20955. }
  20956. }
  20957. // Query
  20958. var engine = this.getScene().getEngine();
  20959. if (this._occlusionQuery) {
  20960. this._isOcclusionQueryInProgress = false;
  20961. engine.deleteQuery(this._occlusionQuery);
  20962. this._occlusionQuery = null;
  20963. }
  20964. // Engine
  20965. engine.wipeCaches();
  20966. // Remove from scene
  20967. this.getScene().removeMesh(this);
  20968. if (disposeMaterialAndTextures) {
  20969. if (this.material) {
  20970. this.material.dispose(false, true);
  20971. }
  20972. }
  20973. if (!doNotRecurse) {
  20974. // Particles
  20975. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20976. if (this.getScene().particleSystems[index].emitter === this) {
  20977. this.getScene().particleSystems[index].dispose();
  20978. index--;
  20979. }
  20980. }
  20981. }
  20982. // facet data
  20983. if (this._facetDataEnabled) {
  20984. this.disableFacetData();
  20985. }
  20986. this.onAfterWorldMatrixUpdateObservable.clear();
  20987. this.onCollideObservable.clear();
  20988. this.onCollisionPositionChangeObservable.clear();
  20989. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20990. };
  20991. /**
  20992. * Adds the passed mesh as a child to the current mesh
  20993. * @param mesh defines the child mesh
  20994. * @returns the current mesh
  20995. */
  20996. AbstractMesh.prototype.addChild = function (mesh) {
  20997. mesh.setParent(this);
  20998. return this;
  20999. };
  21000. /**
  21001. * Removes the passed mesh from the current mesh children list
  21002. * @param mesh defines the child mesh
  21003. * @returns the current mesh
  21004. */
  21005. AbstractMesh.prototype.removeChild = function (mesh) {
  21006. mesh.setParent(null);
  21007. return this;
  21008. };
  21009. // Facet data
  21010. /** @hidden */
  21011. AbstractMesh.prototype._initFacetData = function () {
  21012. if (!this._facetNormals) {
  21013. this._facetNormals = new Array();
  21014. }
  21015. if (!this._facetPositions) {
  21016. this._facetPositions = new Array();
  21017. }
  21018. if (!this._facetPartitioning) {
  21019. this._facetPartitioning = new Array();
  21020. }
  21021. this._facetNb = (this.getIndices().length / 3) | 0;
  21022. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21023. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21024. for (var f = 0; f < this._facetNb; f++) {
  21025. this._facetNormals[f] = BABYLON.Vector3.Zero();
  21026. this._facetPositions[f] = BABYLON.Vector3.Zero();
  21027. }
  21028. this._facetDataEnabled = true;
  21029. return this;
  21030. };
  21031. /**
  21032. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21033. * This method can be called within the render loop.
  21034. * 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
  21035. * @returns the current mesh
  21036. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21037. */
  21038. AbstractMesh.prototype.updateFacetData = function () {
  21039. if (!this._facetDataEnabled) {
  21040. this._initFacetData();
  21041. }
  21042. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21043. var indices = this.getIndices();
  21044. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21045. var bInfo = this.getBoundingInfo();
  21046. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21047. // init arrays, matrix and sort function on first call
  21048. this._facetDepthSortEnabled = true;
  21049. if (indices instanceof Uint16Array) {
  21050. this._depthSortedIndices = new Uint16Array(indices);
  21051. }
  21052. else if (indices instanceof Uint32Array) {
  21053. this._depthSortedIndices = new Uint32Array(indices);
  21054. }
  21055. else {
  21056. var needs32bits = false;
  21057. for (var i = 0; i < indices.length; i++) {
  21058. if (indices[i] > 65535) {
  21059. needs32bits = true;
  21060. break;
  21061. }
  21062. }
  21063. if (needs32bits) {
  21064. this._depthSortedIndices = new Uint32Array(indices);
  21065. }
  21066. else {
  21067. this._depthSortedIndices = new Uint16Array(indices);
  21068. }
  21069. }
  21070. this._facetDepthSortFunction = function (f1, f2) {
  21071. return (f2.sqDistance - f1.sqDistance);
  21072. };
  21073. if (!this._facetDepthSortFrom) {
  21074. var camera = this.getScene().activeCamera;
  21075. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21076. }
  21077. this._depthSortedFacets = [];
  21078. for (var f = 0; f < this._facetNb; f++) {
  21079. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21080. this._depthSortedFacets.push(depthSortedFacet);
  21081. }
  21082. this._invertedMatrix = BABYLON.Matrix.Identity();
  21083. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21084. }
  21085. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21086. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21087. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21088. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21089. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21090. this._subDiv.max = this._partitioningSubdivisions;
  21091. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21092. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21093. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21094. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21095. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21096. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21097. // set the parameters for ComputeNormals()
  21098. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21099. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21100. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21101. this._facetParameters.bInfo = bInfo;
  21102. this._facetParameters.bbSize = this._bbSize;
  21103. this._facetParameters.subDiv = this._subDiv;
  21104. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21105. this._facetParameters.depthSort = this._facetDepthSort;
  21106. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21107. this.computeWorldMatrix(true);
  21108. this._worldMatrix.invertToRef(this._invertedMatrix);
  21109. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21110. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21111. }
  21112. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21113. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21114. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21115. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21116. var l = (this._depthSortedIndices.length / 3) | 0;
  21117. for (var f = 0; f < l; f++) {
  21118. var sind = this._depthSortedFacets[f].ind;
  21119. this._depthSortedIndices[f * 3] = indices[sind];
  21120. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21121. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21122. }
  21123. this.updateIndices(this._depthSortedIndices);
  21124. }
  21125. return this;
  21126. };
  21127. /**
  21128. * Returns the facetLocalNormals array.
  21129. * The normals are expressed in the mesh local spac
  21130. * @returns an array of Vector3
  21131. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21132. */
  21133. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21134. if (!this._facetNormals) {
  21135. this.updateFacetData();
  21136. }
  21137. return this._facetNormals;
  21138. };
  21139. /**
  21140. * Returns the facetLocalPositions array.
  21141. * The facet positions are expressed in the mesh local space
  21142. * @returns an array of Vector3
  21143. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21144. */
  21145. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21146. if (!this._facetPositions) {
  21147. this.updateFacetData();
  21148. }
  21149. return this._facetPositions;
  21150. };
  21151. /**
  21152. * Returns the facetLocalPartioning array
  21153. * @returns an array of array of numbers
  21154. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21155. */
  21156. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21157. if (!this._facetPartitioning) {
  21158. this.updateFacetData();
  21159. }
  21160. return this._facetPartitioning;
  21161. };
  21162. /**
  21163. * Returns the i-th facet position in the world system.
  21164. * This method allocates a new Vector3 per call
  21165. * @param i defines the facet index
  21166. * @returns a new Vector3
  21167. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21168. */
  21169. AbstractMesh.prototype.getFacetPosition = function (i) {
  21170. var pos = BABYLON.Vector3.Zero();
  21171. this.getFacetPositionToRef(i, pos);
  21172. return pos;
  21173. };
  21174. /**
  21175. * Sets the reference Vector3 with the i-th facet position in the world system
  21176. * @param i defines the facet index
  21177. * @param ref defines the target vector
  21178. * @returns the current mesh
  21179. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21180. */
  21181. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21182. var localPos = (this.getFacetLocalPositions())[i];
  21183. var world = this.getWorldMatrix();
  21184. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21185. return this;
  21186. };
  21187. /**
  21188. * Returns the i-th facet normal in the world system.
  21189. * This method allocates a new Vector3 per call
  21190. * @param i defines the facet index
  21191. * @returns a new Vector3
  21192. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21193. */
  21194. AbstractMesh.prototype.getFacetNormal = function (i) {
  21195. var norm = BABYLON.Vector3.Zero();
  21196. this.getFacetNormalToRef(i, norm);
  21197. return norm;
  21198. };
  21199. /**
  21200. * Sets the reference Vector3 with the i-th facet normal in the world system
  21201. * @param i defines the facet index
  21202. * @param ref defines the target vector
  21203. * @returns the current mesh
  21204. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21205. */
  21206. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21207. var localNorm = (this.getFacetLocalNormals())[i];
  21208. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21209. return this;
  21210. };
  21211. /**
  21212. * 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)
  21213. * @param x defines x coordinate
  21214. * @param y defines y coordinate
  21215. * @param z defines z coordinate
  21216. * @returns the array of facet indexes
  21217. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21218. */
  21219. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21220. var bInfo = this.getBoundingInfo();
  21221. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21222. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21223. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21224. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21225. return null;
  21226. }
  21227. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21228. };
  21229. /**
  21230. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21231. * @param projected sets as the (x,y,z) world projection on the facet
  21232. * @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
  21233. * @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
  21234. * @param x defines x coordinate
  21235. * @param y defines y coordinate
  21236. * @param z defines z coordinate
  21237. * @returns the face index if found (or null instead)
  21238. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21239. */
  21240. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21241. if (checkFace === void 0) { checkFace = false; }
  21242. if (facing === void 0) { facing = true; }
  21243. var world = this.getWorldMatrix();
  21244. var invMat = BABYLON.Tmp.Matrix[5];
  21245. world.invertToRef(invMat);
  21246. var invVect = BABYLON.Tmp.Vector3[8];
  21247. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21248. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21249. if (projected) {
  21250. // tranform the local computed projected vector to world coordinates
  21251. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21252. }
  21253. return closest;
  21254. };
  21255. /**
  21256. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21257. * @param projected sets as the (x,y,z) local projection on the facet
  21258. * @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
  21259. * @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
  21260. * @param x defines x coordinate
  21261. * @param y defines y coordinate
  21262. * @param z defines z coordinate
  21263. * @returns the face index if found (or null instead)
  21264. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21265. */
  21266. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21267. if (checkFace === void 0) { checkFace = false; }
  21268. if (facing === void 0) { facing = true; }
  21269. var closest = null;
  21270. var tmpx = 0.0;
  21271. var tmpy = 0.0;
  21272. var tmpz = 0.0;
  21273. var d = 0.0; // tmp dot facet normal * facet position
  21274. var t0 = 0.0;
  21275. var projx = 0.0;
  21276. var projy = 0.0;
  21277. var projz = 0.0;
  21278. // Get all the facets in the same partitioning block than (x, y, z)
  21279. var facetPositions = this.getFacetLocalPositions();
  21280. var facetNormals = this.getFacetLocalNormals();
  21281. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21282. if (!facetsInBlock) {
  21283. return null;
  21284. }
  21285. // Get the closest facet to (x, y, z)
  21286. var shortest = Number.MAX_VALUE; // init distance vars
  21287. var tmpDistance = shortest;
  21288. var fib; // current facet in the block
  21289. var norm; // current facet normal
  21290. var p0; // current facet barycenter position
  21291. // loop on all the facets in the current partitioning block
  21292. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21293. fib = facetsInBlock[idx];
  21294. norm = facetNormals[fib];
  21295. p0 = facetPositions[fib];
  21296. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21297. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21298. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21299. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21300. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21301. projx = x + norm.x * t0;
  21302. projy = y + norm.y * t0;
  21303. projz = z + norm.z * t0;
  21304. tmpx = projx - x;
  21305. tmpy = projy - y;
  21306. tmpz = projz - z;
  21307. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21308. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21309. shortest = tmpDistance;
  21310. closest = fib;
  21311. if (projected) {
  21312. projected.x = projx;
  21313. projected.y = projy;
  21314. projected.z = projz;
  21315. }
  21316. }
  21317. }
  21318. }
  21319. return closest;
  21320. };
  21321. /**
  21322. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21323. * @returns the parameters
  21324. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21325. */
  21326. AbstractMesh.prototype.getFacetDataParameters = function () {
  21327. return this._facetParameters;
  21328. };
  21329. /**
  21330. * Disables the feature FacetData and frees the related memory
  21331. * @returns the current mesh
  21332. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21333. */
  21334. AbstractMesh.prototype.disableFacetData = function () {
  21335. if (this._facetDataEnabled) {
  21336. this._facetDataEnabled = false;
  21337. this._facetPositions = new Array();
  21338. this._facetNormals = new Array();
  21339. this._facetPartitioning = new Array();
  21340. this._facetParameters = null;
  21341. this._depthSortedIndices = new Uint32Array(0);
  21342. }
  21343. return this;
  21344. };
  21345. /**
  21346. * Updates the AbstractMesh indices array
  21347. * @param indices defines the data source
  21348. * @returns the current mesh
  21349. */
  21350. AbstractMesh.prototype.updateIndices = function (indices) {
  21351. return this;
  21352. };
  21353. /**
  21354. * Creates new normals data for the mesh
  21355. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21356. * @returns the current mesh
  21357. */
  21358. AbstractMesh.prototype.createNormals = function (updatable) {
  21359. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21360. var indices = this.getIndices();
  21361. var normals;
  21362. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21363. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21364. }
  21365. else {
  21366. normals = [];
  21367. }
  21368. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21369. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21370. return this;
  21371. };
  21372. /**
  21373. * Align the mesh with a normal
  21374. * @param normal defines the normal to use
  21375. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21376. * @returns the current mesh
  21377. */
  21378. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21379. if (!upDirection) {
  21380. upDirection = BABYLON.Axis.Y;
  21381. }
  21382. var axisX = BABYLON.Tmp.Vector3[0];
  21383. var axisZ = BABYLON.Tmp.Vector3[1];
  21384. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21385. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21386. if (this.rotationQuaternion) {
  21387. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21388. }
  21389. else {
  21390. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21391. }
  21392. return this;
  21393. };
  21394. /** @hidden */
  21395. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21396. this._isOccluded = false;
  21397. };
  21398. /** No occlusion */
  21399. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21400. /** Occlusion set to optimisitic */
  21401. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21402. /** Occlusion set to strict */
  21403. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21404. /** Use an accurante occlusion algorithm */
  21405. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21406. /** Use a conservative occlusion algorithm */
  21407. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21408. /** Default culling strategy with bounding box and bounding sphere and then frustum culling */
  21409. AbstractMesh.CULLINGSTRATEGY_STANDARD = 0;
  21410. /** Culling strategy with bounding sphere only and then frustum culling */
  21411. AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
  21412. return AbstractMesh;
  21413. }(BABYLON.TransformNode));
  21414. BABYLON.AbstractMesh = AbstractMesh;
  21415. })(BABYLON || (BABYLON = {}));
  21416. //# sourceMappingURL=babylon.abstractMesh.js.map
  21417. var BABYLON;
  21418. (function (BABYLON) {
  21419. /**
  21420. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21421. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21422. * 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.
  21423. */
  21424. var Light = /** @class */ (function (_super) {
  21425. __extends(Light, _super);
  21426. /**
  21427. * Creates a Light object in the scene.
  21428. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21429. * @param name The firendly name of the light
  21430. * @param scene The scene the light belongs too
  21431. */
  21432. function Light(name, scene) {
  21433. var _this = _super.call(this, name, scene) || this;
  21434. /**
  21435. * Diffuse gives the basic color to an object.
  21436. */
  21437. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21438. /**
  21439. * Specular produces a highlight color on an object.
  21440. * Note: This is note affecting PBR materials.
  21441. */
  21442. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21443. /**
  21444. * Defines the falloff type for this light. This lets overrriding how punctual light are
  21445. * falling off base on range or angle.
  21446. * This can be set to any values in Light.FALLOFF_x.
  21447. *
  21448. * Note: This is only usefull for PBR Materials at the moment. This could be extended if required to
  21449. * other types of materials.
  21450. */
  21451. _this.falloffType = Light.FALLOFF_DEFAULT;
  21452. /**
  21453. * Strength of the light.
  21454. * Note: By default it is define in the framework own unit.
  21455. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21456. */
  21457. _this.intensity = 1.0;
  21458. _this._range = Number.MAX_VALUE;
  21459. _this._inverseSquaredRange = 0;
  21460. /**
  21461. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21462. * of light.
  21463. */
  21464. _this._photometricScale = 1.0;
  21465. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21466. _this._radius = 0.00001;
  21467. /**
  21468. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21469. * exceeding the number allowed of the materials.
  21470. */
  21471. _this.renderPriority = 0;
  21472. _this._shadowEnabled = true;
  21473. _this._excludeWithLayerMask = 0;
  21474. _this._includeOnlyWithLayerMask = 0;
  21475. _this._lightmapMode = 0;
  21476. /**
  21477. * @hidden Internal use only.
  21478. */
  21479. _this._excludedMeshesIds = new Array();
  21480. /**
  21481. * @hidden Internal use only.
  21482. */
  21483. _this._includedOnlyMeshesIds = new Array();
  21484. _this.getScene().addLight(_this);
  21485. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21486. _this._buildUniformLayout();
  21487. _this.includedOnlyMeshes = new Array();
  21488. _this.excludedMeshes = new Array();
  21489. _this._resyncMeshes();
  21490. return _this;
  21491. }
  21492. Object.defineProperty(Light.prototype, "range", {
  21493. /**
  21494. * Defines how far from the source the light is impacting in scene units.
  21495. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21496. */
  21497. get: function () {
  21498. return this._range;
  21499. },
  21500. /**
  21501. * Defines how far from the source the light is impacting in scene units.
  21502. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21503. */
  21504. set: function (value) {
  21505. this._range = value;
  21506. this._inverseSquaredRange = 1.0 / (this.range * this.range);
  21507. },
  21508. enumerable: true,
  21509. configurable: true
  21510. });
  21511. Object.defineProperty(Light.prototype, "intensityMode", {
  21512. /**
  21513. * Gets the photometric scale used to interpret the intensity.
  21514. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21515. */
  21516. get: function () {
  21517. return this._intensityMode;
  21518. },
  21519. /**
  21520. * Sets the photometric scale used to interpret the intensity.
  21521. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21522. */
  21523. set: function (value) {
  21524. this._intensityMode = value;
  21525. this._computePhotometricScale();
  21526. },
  21527. enumerable: true,
  21528. configurable: true
  21529. });
  21530. ;
  21531. ;
  21532. Object.defineProperty(Light.prototype, "radius", {
  21533. /**
  21534. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21535. */
  21536. get: function () {
  21537. return this._radius;
  21538. },
  21539. /**
  21540. * sets the light radius used by PBR Materials to simulate soft area lights.
  21541. */
  21542. set: function (value) {
  21543. this._radius = value;
  21544. this._computePhotometricScale();
  21545. },
  21546. enumerable: true,
  21547. configurable: true
  21548. });
  21549. ;
  21550. ;
  21551. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21552. /**
  21553. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21554. * the current shadow generator.
  21555. */
  21556. get: function () {
  21557. return this._shadowEnabled;
  21558. },
  21559. /**
  21560. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21561. * the current shadow generator.
  21562. */
  21563. set: function (value) {
  21564. if (this._shadowEnabled === value) {
  21565. return;
  21566. }
  21567. this._shadowEnabled = value;
  21568. this._markMeshesAsLightDirty();
  21569. },
  21570. enumerable: true,
  21571. configurable: true
  21572. });
  21573. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21574. /**
  21575. * Gets the only meshes impacted by this light.
  21576. */
  21577. get: function () {
  21578. return this._includedOnlyMeshes;
  21579. },
  21580. /**
  21581. * Sets the only meshes impacted by this light.
  21582. */
  21583. set: function (value) {
  21584. this._includedOnlyMeshes = value;
  21585. this._hookArrayForIncludedOnly(value);
  21586. },
  21587. enumerable: true,
  21588. configurable: true
  21589. });
  21590. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21591. /**
  21592. * Gets the meshes not impacted by this light.
  21593. */
  21594. get: function () {
  21595. return this._excludedMeshes;
  21596. },
  21597. /**
  21598. * Sets the meshes not impacted by this light.
  21599. */
  21600. set: function (value) {
  21601. this._excludedMeshes = value;
  21602. this._hookArrayForExcluded(value);
  21603. },
  21604. enumerable: true,
  21605. configurable: true
  21606. });
  21607. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21608. /**
  21609. * Gets the layer id use to find what meshes are not impacted by the light.
  21610. * Inactive if 0
  21611. */
  21612. get: function () {
  21613. return this._excludeWithLayerMask;
  21614. },
  21615. /**
  21616. * Sets the layer id use to find what meshes are not impacted by the light.
  21617. * Inactive if 0
  21618. */
  21619. set: function (value) {
  21620. this._excludeWithLayerMask = value;
  21621. this._resyncMeshes();
  21622. },
  21623. enumerable: true,
  21624. configurable: true
  21625. });
  21626. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21627. /**
  21628. * Gets the layer id use to find what meshes are impacted by the light.
  21629. * Inactive if 0
  21630. */
  21631. get: function () {
  21632. return this._includeOnlyWithLayerMask;
  21633. },
  21634. /**
  21635. * Sets the layer id use to find what meshes are impacted by the light.
  21636. * Inactive if 0
  21637. */
  21638. set: function (value) {
  21639. this._includeOnlyWithLayerMask = value;
  21640. this._resyncMeshes();
  21641. },
  21642. enumerable: true,
  21643. configurable: true
  21644. });
  21645. Object.defineProperty(Light.prototype, "lightmapMode", {
  21646. /**
  21647. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21648. */
  21649. get: function () {
  21650. return this._lightmapMode;
  21651. },
  21652. /**
  21653. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21654. */
  21655. set: function (value) {
  21656. if (this._lightmapMode === value) {
  21657. return;
  21658. }
  21659. this._lightmapMode = value;
  21660. this._markMeshesAsLightDirty();
  21661. },
  21662. enumerable: true,
  21663. configurable: true
  21664. });
  21665. /**
  21666. * Returns the string "Light".
  21667. * @returns the class name
  21668. */
  21669. Light.prototype.getClassName = function () {
  21670. return "Light";
  21671. };
  21672. /**
  21673. * Converts the light information to a readable string for debug purpose.
  21674. * @param fullDetails Supports for multiple levels of logging within scene loading
  21675. * @returns the human readable light info
  21676. */
  21677. Light.prototype.toString = function (fullDetails) {
  21678. var ret = "Name: " + this.name;
  21679. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21680. if (this.animations) {
  21681. for (var i = 0; i < this.animations.length; i++) {
  21682. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21683. }
  21684. }
  21685. if (fullDetails) {
  21686. }
  21687. return ret;
  21688. };
  21689. /**
  21690. * Set the enabled state of this node.
  21691. * @param value - the new enabled state
  21692. */
  21693. Light.prototype.setEnabled = function (value) {
  21694. _super.prototype.setEnabled.call(this, value);
  21695. this._resyncMeshes();
  21696. };
  21697. /**
  21698. * Returns the Light associated shadow generator if any.
  21699. * @return the associated shadow generator.
  21700. */
  21701. Light.prototype.getShadowGenerator = function () {
  21702. return this._shadowGenerator;
  21703. };
  21704. /**
  21705. * Returns a Vector3, the absolute light position in the World.
  21706. * @returns the world space position of the light
  21707. */
  21708. Light.prototype.getAbsolutePosition = function () {
  21709. return BABYLON.Vector3.Zero();
  21710. };
  21711. /**
  21712. * Specifies if the light will affect the passed mesh.
  21713. * @param mesh The mesh to test against the light
  21714. * @return true the mesh is affected otherwise, false.
  21715. */
  21716. Light.prototype.canAffectMesh = function (mesh) {
  21717. if (!mesh) {
  21718. return true;
  21719. }
  21720. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21721. return false;
  21722. }
  21723. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21724. return false;
  21725. }
  21726. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21727. return false;
  21728. }
  21729. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21730. return false;
  21731. }
  21732. return true;
  21733. };
  21734. /**
  21735. * Computes and Returns the light World matrix.
  21736. * @returns the world matrix
  21737. */
  21738. Light.prototype.getWorldMatrix = function () {
  21739. this._currentRenderId = this.getScene().getRenderId();
  21740. this._childRenderId = this._currentRenderId;
  21741. var worldMatrix = this._getWorldMatrix();
  21742. if (this.parent && this.parent.getWorldMatrix) {
  21743. if (!this._parentedWorldMatrix) {
  21744. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21745. }
  21746. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21747. this._markSyncedWithParent();
  21748. return this._parentedWorldMatrix;
  21749. }
  21750. return worldMatrix;
  21751. };
  21752. /**
  21753. * Sort function to order lights for rendering.
  21754. * @param a First Light object to compare to second.
  21755. * @param b Second Light object to compare first.
  21756. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21757. */
  21758. Light.CompareLightsPriority = function (a, b) {
  21759. //shadow-casting lights have priority over non-shadow-casting lights
  21760. //the renderPrioirty is a secondary sort criterion
  21761. if (a.shadowEnabled !== b.shadowEnabled) {
  21762. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21763. }
  21764. return b.renderPriority - a.renderPriority;
  21765. };
  21766. /**
  21767. * Releases resources associated with this node.
  21768. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21769. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21770. */
  21771. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21772. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21773. if (this._shadowGenerator) {
  21774. this._shadowGenerator.dispose();
  21775. this._shadowGenerator = null;
  21776. }
  21777. // Animations
  21778. this.getScene().stopAnimation(this);
  21779. // Remove from meshes
  21780. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21781. var mesh = _a[_i];
  21782. mesh._removeLightSource(this);
  21783. }
  21784. this._uniformBuffer.dispose();
  21785. // Remove from scene
  21786. this.getScene().removeLight(this);
  21787. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21788. };
  21789. /**
  21790. * Returns the light type ID (integer).
  21791. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21792. */
  21793. Light.prototype.getTypeID = function () {
  21794. return 0;
  21795. };
  21796. /**
  21797. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21798. * @returns the scaled intensity in intensity mode unit
  21799. */
  21800. Light.prototype.getScaledIntensity = function () {
  21801. return this._photometricScale * this.intensity;
  21802. };
  21803. /**
  21804. * Returns a new Light object, named "name", from the current one.
  21805. * @param name The name of the cloned light
  21806. * @returns the new created light
  21807. */
  21808. Light.prototype.clone = function (name) {
  21809. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21810. if (!constructor) {
  21811. return null;
  21812. }
  21813. return BABYLON.SerializationHelper.Clone(constructor, this);
  21814. };
  21815. /**
  21816. * Serializes the current light into a Serialization object.
  21817. * @returns the serialized object.
  21818. */
  21819. Light.prototype.serialize = function () {
  21820. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21821. // Type
  21822. serializationObject.type = this.getTypeID();
  21823. // Parent
  21824. if (this.parent) {
  21825. serializationObject.parentId = this.parent.id;
  21826. }
  21827. // Inclusion / exclusions
  21828. if (this.excludedMeshes.length > 0) {
  21829. serializationObject.excludedMeshesIds = [];
  21830. this.excludedMeshes.forEach(function (mesh) {
  21831. serializationObject.excludedMeshesIds.push(mesh.id);
  21832. });
  21833. }
  21834. if (this.includedOnlyMeshes.length > 0) {
  21835. serializationObject.includedOnlyMeshesIds = [];
  21836. this.includedOnlyMeshes.forEach(function (mesh) {
  21837. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21838. });
  21839. }
  21840. // Animations
  21841. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21842. serializationObject.ranges = this.serializeAnimationRanges();
  21843. return serializationObject;
  21844. };
  21845. /**
  21846. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21847. * This new light is named "name" and added to the passed scene.
  21848. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21849. * @param name The friendly name of the light
  21850. * @param scene The scene the new light will belong to
  21851. * @returns the constructor function
  21852. */
  21853. Light.GetConstructorFromName = function (type, name, scene) {
  21854. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  21855. if (constructorFunc) {
  21856. return constructorFunc;
  21857. }
  21858. // Default to no light for none present once.
  21859. return null;
  21860. };
  21861. /**
  21862. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21863. * @param parsedLight The JSON representation of the light
  21864. * @param scene The scene to create the parsed light in
  21865. * @returns the created light after parsing
  21866. */
  21867. Light.Parse = function (parsedLight, scene) {
  21868. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21869. if (!constructor) {
  21870. return null;
  21871. }
  21872. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21873. // Inclusion / exclusions
  21874. if (parsedLight.excludedMeshesIds) {
  21875. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21876. }
  21877. if (parsedLight.includedOnlyMeshesIds) {
  21878. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21879. }
  21880. // Parent
  21881. if (parsedLight.parentId) {
  21882. light._waitingParentId = parsedLight.parentId;
  21883. }
  21884. // Animations
  21885. if (parsedLight.animations) {
  21886. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21887. var parsedAnimation = parsedLight.animations[animationIndex];
  21888. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21889. }
  21890. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21891. }
  21892. if (parsedLight.autoAnimate) {
  21893. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21894. }
  21895. return light;
  21896. };
  21897. Light.prototype._hookArrayForExcluded = function (array) {
  21898. var _this = this;
  21899. var oldPush = array.push;
  21900. array.push = function () {
  21901. var items = [];
  21902. for (var _i = 0; _i < arguments.length; _i++) {
  21903. items[_i] = arguments[_i];
  21904. }
  21905. var result = oldPush.apply(array, items);
  21906. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21907. var item = items_1[_a];
  21908. item._resyncLighSource(_this);
  21909. }
  21910. return result;
  21911. };
  21912. var oldSplice = array.splice;
  21913. array.splice = function (index, deleteCount) {
  21914. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21915. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21916. var item = deleted_1[_i];
  21917. item._resyncLighSource(_this);
  21918. }
  21919. return deleted;
  21920. };
  21921. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21922. var item = array_1[_i];
  21923. item._resyncLighSource(this);
  21924. }
  21925. };
  21926. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21927. var _this = this;
  21928. var oldPush = array.push;
  21929. array.push = function () {
  21930. var items = [];
  21931. for (var _i = 0; _i < arguments.length; _i++) {
  21932. items[_i] = arguments[_i];
  21933. }
  21934. var result = oldPush.apply(array, items);
  21935. _this._resyncMeshes();
  21936. return result;
  21937. };
  21938. var oldSplice = array.splice;
  21939. array.splice = function (index, deleteCount) {
  21940. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21941. _this._resyncMeshes();
  21942. return deleted;
  21943. };
  21944. this._resyncMeshes();
  21945. };
  21946. Light.prototype._resyncMeshes = function () {
  21947. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21948. var mesh = _a[_i];
  21949. mesh._resyncLighSource(this);
  21950. }
  21951. };
  21952. /**
  21953. * Forces the meshes to update their light related information in their rendering used effects
  21954. * @hidden Internal Use Only
  21955. */
  21956. Light.prototype._markMeshesAsLightDirty = function () {
  21957. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21958. var mesh = _a[_i];
  21959. if (mesh._lightSources.indexOf(this) !== -1) {
  21960. mesh._markSubMeshesAsLightDirty();
  21961. }
  21962. }
  21963. };
  21964. /**
  21965. * Recomputes the cached photometric scale if needed.
  21966. */
  21967. Light.prototype._computePhotometricScale = function () {
  21968. this._photometricScale = this._getPhotometricScale();
  21969. this.getScene().resetCachedMaterial();
  21970. };
  21971. /**
  21972. * Returns the Photometric Scale according to the light type and intensity mode.
  21973. */
  21974. Light.prototype._getPhotometricScale = function () {
  21975. var photometricScale = 0.0;
  21976. var lightTypeID = this.getTypeID();
  21977. //get photometric mode
  21978. var photometricMode = this.intensityMode;
  21979. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21980. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21981. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21982. }
  21983. else {
  21984. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21985. }
  21986. }
  21987. //compute photometric scale
  21988. switch (lightTypeID) {
  21989. case Light.LIGHTTYPEID_POINTLIGHT:
  21990. case Light.LIGHTTYPEID_SPOTLIGHT:
  21991. switch (photometricMode) {
  21992. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21993. photometricScale = 1.0 / (4.0 * Math.PI);
  21994. break;
  21995. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21996. photometricScale = 1.0;
  21997. break;
  21998. case Light.INTENSITYMODE_LUMINANCE:
  21999. photometricScale = this.radius * this.radius;
  22000. break;
  22001. }
  22002. break;
  22003. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22004. switch (photometricMode) {
  22005. case Light.INTENSITYMODE_ILLUMINANCE:
  22006. photometricScale = 1.0;
  22007. break;
  22008. case Light.INTENSITYMODE_LUMINANCE:
  22009. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22010. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22011. var apexAngleRadians = this.radius;
  22012. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22013. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22014. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22015. photometricScale = solidAngle;
  22016. break;
  22017. }
  22018. break;
  22019. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22020. // No fall off in hemisperic light.
  22021. photometricScale = 1.0;
  22022. break;
  22023. }
  22024. return photometricScale;
  22025. };
  22026. /**
  22027. * Reorder the light in the scene according to their defined priority.
  22028. * @hidden Internal Use Only
  22029. */
  22030. Light.prototype._reorderLightsInScene = function () {
  22031. var scene = this.getScene();
  22032. if (this._renderPriority != 0) {
  22033. scene.requireLightSorting = true;
  22034. }
  22035. this.getScene().sortLightsByPriority();
  22036. };
  22037. /**
  22038. * Falloff Default: light is falling off following the material specification:
  22039. * standard material is using standard falloff whereas pbr material can request special falloff per materials.
  22040. */
  22041. Light.FALLOFF_DEFAULT = 0;
  22042. /**
  22043. * Falloff Physical: light is falling off following the inverse squared distance law.
  22044. */
  22045. Light.FALLOFF_PHYSICAL = 1;
  22046. /**
  22047. * Falloff gltf: light is falling off as described in the gltf moving to PBR document
  22048. * to enhance interoperability with other engines.
  22049. */
  22050. Light.FALLOFF_GLTF = 2;
  22051. /**
  22052. * Falloff Standard: light is falling off like in the standard material
  22053. * to enhance interoperability with other materials.
  22054. */
  22055. Light.FALLOFF_STANDARD = 3;
  22056. //lightmapMode Consts
  22057. /**
  22058. * If every light affecting the material is in this lightmapMode,
  22059. * material.lightmapTexture adds or multiplies
  22060. * (depends on material.useLightmapAsShadowmap)
  22061. * after every other light calculations.
  22062. */
  22063. Light.LIGHTMAP_DEFAULT = 0;
  22064. /**
  22065. * material.lightmapTexture as only diffuse lighting from this light
  22066. * adds only specular lighting from this light
  22067. * adds dynamic shadows
  22068. */
  22069. Light.LIGHTMAP_SPECULAR = 1;
  22070. /**
  22071. * material.lightmapTexture as only lighting
  22072. * no light calculation from this light
  22073. * only adds dynamic shadows from this light
  22074. */
  22075. Light.LIGHTMAP_SHADOWSONLY = 2;
  22076. // Intensity Mode Consts
  22077. /**
  22078. * Each light type uses the default quantity according to its type:
  22079. * point/spot lights use luminous intensity
  22080. * directional lights use illuminance
  22081. */
  22082. Light.INTENSITYMODE_AUTOMATIC = 0;
  22083. /**
  22084. * lumen (lm)
  22085. */
  22086. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  22087. /**
  22088. * candela (lm/sr)
  22089. */
  22090. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22091. /**
  22092. * lux (lm/m^2)
  22093. */
  22094. Light.INTENSITYMODE_ILLUMINANCE = 3;
  22095. /**
  22096. * nit (cd/m^2)
  22097. */
  22098. Light.INTENSITYMODE_LUMINANCE = 4;
  22099. // Light types ids const.
  22100. /**
  22101. * Light type const id of the point light.
  22102. */
  22103. Light.LIGHTTYPEID_POINTLIGHT = 0;
  22104. /**
  22105. * Light type const id of the directional light.
  22106. */
  22107. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22108. /**
  22109. * Light type const id of the spot light.
  22110. */
  22111. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  22112. /**
  22113. * Light type const id of the hemispheric light.
  22114. */
  22115. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22116. __decorate([
  22117. BABYLON.serializeAsColor3()
  22118. ], Light.prototype, "diffuse", void 0);
  22119. __decorate([
  22120. BABYLON.serializeAsColor3()
  22121. ], Light.prototype, "specular", void 0);
  22122. __decorate([
  22123. BABYLON.serialize()
  22124. ], Light.prototype, "falloffType", void 0);
  22125. __decorate([
  22126. BABYLON.serialize()
  22127. ], Light.prototype, "intensity", void 0);
  22128. __decorate([
  22129. BABYLON.serialize()
  22130. ], Light.prototype, "range", null);
  22131. __decorate([
  22132. BABYLON.serialize()
  22133. ], Light.prototype, "intensityMode", null);
  22134. __decorate([
  22135. BABYLON.serialize()
  22136. ], Light.prototype, "radius", null);
  22137. __decorate([
  22138. BABYLON.serialize()
  22139. ], Light.prototype, "_renderPriority", void 0);
  22140. __decorate([
  22141. BABYLON.expandToProperty("_reorderLightsInScene")
  22142. ], Light.prototype, "renderPriority", void 0);
  22143. __decorate([
  22144. BABYLON.serialize("shadowEnabled")
  22145. ], Light.prototype, "_shadowEnabled", void 0);
  22146. __decorate([
  22147. BABYLON.serialize("excludeWithLayerMask")
  22148. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22149. __decorate([
  22150. BABYLON.serialize("includeOnlyWithLayerMask")
  22151. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22152. __decorate([
  22153. BABYLON.serialize("lightmapMode")
  22154. ], Light.prototype, "_lightmapMode", void 0);
  22155. return Light;
  22156. }(BABYLON.Node));
  22157. BABYLON.Light = Light;
  22158. })(BABYLON || (BABYLON = {}));
  22159. //# sourceMappingURL=babylon.light.js.map
  22160. var BABYLON;
  22161. (function (BABYLON) {
  22162. var Camera = /** @class */ (function (_super) {
  22163. __extends(Camera, _super);
  22164. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22165. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22166. var _this = _super.call(this, name, scene) || this;
  22167. /**
  22168. * The vector the camera should consider as up.
  22169. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22170. */
  22171. _this.upVector = BABYLON.Vector3.Up();
  22172. _this.orthoLeft = null;
  22173. _this.orthoRight = null;
  22174. _this.orthoBottom = null;
  22175. _this.orthoTop = null;
  22176. /**
  22177. * FOV is set in Radians. (default is 0.8)
  22178. */
  22179. _this.fov = 0.8;
  22180. _this.minZ = 1;
  22181. _this.maxZ = 10000.0;
  22182. _this.inertia = 0.9;
  22183. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22184. _this.isIntermediate = false;
  22185. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22186. /**
  22187. * Restricts the camera to viewing objects with the same layerMask.
  22188. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22189. */
  22190. _this.layerMask = 0x0FFFFFFF;
  22191. /**
  22192. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22193. */
  22194. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22195. // Camera rig members
  22196. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22197. /** @hidden */
  22198. _this._rigCameras = new Array();
  22199. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22200. /** @hidden */
  22201. _this._skipRendering = false;
  22202. _this.customRenderTargets = new Array();
  22203. // Observables
  22204. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22205. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22206. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22207. _this.onRestoreStateObservable = new BABYLON.Observable();
  22208. // Cache
  22209. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22210. _this._projectionMatrix = new BABYLON.Matrix();
  22211. _this._doNotComputeProjectionMatrix = false;
  22212. _this._worldMatrix = BABYLON.Matrix.Identity();
  22213. _this._postProcesses = new Array();
  22214. _this._transformMatrix = BABYLON.Matrix.Zero();
  22215. _this._activeMeshes = new BABYLON.SmartArray(256);
  22216. _this._globalPosition = BABYLON.Vector3.Zero();
  22217. _this._refreshFrustumPlanes = true;
  22218. _this.getScene().addCamera(_this);
  22219. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22220. _this.getScene().activeCamera = _this;
  22221. }
  22222. _this.position = position;
  22223. return _this;
  22224. }
  22225. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22226. get: function () {
  22227. return Camera._PERSPECTIVE_CAMERA;
  22228. },
  22229. enumerable: true,
  22230. configurable: true
  22231. });
  22232. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22233. get: function () {
  22234. return Camera._ORTHOGRAPHIC_CAMERA;
  22235. },
  22236. enumerable: true,
  22237. configurable: true
  22238. });
  22239. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22240. /**
  22241. * This is the default FOV mode for perspective cameras.
  22242. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22243. *
  22244. */
  22245. get: function () {
  22246. return Camera._FOVMODE_VERTICAL_FIXED;
  22247. },
  22248. enumerable: true,
  22249. configurable: true
  22250. });
  22251. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22252. /**
  22253. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22254. *
  22255. */
  22256. get: function () {
  22257. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22258. },
  22259. enumerable: true,
  22260. configurable: true
  22261. });
  22262. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22263. get: function () {
  22264. return Camera._RIG_MODE_NONE;
  22265. },
  22266. enumerable: true,
  22267. configurable: true
  22268. });
  22269. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22270. get: function () {
  22271. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22272. },
  22273. enumerable: true,
  22274. configurable: true
  22275. });
  22276. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22277. get: function () {
  22278. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22279. },
  22280. enumerable: true,
  22281. configurable: true
  22282. });
  22283. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22284. get: function () {
  22285. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22286. },
  22287. enumerable: true,
  22288. configurable: true
  22289. });
  22290. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22291. get: function () {
  22292. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22293. },
  22294. enumerable: true,
  22295. configurable: true
  22296. });
  22297. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22298. get: function () {
  22299. return Camera._RIG_MODE_VR;
  22300. },
  22301. enumerable: true,
  22302. configurable: true
  22303. });
  22304. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22305. get: function () {
  22306. return Camera._RIG_MODE_WEBVR;
  22307. },
  22308. enumerable: true,
  22309. configurable: true
  22310. });
  22311. /**
  22312. * Store current camera state (fov, position, etc..)
  22313. */
  22314. Camera.prototype.storeState = function () {
  22315. this._stateStored = true;
  22316. this._storedFov = this.fov;
  22317. return this;
  22318. };
  22319. /**
  22320. * Restores the camera state values if it has been stored. You must call storeState() first
  22321. */
  22322. Camera.prototype._restoreStateValues = function () {
  22323. if (!this._stateStored) {
  22324. return false;
  22325. }
  22326. this.fov = this._storedFov;
  22327. return true;
  22328. };
  22329. /**
  22330. * Restored camera state. You must call storeState() first
  22331. */
  22332. Camera.prototype.restoreState = function () {
  22333. if (this._restoreStateValues()) {
  22334. this.onRestoreStateObservable.notifyObservers(this);
  22335. return true;
  22336. }
  22337. return false;
  22338. };
  22339. Camera.prototype.getClassName = function () {
  22340. return "Camera";
  22341. };
  22342. /**
  22343. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22344. */
  22345. Camera.prototype.toString = function (fullDetails) {
  22346. var ret = "Name: " + this.name;
  22347. ret += ", type: " + this.getClassName();
  22348. if (this.animations) {
  22349. for (var i = 0; i < this.animations.length; i++) {
  22350. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22351. }
  22352. }
  22353. if (fullDetails) {
  22354. }
  22355. return ret;
  22356. };
  22357. Object.defineProperty(Camera.prototype, "globalPosition", {
  22358. get: function () {
  22359. return this._globalPosition;
  22360. },
  22361. enumerable: true,
  22362. configurable: true
  22363. });
  22364. Camera.prototype.getActiveMeshes = function () {
  22365. return this._activeMeshes;
  22366. };
  22367. Camera.prototype.isActiveMesh = function (mesh) {
  22368. return (this._activeMeshes.indexOf(mesh) !== -1);
  22369. };
  22370. /**
  22371. * Is this camera ready to be used/rendered
  22372. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22373. * @return true if the camera is ready
  22374. */
  22375. Camera.prototype.isReady = function (completeCheck) {
  22376. if (completeCheck === void 0) { completeCheck = false; }
  22377. if (completeCheck) {
  22378. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22379. var pp = _a[_i];
  22380. if (pp && !pp.isReady()) {
  22381. return false;
  22382. }
  22383. }
  22384. }
  22385. return _super.prototype.isReady.call(this, completeCheck);
  22386. };
  22387. //Cache
  22388. /** @hidden */
  22389. Camera.prototype._initCache = function () {
  22390. _super.prototype._initCache.call(this);
  22391. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22392. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22393. this._cache.mode = undefined;
  22394. this._cache.minZ = undefined;
  22395. this._cache.maxZ = undefined;
  22396. this._cache.fov = undefined;
  22397. this._cache.fovMode = undefined;
  22398. this._cache.aspectRatio = undefined;
  22399. this._cache.orthoLeft = undefined;
  22400. this._cache.orthoRight = undefined;
  22401. this._cache.orthoBottom = undefined;
  22402. this._cache.orthoTop = undefined;
  22403. this._cache.renderWidth = undefined;
  22404. this._cache.renderHeight = undefined;
  22405. };
  22406. /** @hidden */
  22407. Camera.prototype._updateCache = function (ignoreParentClass) {
  22408. if (!ignoreParentClass) {
  22409. _super.prototype._updateCache.call(this);
  22410. }
  22411. this._cache.position.copyFrom(this.position);
  22412. this._cache.upVector.copyFrom(this.upVector);
  22413. };
  22414. // Synchronized
  22415. /** @hidden */
  22416. Camera.prototype._isSynchronized = function () {
  22417. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22418. };
  22419. /** @hidden */
  22420. Camera.prototype._isSynchronizedViewMatrix = function () {
  22421. if (!_super.prototype._isSynchronized.call(this))
  22422. return false;
  22423. return this._cache.position.equals(this.position)
  22424. && this._cache.upVector.equals(this.upVector)
  22425. && this.isSynchronizedWithParent();
  22426. };
  22427. /** @hidden */
  22428. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22429. var check = this._cache.mode === this.mode
  22430. && this._cache.minZ === this.minZ
  22431. && this._cache.maxZ === this.maxZ;
  22432. if (!check) {
  22433. return false;
  22434. }
  22435. var engine = this.getEngine();
  22436. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22437. check = this._cache.fov === this.fov
  22438. && this._cache.fovMode === this.fovMode
  22439. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22440. }
  22441. else {
  22442. check = this._cache.orthoLeft === this.orthoLeft
  22443. && this._cache.orthoRight === this.orthoRight
  22444. && this._cache.orthoBottom === this.orthoBottom
  22445. && this._cache.orthoTop === this.orthoTop
  22446. && this._cache.renderWidth === engine.getRenderWidth()
  22447. && this._cache.renderHeight === engine.getRenderHeight();
  22448. }
  22449. return check;
  22450. };
  22451. // Controls
  22452. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22453. };
  22454. Camera.prototype.detachControl = function (element) {
  22455. };
  22456. Camera.prototype.update = function () {
  22457. this._checkInputs();
  22458. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22459. this._updateRigCameras();
  22460. }
  22461. };
  22462. /** @hidden */
  22463. Camera.prototype._checkInputs = function () {
  22464. this.onAfterCheckInputsObservable.notifyObservers(this);
  22465. };
  22466. Object.defineProperty(Camera.prototype, "rigCameras", {
  22467. get: function () {
  22468. return this._rigCameras;
  22469. },
  22470. enumerable: true,
  22471. configurable: true
  22472. });
  22473. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22474. get: function () {
  22475. return this._rigPostProcess;
  22476. },
  22477. enumerable: true,
  22478. configurable: true
  22479. });
  22480. /**
  22481. * Internal, gets the first post proces.
  22482. * @returns the first post process to be run on this camera.
  22483. */
  22484. Camera.prototype._getFirstPostProcess = function () {
  22485. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22486. if (this._postProcesses[ppIndex] !== null) {
  22487. return this._postProcesses[ppIndex];
  22488. }
  22489. }
  22490. return null;
  22491. };
  22492. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22493. // invalidate framebuffer
  22494. var firstPostProcess = this._getFirstPostProcess();
  22495. if (firstPostProcess) {
  22496. firstPostProcess.markTextureDirty();
  22497. }
  22498. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22499. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22500. var cam = this._rigCameras[i];
  22501. var rigPostProcess = cam._rigPostProcess;
  22502. // for VR rig, there does not have to be a post process
  22503. if (rigPostProcess) {
  22504. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22505. if (isPass) {
  22506. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22507. cam.isIntermediate = this._postProcesses.length === 0;
  22508. }
  22509. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22510. rigPostProcess.markTextureDirty();
  22511. }
  22512. else {
  22513. cam._postProcesses = this._postProcesses.slice(0);
  22514. }
  22515. }
  22516. };
  22517. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22518. if (insertAt === void 0) { insertAt = null; }
  22519. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22520. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22521. return 0;
  22522. }
  22523. if (insertAt == null || insertAt < 0) {
  22524. this._postProcesses.push(postProcess);
  22525. }
  22526. else if (this._postProcesses[insertAt] === null) {
  22527. this._postProcesses[insertAt] = postProcess;
  22528. }
  22529. else {
  22530. this._postProcesses.splice(insertAt, 0, postProcess);
  22531. }
  22532. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22533. return this._postProcesses.indexOf(postProcess);
  22534. };
  22535. Camera.prototype.detachPostProcess = function (postProcess) {
  22536. var idx = this._postProcesses.indexOf(postProcess);
  22537. if (idx !== -1) {
  22538. this._postProcesses[idx] = null;
  22539. }
  22540. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22541. };
  22542. Camera.prototype.getWorldMatrix = function () {
  22543. if (this._isSynchronizedViewMatrix()) {
  22544. return this._worldMatrix;
  22545. }
  22546. // Getting the the view matrix will also compute the world matrix.
  22547. this.getViewMatrix();
  22548. return this._worldMatrix;
  22549. };
  22550. /** @hidden */
  22551. Camera.prototype._getViewMatrix = function () {
  22552. return BABYLON.Matrix.Identity();
  22553. };
  22554. Camera.prototype.getViewMatrix = function (force) {
  22555. if (!force && this._isSynchronizedViewMatrix()) {
  22556. return this._computedViewMatrix;
  22557. }
  22558. this.updateCache();
  22559. this._computedViewMatrix = this._getViewMatrix();
  22560. this._currentRenderId = this.getScene().getRenderId();
  22561. this._childRenderId = this._currentRenderId;
  22562. this._refreshFrustumPlanes = true;
  22563. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22564. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22565. }
  22566. this.onViewMatrixChangedObservable.notifyObservers(this);
  22567. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22568. return this._computedViewMatrix;
  22569. };
  22570. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22571. this._doNotComputeProjectionMatrix = true;
  22572. if (projection !== undefined) {
  22573. this._projectionMatrix = projection;
  22574. }
  22575. };
  22576. ;
  22577. Camera.prototype.unfreezeProjectionMatrix = function () {
  22578. this._doNotComputeProjectionMatrix = false;
  22579. };
  22580. ;
  22581. Camera.prototype.getProjectionMatrix = function (force) {
  22582. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22583. return this._projectionMatrix;
  22584. }
  22585. // Cache
  22586. this._cache.mode = this.mode;
  22587. this._cache.minZ = this.minZ;
  22588. this._cache.maxZ = this.maxZ;
  22589. // Matrix
  22590. this._refreshFrustumPlanes = true;
  22591. var engine = this.getEngine();
  22592. var scene = this.getScene();
  22593. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22594. this._cache.fov = this.fov;
  22595. this._cache.fovMode = this.fovMode;
  22596. this._cache.aspectRatio = engine.getAspectRatio(this);
  22597. if (this.minZ <= 0) {
  22598. this.minZ = 0.1;
  22599. }
  22600. if (scene.useRightHandedSystem) {
  22601. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22602. }
  22603. else {
  22604. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22605. }
  22606. }
  22607. else {
  22608. var halfWidth = engine.getRenderWidth() / 2.0;
  22609. var halfHeight = engine.getRenderHeight() / 2.0;
  22610. if (scene.useRightHandedSystem) {
  22611. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22612. }
  22613. else {
  22614. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22615. }
  22616. this._cache.orthoLeft = this.orthoLeft;
  22617. this._cache.orthoRight = this.orthoRight;
  22618. this._cache.orthoBottom = this.orthoBottom;
  22619. this._cache.orthoTop = this.orthoTop;
  22620. this._cache.renderWidth = engine.getRenderWidth();
  22621. this._cache.renderHeight = engine.getRenderHeight();
  22622. }
  22623. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22624. return this._projectionMatrix;
  22625. };
  22626. /**
  22627. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  22628. * @returns a Matrix
  22629. */
  22630. Camera.prototype.getTransformationMatrix = function () {
  22631. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22632. return this._transformMatrix;
  22633. };
  22634. Camera.prototype.updateFrustumPlanes = function () {
  22635. if (!this._refreshFrustumPlanes) {
  22636. return;
  22637. }
  22638. this.getTransformationMatrix();
  22639. if (!this._frustumPlanes) {
  22640. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22641. }
  22642. else {
  22643. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22644. }
  22645. this._refreshFrustumPlanes = false;
  22646. };
  22647. Camera.prototype.isInFrustum = function (target) {
  22648. this.updateFrustumPlanes();
  22649. return target.isInFrustum(this._frustumPlanes);
  22650. };
  22651. Camera.prototype.isCompletelyInFrustum = function (target) {
  22652. this.updateFrustumPlanes();
  22653. return target.isCompletelyInFrustum(this._frustumPlanes);
  22654. };
  22655. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22656. if (length === void 0) { length = 100; }
  22657. if (!transform) {
  22658. transform = this.getWorldMatrix();
  22659. }
  22660. if (!origin) {
  22661. origin = this.position;
  22662. }
  22663. var forward = new BABYLON.Vector3(0, 0, 1);
  22664. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22665. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22666. return new BABYLON.Ray(origin, direction, length);
  22667. };
  22668. /**
  22669. * Releases resources associated with this node.
  22670. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22671. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22672. */
  22673. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22674. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22675. // Observables
  22676. this.onViewMatrixChangedObservable.clear();
  22677. this.onProjectionMatrixChangedObservable.clear();
  22678. this.onAfterCheckInputsObservable.clear();
  22679. this.onRestoreStateObservable.clear();
  22680. // Inputs
  22681. if (this.inputs) {
  22682. this.inputs.clear();
  22683. }
  22684. // Animations
  22685. this.getScene().stopAnimation(this);
  22686. // Remove from scene
  22687. this.getScene().removeCamera(this);
  22688. while (this._rigCameras.length > 0) {
  22689. var camera = this._rigCameras.pop();
  22690. if (camera) {
  22691. camera.dispose();
  22692. }
  22693. }
  22694. // Postprocesses
  22695. if (this._rigPostProcess) {
  22696. this._rigPostProcess.dispose(this);
  22697. this._rigPostProcess = null;
  22698. this._postProcesses = [];
  22699. }
  22700. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22701. this._rigPostProcess = null;
  22702. this._postProcesses = [];
  22703. }
  22704. else {
  22705. var i = this._postProcesses.length;
  22706. while (--i >= 0) {
  22707. var postProcess = this._postProcesses[i];
  22708. if (postProcess) {
  22709. postProcess.dispose(this);
  22710. }
  22711. }
  22712. }
  22713. // Render targets
  22714. var i = this.customRenderTargets.length;
  22715. while (--i >= 0) {
  22716. this.customRenderTargets[i].dispose();
  22717. }
  22718. this.customRenderTargets = [];
  22719. // Active Meshes
  22720. this._activeMeshes.dispose();
  22721. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22722. };
  22723. Object.defineProperty(Camera.prototype, "leftCamera", {
  22724. // ---- Camera rigs section ----
  22725. get: function () {
  22726. if (this._rigCameras.length < 1) {
  22727. return null;
  22728. }
  22729. return this._rigCameras[0];
  22730. },
  22731. enumerable: true,
  22732. configurable: true
  22733. });
  22734. Object.defineProperty(Camera.prototype, "rightCamera", {
  22735. get: function () {
  22736. if (this._rigCameras.length < 2) {
  22737. return null;
  22738. }
  22739. return this._rigCameras[1];
  22740. },
  22741. enumerable: true,
  22742. configurable: true
  22743. });
  22744. Camera.prototype.getLeftTarget = function () {
  22745. if (this._rigCameras.length < 1) {
  22746. return null;
  22747. }
  22748. return this._rigCameras[0].getTarget();
  22749. };
  22750. Camera.prototype.getRightTarget = function () {
  22751. if (this._rigCameras.length < 2) {
  22752. return null;
  22753. }
  22754. return this._rigCameras[1].getTarget();
  22755. };
  22756. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22757. if (this.cameraRigMode === mode) {
  22758. return;
  22759. }
  22760. while (this._rigCameras.length > 0) {
  22761. var camera = this._rigCameras.pop();
  22762. if (camera) {
  22763. camera.dispose();
  22764. }
  22765. }
  22766. this.cameraRigMode = mode;
  22767. this._cameraRigParams = {};
  22768. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22769. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22770. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22771. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22772. // create the rig cameras, unless none
  22773. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22774. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22775. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22776. if (leftCamera && rightCamera) {
  22777. this._rigCameras.push(leftCamera);
  22778. this._rigCameras.push(rightCamera);
  22779. }
  22780. }
  22781. switch (this.cameraRigMode) {
  22782. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22783. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22784. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22785. break;
  22786. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22787. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22788. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22789. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22790. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22791. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22792. break;
  22793. case Camera.RIG_MODE_VR:
  22794. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22795. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22796. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22797. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22798. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22799. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22800. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22801. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22802. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22803. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22804. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22805. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22806. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22807. if (metrics.compensateDistortion) {
  22808. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22809. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22810. }
  22811. break;
  22812. case Camera.RIG_MODE_WEBVR:
  22813. if (rigParams.vrDisplay) {
  22814. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22815. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22816. //Left eye
  22817. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22818. this._rigCameras[0].setCameraRigParameter("left", true);
  22819. //leaving this for future reference
  22820. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22821. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22822. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22823. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22824. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22825. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22826. this._rigCameras[0].parent = this;
  22827. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22828. //Right eye
  22829. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22830. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22831. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22832. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22833. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22834. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22835. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22836. this._rigCameras[1].parent = this;
  22837. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22838. if (Camera.UseAlternateWebVRRendering) {
  22839. this._rigCameras[1]._skipRendering = true;
  22840. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22841. }
  22842. }
  22843. break;
  22844. }
  22845. this._cascadePostProcessesToRigCams();
  22846. this.update();
  22847. };
  22848. Camera.prototype._getVRProjectionMatrix = function () {
  22849. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22850. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22851. return this._projectionMatrix;
  22852. };
  22853. Camera.prototype._updateCameraRotationMatrix = function () {
  22854. //Here for WebVR
  22855. };
  22856. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22857. //Here for WebVR
  22858. };
  22859. /**
  22860. * This function MUST be overwritten by the different WebVR cameras available.
  22861. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22862. */
  22863. Camera.prototype._getWebVRProjectionMatrix = function () {
  22864. return BABYLON.Matrix.Identity();
  22865. };
  22866. /**
  22867. * This function MUST be overwritten by the different WebVR cameras available.
  22868. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22869. */
  22870. Camera.prototype._getWebVRViewMatrix = function () {
  22871. return BABYLON.Matrix.Identity();
  22872. };
  22873. Camera.prototype.setCameraRigParameter = function (name, value) {
  22874. if (!this._cameraRigParams) {
  22875. this._cameraRigParams = {};
  22876. }
  22877. this._cameraRigParams[name] = value;
  22878. //provisionnally:
  22879. if (name === "interaxialDistance") {
  22880. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22881. }
  22882. };
  22883. /**
  22884. * needs to be overridden by children so sub has required properties to be copied
  22885. */
  22886. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22887. return null;
  22888. };
  22889. /**
  22890. * May need to be overridden by children
  22891. * @hidden
  22892. */
  22893. Camera.prototype._updateRigCameras = function () {
  22894. for (var i = 0; i < this._rigCameras.length; i++) {
  22895. this._rigCameras[i].minZ = this.minZ;
  22896. this._rigCameras[i].maxZ = this.maxZ;
  22897. this._rigCameras[i].fov = this.fov;
  22898. }
  22899. // only update viewport when ANAGLYPH
  22900. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22901. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22902. }
  22903. };
  22904. /** @hidden */
  22905. Camera.prototype._setupInputs = function () {
  22906. };
  22907. Camera.prototype.serialize = function () {
  22908. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22909. // Type
  22910. serializationObject.type = this.getClassName();
  22911. // Parent
  22912. if (this.parent) {
  22913. serializationObject.parentId = this.parent.id;
  22914. }
  22915. if (this.inputs) {
  22916. this.inputs.serialize(serializationObject);
  22917. }
  22918. // Animations
  22919. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22920. serializationObject.ranges = this.serializeAnimationRanges();
  22921. return serializationObject;
  22922. };
  22923. Camera.prototype.clone = function (name) {
  22924. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22925. };
  22926. Camera.prototype.getDirection = function (localAxis) {
  22927. var result = BABYLON.Vector3.Zero();
  22928. this.getDirectionToRef(localAxis, result);
  22929. return result;
  22930. };
  22931. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22932. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22933. };
  22934. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22935. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22936. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22937. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  22938. interaxial_distance: interaxial_distance,
  22939. isStereoscopicSideBySide: isStereoscopicSideBySide
  22940. });
  22941. if (constructorFunc) {
  22942. return constructorFunc;
  22943. }
  22944. // Default to universal camera
  22945. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22946. };
  22947. Camera.prototype.computeWorldMatrix = function () {
  22948. return this.getWorldMatrix();
  22949. };
  22950. Camera.Parse = function (parsedCamera, scene) {
  22951. var type = parsedCamera.type;
  22952. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22953. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22954. // Parent
  22955. if (parsedCamera.parentId) {
  22956. camera._waitingParentId = parsedCamera.parentId;
  22957. }
  22958. //If camera has an input manager, let it parse inputs settings
  22959. if (camera.inputs) {
  22960. camera.inputs.parse(parsedCamera);
  22961. camera._setupInputs();
  22962. }
  22963. if (camera.setPosition) { // need to force position
  22964. camera.position.copyFromFloats(0, 0, 0);
  22965. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22966. }
  22967. // Target
  22968. if (parsedCamera.target) {
  22969. if (camera.setTarget) {
  22970. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22971. }
  22972. }
  22973. // Apply 3d rig, when found
  22974. if (parsedCamera.cameraRigMode) {
  22975. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22976. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22977. }
  22978. // Animations
  22979. if (parsedCamera.animations) {
  22980. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22981. var parsedAnimation = parsedCamera.animations[animationIndex];
  22982. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22983. }
  22984. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22985. }
  22986. if (parsedCamera.autoAnimate) {
  22987. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22988. }
  22989. return camera;
  22990. };
  22991. // Statics
  22992. Camera._PERSPECTIVE_CAMERA = 0;
  22993. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22994. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22995. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22996. Camera._RIG_MODE_NONE = 0;
  22997. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22998. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22999. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23000. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23001. Camera._RIG_MODE_VR = 20;
  23002. Camera._RIG_MODE_WEBVR = 21;
  23003. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23004. Camera.UseAlternateWebVRRendering = false;
  23005. __decorate([
  23006. BABYLON.serializeAsVector3()
  23007. ], Camera.prototype, "position", void 0);
  23008. __decorate([
  23009. BABYLON.serializeAsVector3()
  23010. ], Camera.prototype, "upVector", void 0);
  23011. __decorate([
  23012. BABYLON.serialize()
  23013. ], Camera.prototype, "orthoLeft", void 0);
  23014. __decorate([
  23015. BABYLON.serialize()
  23016. ], Camera.prototype, "orthoRight", void 0);
  23017. __decorate([
  23018. BABYLON.serialize()
  23019. ], Camera.prototype, "orthoBottom", void 0);
  23020. __decorate([
  23021. BABYLON.serialize()
  23022. ], Camera.prototype, "orthoTop", void 0);
  23023. __decorate([
  23024. BABYLON.serialize()
  23025. ], Camera.prototype, "fov", void 0);
  23026. __decorate([
  23027. BABYLON.serialize()
  23028. ], Camera.prototype, "minZ", void 0);
  23029. __decorate([
  23030. BABYLON.serialize()
  23031. ], Camera.prototype, "maxZ", void 0);
  23032. __decorate([
  23033. BABYLON.serialize()
  23034. ], Camera.prototype, "inertia", void 0);
  23035. __decorate([
  23036. BABYLON.serialize()
  23037. ], Camera.prototype, "mode", void 0);
  23038. __decorate([
  23039. BABYLON.serialize()
  23040. ], Camera.prototype, "layerMask", void 0);
  23041. __decorate([
  23042. BABYLON.serialize()
  23043. ], Camera.prototype, "fovMode", void 0);
  23044. __decorate([
  23045. BABYLON.serialize()
  23046. ], Camera.prototype, "cameraRigMode", void 0);
  23047. __decorate([
  23048. BABYLON.serialize()
  23049. ], Camera.prototype, "interaxialDistance", void 0);
  23050. __decorate([
  23051. BABYLON.serialize()
  23052. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23053. return Camera;
  23054. }(BABYLON.Node));
  23055. BABYLON.Camera = Camera;
  23056. })(BABYLON || (BABYLON = {}));
  23057. //# sourceMappingURL=babylon.camera.js.map
  23058. var BABYLON;
  23059. (function (BABYLON) {
  23060. var RenderingManager = /** @class */ (function () {
  23061. function RenderingManager(scene) {
  23062. /**
  23063. * @hidden
  23064. */
  23065. this._useSceneAutoClearSetup = false;
  23066. this._renderingGroups = new Array();
  23067. this._autoClearDepthStencil = {};
  23068. this._customOpaqueSortCompareFn = {};
  23069. this._customAlphaTestSortCompareFn = {};
  23070. this._customTransparentSortCompareFn = {};
  23071. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  23072. this._scene = scene;
  23073. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23074. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23075. }
  23076. }
  23077. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23078. if (depth === void 0) { depth = true; }
  23079. if (stencil === void 0) { stencil = true; }
  23080. if (this._depthStencilBufferAlreadyCleaned) {
  23081. return;
  23082. }
  23083. this._scene.getEngine().clear(null, false, depth, stencil);
  23084. this._depthStencilBufferAlreadyCleaned = true;
  23085. };
  23086. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23087. // Update the observable context (not null as it only goes away on dispose)
  23088. var info = this._renderingGroupInfo;
  23089. info.scene = this._scene;
  23090. info.camera = this._scene.activeCamera;
  23091. // Dispatch sprites
  23092. if (renderSprites) {
  23093. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23094. var manager = this._scene.spriteManagers[index];
  23095. this.dispatchSprites(manager);
  23096. }
  23097. }
  23098. // Render
  23099. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23100. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23101. var renderingGroup = this._renderingGroups[index];
  23102. if (!renderingGroup)
  23103. continue;
  23104. var renderingGroupMask = Math.pow(2, index);
  23105. info.renderingGroupId = index;
  23106. // Before Observable
  23107. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23108. // Clear depth/stencil if needed
  23109. if (RenderingManager.AUTOCLEAR) {
  23110. var autoClear = this._useSceneAutoClearSetup ?
  23111. this._scene.getAutoClearDepthStencilSetup(index) :
  23112. this._autoClearDepthStencil[index];
  23113. if (autoClear && autoClear.autoClear) {
  23114. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23115. }
  23116. }
  23117. // Render
  23118. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  23119. var step = _a[_i];
  23120. step.action(index);
  23121. }
  23122. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23123. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  23124. var step = _c[_b];
  23125. step.action(index);
  23126. }
  23127. // After Observable
  23128. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23129. }
  23130. };
  23131. RenderingManager.prototype.reset = function () {
  23132. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23133. var renderingGroup = this._renderingGroups[index];
  23134. if (renderingGroup) {
  23135. renderingGroup.prepare();
  23136. }
  23137. }
  23138. };
  23139. RenderingManager.prototype.dispose = function () {
  23140. this.freeRenderingGroups();
  23141. this._renderingGroups.length = 0;
  23142. this._renderingGroupInfo = null;
  23143. };
  23144. /**
  23145. * Clear the info related to rendering groups preventing retention points during dispose.
  23146. */
  23147. RenderingManager.prototype.freeRenderingGroups = function () {
  23148. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23149. var renderingGroup = this._renderingGroups[index];
  23150. if (renderingGroup) {
  23151. renderingGroup.dispose();
  23152. }
  23153. }
  23154. };
  23155. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23156. if (this._renderingGroups[renderingGroupId] === undefined) {
  23157. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23158. }
  23159. };
  23160. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23161. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23162. this._prepareRenderingGroup(renderingGroupId);
  23163. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23164. };
  23165. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23166. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23167. this._prepareRenderingGroup(renderingGroupId);
  23168. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23169. };
  23170. /**
  23171. * @param subMesh The submesh to dispatch
  23172. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23173. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23174. */
  23175. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23176. if (mesh === undefined) {
  23177. mesh = subMesh.getMesh();
  23178. }
  23179. var renderingGroupId = mesh.renderingGroupId || 0;
  23180. this._prepareRenderingGroup(renderingGroupId);
  23181. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23182. };
  23183. /**
  23184. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23185. * This allowed control for front to back rendering or reversly depending of the special needs.
  23186. *
  23187. * @param renderingGroupId The rendering group id corresponding to its index
  23188. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23189. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23190. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23191. */
  23192. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23193. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23194. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23195. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23196. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23197. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23198. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23199. if (this._renderingGroups[renderingGroupId]) {
  23200. var group = this._renderingGroups[renderingGroupId];
  23201. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23202. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23203. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23204. }
  23205. };
  23206. /**
  23207. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23208. *
  23209. * @param renderingGroupId The rendering group id corresponding to its index
  23210. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23211. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23212. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23213. */
  23214. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23215. if (depth === void 0) { depth = true; }
  23216. if (stencil === void 0) { stencil = true; }
  23217. this._autoClearDepthStencil[renderingGroupId] = {
  23218. autoClear: autoClearDepthStencil,
  23219. depth: depth,
  23220. stencil: stencil
  23221. };
  23222. };
  23223. /**
  23224. * Gets the current auto clear configuration for one rendering group of the rendering
  23225. * manager.
  23226. * @param index the rendering group index to get the information for
  23227. * @returns The auto clear setup for the requested rendering group
  23228. */
  23229. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  23230. return this._autoClearDepthStencil[index];
  23231. };
  23232. /**
  23233. * The max id used for rendering groups (not included)
  23234. */
  23235. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23236. /**
  23237. * The min id used for rendering groups (included)
  23238. */
  23239. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23240. /**
  23241. * Used to globally prevent autoclearing scenes.
  23242. */
  23243. RenderingManager.AUTOCLEAR = true;
  23244. return RenderingManager;
  23245. }());
  23246. BABYLON.RenderingManager = RenderingManager;
  23247. })(BABYLON || (BABYLON = {}));
  23248. //# sourceMappingURL=babylon.renderingManager.js.map
  23249. var BABYLON;
  23250. (function (BABYLON) {
  23251. var RenderingGroup = /** @class */ (function () {
  23252. /**
  23253. * Creates a new rendering group.
  23254. * @param index The rendering group index
  23255. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23256. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23257. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23258. */
  23259. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23260. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23261. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23262. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23263. this.index = index;
  23264. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23265. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23266. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23267. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23268. this._particleSystems = new BABYLON.SmartArray(256);
  23269. this._spriteManagers = new BABYLON.SmartArray(256);
  23270. this._edgesRenderers = new BABYLON.SmartArray(16);
  23271. this._scene = scene;
  23272. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23273. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23274. this.transparentSortCompareFn = transparentSortCompareFn;
  23275. }
  23276. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23277. /**
  23278. * Set the opaque sort comparison function.
  23279. * If null the sub meshes will be render in the order they were created
  23280. */
  23281. set: function (value) {
  23282. this._opaqueSortCompareFn = value;
  23283. if (value) {
  23284. this._renderOpaque = this.renderOpaqueSorted;
  23285. }
  23286. else {
  23287. this._renderOpaque = RenderingGroup.renderUnsorted;
  23288. }
  23289. },
  23290. enumerable: true,
  23291. configurable: true
  23292. });
  23293. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23294. /**
  23295. * Set the alpha test sort comparison function.
  23296. * If null the sub meshes will be render in the order they were created
  23297. */
  23298. set: function (value) {
  23299. this._alphaTestSortCompareFn = value;
  23300. if (value) {
  23301. this._renderAlphaTest = this.renderAlphaTestSorted;
  23302. }
  23303. else {
  23304. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23305. }
  23306. },
  23307. enumerable: true,
  23308. configurable: true
  23309. });
  23310. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23311. /**
  23312. * Set the transparent sort comparison function.
  23313. * If null the sub meshes will be render in the order they were created
  23314. */
  23315. set: function (value) {
  23316. if (value) {
  23317. this._transparentSortCompareFn = value;
  23318. }
  23319. else {
  23320. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23321. }
  23322. this._renderTransparent = this.renderTransparentSorted;
  23323. },
  23324. enumerable: true,
  23325. configurable: true
  23326. });
  23327. /**
  23328. * Render all the sub meshes contained in the group.
  23329. * @param customRenderFunction Used to override the default render behaviour of the group.
  23330. * @returns true if rendered some submeshes.
  23331. */
  23332. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23333. if (customRenderFunction) {
  23334. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23335. return;
  23336. }
  23337. var engine = this._scene.getEngine();
  23338. // Depth only
  23339. if (this._depthOnlySubMeshes.length !== 0) {
  23340. engine.setColorWrite(false);
  23341. this._renderAlphaTest(this._depthOnlySubMeshes);
  23342. engine.setColorWrite(true);
  23343. }
  23344. // Opaque
  23345. if (this._opaqueSubMeshes.length !== 0) {
  23346. this._renderOpaque(this._opaqueSubMeshes);
  23347. }
  23348. // Alpha test
  23349. if (this._alphaTestSubMeshes.length !== 0) {
  23350. this._renderAlphaTest(this._alphaTestSubMeshes);
  23351. }
  23352. var stencilState = engine.getStencilBuffer();
  23353. engine.setStencilBuffer(false);
  23354. // Sprites
  23355. if (renderSprites) {
  23356. this._renderSprites();
  23357. }
  23358. // Particles
  23359. if (renderParticles) {
  23360. this._renderParticles(activeMeshes);
  23361. }
  23362. if (this.onBeforeTransparentRendering) {
  23363. this.onBeforeTransparentRendering();
  23364. }
  23365. // Transparent
  23366. if (this._transparentSubMeshes.length !== 0) {
  23367. this._renderTransparent(this._transparentSubMeshes);
  23368. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23369. }
  23370. // Set back stencil to false in case it changes before the edge renderer.
  23371. engine.setStencilBuffer(false);
  23372. // Edges
  23373. if (this._edgesRenderers.length) {
  23374. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23375. this._edgesRenderers.data[edgesRendererIndex].render();
  23376. }
  23377. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23378. }
  23379. // Restore Stencil state.
  23380. engine.setStencilBuffer(stencilState);
  23381. };
  23382. /**
  23383. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23384. * @param subMeshes The submeshes to render
  23385. */
  23386. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23387. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23388. };
  23389. /**
  23390. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23391. * @param subMeshes The submeshes to render
  23392. */
  23393. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23394. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23395. };
  23396. /**
  23397. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23398. * @param subMeshes The submeshes to render
  23399. */
  23400. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23401. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23402. };
  23403. /**
  23404. * Renders the submeshes in a specified order.
  23405. * @param subMeshes The submeshes to sort before render
  23406. * @param sortCompareFn The comparison function use to sort
  23407. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23408. * @param transparent Specifies to activate blending if true
  23409. */
  23410. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23411. var subIndex = 0;
  23412. var subMesh;
  23413. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23414. for (; subIndex < subMeshes.length; subIndex++) {
  23415. subMesh = subMeshes.data[subIndex];
  23416. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23417. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23418. }
  23419. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23420. if (sortCompareFn) {
  23421. sortedArray.sort(sortCompareFn);
  23422. }
  23423. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23424. subMesh = sortedArray[subIndex];
  23425. if (transparent) {
  23426. var material = subMesh.getMaterial();
  23427. if (material && material.needDepthPrePass) {
  23428. var engine = material.getScene().getEngine();
  23429. engine.setColorWrite(false);
  23430. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23431. subMesh.render(false);
  23432. engine.setColorWrite(true);
  23433. }
  23434. }
  23435. subMesh.render(transparent);
  23436. }
  23437. };
  23438. /**
  23439. * Renders the submeshes in the order they were dispatched (no sort applied).
  23440. * @param subMeshes The submeshes to render
  23441. */
  23442. RenderingGroup.renderUnsorted = function (subMeshes) {
  23443. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23444. var submesh = subMeshes.data[subIndex];
  23445. submesh.render(false);
  23446. }
  23447. };
  23448. /**
  23449. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23450. * are rendered back to front if in the same alpha index.
  23451. *
  23452. * @param a The first submesh
  23453. * @param b The second submesh
  23454. * @returns The result of the comparison
  23455. */
  23456. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23457. // Alpha index first
  23458. if (a._alphaIndex > b._alphaIndex) {
  23459. return 1;
  23460. }
  23461. if (a._alphaIndex < b._alphaIndex) {
  23462. return -1;
  23463. }
  23464. // Then distance to camera
  23465. return RenderingGroup.backToFrontSortCompare(a, b);
  23466. };
  23467. /**
  23468. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23469. * are rendered back to front.
  23470. *
  23471. * @param a The first submesh
  23472. * @param b The second submesh
  23473. * @returns The result of the comparison
  23474. */
  23475. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23476. // Then distance to camera
  23477. if (a._distanceToCamera < b._distanceToCamera) {
  23478. return 1;
  23479. }
  23480. if (a._distanceToCamera > b._distanceToCamera) {
  23481. return -1;
  23482. }
  23483. return 0;
  23484. };
  23485. /**
  23486. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23487. * are rendered front to back (prevent overdraw).
  23488. *
  23489. * @param a The first submesh
  23490. * @param b The second submesh
  23491. * @returns The result of the comparison
  23492. */
  23493. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23494. // Then distance to camera
  23495. if (a._distanceToCamera < b._distanceToCamera) {
  23496. return -1;
  23497. }
  23498. if (a._distanceToCamera > b._distanceToCamera) {
  23499. return 1;
  23500. }
  23501. return 0;
  23502. };
  23503. /**
  23504. * Resets the different lists of submeshes to prepare a new frame.
  23505. */
  23506. RenderingGroup.prototype.prepare = function () {
  23507. this._opaqueSubMeshes.reset();
  23508. this._transparentSubMeshes.reset();
  23509. this._alphaTestSubMeshes.reset();
  23510. this._depthOnlySubMeshes.reset();
  23511. this._particleSystems.reset();
  23512. this._spriteManagers.reset();
  23513. this._edgesRenderers.reset();
  23514. };
  23515. RenderingGroup.prototype.dispose = function () {
  23516. this._opaqueSubMeshes.dispose();
  23517. this._transparentSubMeshes.dispose();
  23518. this._alphaTestSubMeshes.dispose();
  23519. this._depthOnlySubMeshes.dispose();
  23520. this._particleSystems.dispose();
  23521. this._spriteManagers.dispose();
  23522. this._edgesRenderers.dispose();
  23523. };
  23524. /**
  23525. * Inserts the submesh in its correct queue depending on its material.
  23526. * @param subMesh The submesh to dispatch
  23527. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23528. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23529. */
  23530. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23531. // Get mesh and materials if not provided
  23532. if (mesh === undefined) {
  23533. mesh = subMesh.getMesh();
  23534. }
  23535. if (material === undefined) {
  23536. material = subMesh.getMaterial();
  23537. }
  23538. if (material === null || material === undefined) {
  23539. return;
  23540. }
  23541. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23542. this._transparentSubMeshes.push(subMesh);
  23543. }
  23544. else if (material.needAlphaTesting()) { // Alpha test
  23545. if (material.needDepthPrePass) {
  23546. this._depthOnlySubMeshes.push(subMesh);
  23547. }
  23548. this._alphaTestSubMeshes.push(subMesh);
  23549. }
  23550. else {
  23551. if (material.needDepthPrePass) {
  23552. this._depthOnlySubMeshes.push(subMesh);
  23553. }
  23554. this._opaqueSubMeshes.push(subMesh); // Opaque
  23555. }
  23556. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23557. this._edgesRenderers.push(mesh._edgesRenderer);
  23558. }
  23559. };
  23560. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23561. this._spriteManagers.push(spriteManager);
  23562. };
  23563. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23564. this._particleSystems.push(particleSystem);
  23565. };
  23566. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23567. if (this._particleSystems.length === 0) {
  23568. return;
  23569. }
  23570. // Particles
  23571. var activeCamera = this._scene.activeCamera;
  23572. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23573. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23574. var particleSystem = this._particleSystems.data[particleIndex];
  23575. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23576. continue;
  23577. }
  23578. var emitter = particleSystem.emitter;
  23579. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23580. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23581. }
  23582. }
  23583. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23584. };
  23585. RenderingGroup.prototype._renderSprites = function () {
  23586. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23587. return;
  23588. }
  23589. // Sprites
  23590. var activeCamera = this._scene.activeCamera;
  23591. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23592. for (var id = 0; id < this._spriteManagers.length; id++) {
  23593. var spriteManager = this._spriteManagers.data[id];
  23594. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23595. spriteManager.render();
  23596. }
  23597. }
  23598. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23599. };
  23600. return RenderingGroup;
  23601. }());
  23602. BABYLON.RenderingGroup = RenderingGroup;
  23603. })(BABYLON || (BABYLON = {}));
  23604. //# sourceMappingURL=babylon.renderingGroup.js.map
  23605. var BABYLON;
  23606. (function (BABYLON) {
  23607. /**
  23608. * Groups all the scene component constants in one place to ease maintenance.
  23609. * @hidden
  23610. */
  23611. var SceneComponentConstants = /** @class */ (function () {
  23612. function SceneComponentConstants() {
  23613. }
  23614. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  23615. SceneComponentConstants.NAME_LAYER = "Layer";
  23616. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  23617. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  23618. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  23619. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  23620. SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue";
  23621. SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer";
  23622. SceneComponentConstants.NAME_DEPTHRENDERER = "DepthRenderer";
  23623. SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager";
  23624. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  23625. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23626. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  23627. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23628. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  23629. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  23630. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  23631. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  23632. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;
  23633. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1;
  23634. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  23635. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  23636. SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER = 2;
  23637. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 3;
  23638. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 4;
  23639. SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 0;
  23640. SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 1;
  23641. SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 2;
  23642. SceneComponentConstants.STEP_REBUILDGEOMETRY_POSTPROCESSRENDERPIPELINEMANAGER = 0;
  23643. return SceneComponentConstants;
  23644. }());
  23645. BABYLON.SceneComponentConstants = SceneComponentConstants;
  23646. /**
  23647. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  23648. * @hidden
  23649. */
  23650. var Stage = /** @class */ (function (_super) {
  23651. __extends(Stage, _super);
  23652. /**
  23653. * Hide ctor from the rest of the world.
  23654. * @param items The items to add.
  23655. */
  23656. function Stage(items) {
  23657. return _super.apply(this, items) || this;
  23658. }
  23659. /**
  23660. * Creates a new Stage.
  23661. * @returns A new instance of a Stage
  23662. */
  23663. Stage.Create = function () {
  23664. return Object.create(Stage.prototype);
  23665. };
  23666. /**
  23667. * Registers a step in an ordered way in the targeted stage.
  23668. * @param index Defines the position to register the step in
  23669. * @param component Defines the component attached to the step
  23670. * @param action Defines the action to launch during the step
  23671. */
  23672. Stage.prototype.registerStep = function (index, component, action) {
  23673. var i = 0;
  23674. var maxIndex = Number.MAX_VALUE;
  23675. for (; i < this.length && i < maxIndex; i++) {
  23676. var step = this[i];
  23677. maxIndex = step.index;
  23678. }
  23679. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  23680. };
  23681. /**
  23682. * Clears all the steps from the stage.
  23683. */
  23684. Stage.prototype.clear = function () {
  23685. this.length = 0;
  23686. };
  23687. return Stage;
  23688. }(Array));
  23689. BABYLON.Stage = Stage;
  23690. })(BABYLON || (BABYLON = {}));
  23691. //# sourceMappingURL=babylon.sceneComponent.js.map
  23692. var BABYLON;
  23693. (function (BABYLON) {
  23694. /**
  23695. * Base class of the scene acting as a container for the different elements composing a scene.
  23696. * This class is dynamically extended by the different components of the scene increasing
  23697. * flexibility and reducing coupling
  23698. */
  23699. var AbstractScene = /** @class */ (function () {
  23700. function AbstractScene() {
  23701. /** All of the cameras added to this scene
  23702. * @see http://doc.babylonjs.com/babylon101/cameras
  23703. */
  23704. this.cameras = new Array();
  23705. /**
  23706. * All of the lights added to this scene
  23707. * @see http://doc.babylonjs.com/babylon101/lights
  23708. */
  23709. this.lights = new Array();
  23710. /**
  23711. * All of the (abstract) meshes added to this scene
  23712. */
  23713. this.meshes = new Array();
  23714. /**
  23715. * The list of skeletons added to the scene
  23716. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23717. */
  23718. this.skeletons = new Array();
  23719. /**
  23720. * All of the particle systems added to this scene
  23721. * @see http://doc.babylonjs.com/babylon101/particles
  23722. */
  23723. this.particleSystems = new Array();
  23724. /**
  23725. * Gets a list of Animations associated with the scene
  23726. */
  23727. this.animations = [];
  23728. /**
  23729. * All of the animation groups added to this scene
  23730. * @see http://doc.babylonjs.com/how_to/group
  23731. */
  23732. this.animationGroups = new Array();
  23733. /**
  23734. * All of the multi-materials added to this scene
  23735. * @see http://doc.babylonjs.com/how_to/multi_materials
  23736. */
  23737. this.multiMaterials = new Array();
  23738. /**
  23739. * All of the materials added to this scene
  23740. * @see http://doc.babylonjs.com/babylon101/materials
  23741. */
  23742. this.materials = new Array();
  23743. /**
  23744. * The list of morph target managers added to the scene
  23745. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23746. */
  23747. this.morphTargetManagers = new Array();
  23748. /**
  23749. * The list of geometries used in the scene.
  23750. */
  23751. this.geometries = new Array();
  23752. /**
  23753. * All of the tranform nodes added to this scene
  23754. * @see http://doc.babylonjs.com/how_to/transformnode
  23755. */
  23756. this.transformNodes = new Array();
  23757. /**
  23758. * ActionManagers available on the scene.
  23759. */
  23760. this.actionManagers = new Array();
  23761. /**
  23762. * Sounds to keep.
  23763. */
  23764. this.sounds = new Array();
  23765. /**
  23766. * Textures to keep.
  23767. */
  23768. this.textures = new Array();
  23769. }
  23770. /**
  23771. * Adds a parser in the list of available ones
  23772. * @param name Defines the name of the parser
  23773. * @param parser Defines the parser to add
  23774. */
  23775. AbstractScene.AddParser = function (name, parser) {
  23776. this._BabylonFileParsers[name] = parser;
  23777. };
  23778. /**
  23779. * Gets a general parser from the list of avaialble ones
  23780. * @param name Defines the name of the parser
  23781. * @returns the requested parser or null
  23782. */
  23783. AbstractScene.GetParser = function (name) {
  23784. if (this._BabylonFileParsers[name]) {
  23785. return this._BabylonFileParsers[name];
  23786. }
  23787. return null;
  23788. };
  23789. /**
  23790. * Adds n individual parser in the list of available ones
  23791. * @param name Defines the name of the parser
  23792. * @param parser Defines the parser to add
  23793. */
  23794. AbstractScene.AddIndividualParser = function (name, parser) {
  23795. this._IndividualBabylonFileParsers[name] = parser;
  23796. };
  23797. /**
  23798. * Gets an individual parser from the list of avaialble ones
  23799. * @param name Defines the name of the parser
  23800. * @returns the requested parser or null
  23801. */
  23802. AbstractScene.GetIndividualParser = function (name) {
  23803. if (this._IndividualBabylonFileParsers[name]) {
  23804. return this._IndividualBabylonFileParsers[name];
  23805. }
  23806. return null;
  23807. };
  23808. /**
  23809. * Parser json data and populate both a scene and its associated container object
  23810. * @param jsonData Defines the data to parse
  23811. * @param scene Defines the scene to parse the data for
  23812. * @param container Defines the container attached to the parsing sequence
  23813. * @param rootUrl Defines the root url of the data
  23814. */
  23815. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  23816. for (var parserName in this._BabylonFileParsers) {
  23817. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  23818. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  23819. }
  23820. }
  23821. };
  23822. /**
  23823. * Stores the list of available parsers in the application.
  23824. */
  23825. AbstractScene._BabylonFileParsers = {};
  23826. /**
  23827. * Stores the list of available individual parsers in the application.
  23828. */
  23829. AbstractScene._IndividualBabylonFileParsers = {};
  23830. return AbstractScene;
  23831. }());
  23832. BABYLON.AbstractScene = AbstractScene;
  23833. })(BABYLON || (BABYLON = {}));
  23834. //# sourceMappingURL=babylon.abstractScene.js.map
  23835. var BABYLON;
  23836. (function (BABYLON) {
  23837. /** @hidden */
  23838. var ClickInfo = /** @class */ (function () {
  23839. function ClickInfo() {
  23840. this._singleClick = false;
  23841. this._doubleClick = false;
  23842. this._hasSwiped = false;
  23843. this._ignore = false;
  23844. }
  23845. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23846. get: function () {
  23847. return this._singleClick;
  23848. },
  23849. set: function (b) {
  23850. this._singleClick = b;
  23851. },
  23852. enumerable: true,
  23853. configurable: true
  23854. });
  23855. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23856. get: function () {
  23857. return this._doubleClick;
  23858. },
  23859. set: function (b) {
  23860. this._doubleClick = b;
  23861. },
  23862. enumerable: true,
  23863. configurable: true
  23864. });
  23865. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23866. get: function () {
  23867. return this._hasSwiped;
  23868. },
  23869. set: function (b) {
  23870. this._hasSwiped = b;
  23871. },
  23872. enumerable: true,
  23873. configurable: true
  23874. });
  23875. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23876. get: function () {
  23877. return this._ignore;
  23878. },
  23879. set: function (b) {
  23880. this._ignore = b;
  23881. },
  23882. enumerable: true,
  23883. configurable: true
  23884. });
  23885. return ClickInfo;
  23886. }());
  23887. /**
  23888. * This class is used by the onRenderingGroupObservable
  23889. */
  23890. var RenderingGroupInfo = /** @class */ (function () {
  23891. function RenderingGroupInfo() {
  23892. }
  23893. return RenderingGroupInfo;
  23894. }());
  23895. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23896. /**
  23897. * Represents a scene to be rendered by the engine.
  23898. * @see http://doc.babylonjs.com/features/scene
  23899. */
  23900. var Scene = /** @class */ (function (_super) {
  23901. __extends(Scene, _super);
  23902. /**
  23903. * Creates a new Scene
  23904. * @param engine defines the engine to use to render this scene
  23905. */
  23906. function Scene(engine) {
  23907. var _this = _super.call(this) || this;
  23908. // Members
  23909. /**
  23910. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23911. */
  23912. _this.autoClear = true;
  23913. /**
  23914. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23915. */
  23916. _this.autoClearDepthAndStencil = true;
  23917. /**
  23918. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23919. */
  23920. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23921. /**
  23922. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23923. */
  23924. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23925. _this._forceWireframe = false;
  23926. _this._forcePointsCloud = false;
  23927. /**
  23928. * Gets or sets a boolean indicating if animations are enabled
  23929. */
  23930. _this.animationsEnabled = true;
  23931. _this._animationPropertiesOverride = null;
  23932. /**
  23933. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23934. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23935. */
  23936. _this.useConstantAnimationDeltaTime = false;
  23937. /**
  23938. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23939. * Please note that it requires to run a ray cast through the scene on every frame
  23940. */
  23941. _this.constantlyUpdateMeshUnderPointer = false;
  23942. /**
  23943. * Defines the HTML cursor to use when hovering over interactive elements
  23944. */
  23945. _this.hoverCursor = "pointer";
  23946. /**
  23947. * Defines the HTML default cursor to use (empty by default)
  23948. */
  23949. _this.defaultCursor = "";
  23950. /**
  23951. * This is used to call preventDefault() on pointer down
  23952. * in order to block unwanted artifacts like system double clicks
  23953. */
  23954. _this.preventDefaultOnPointerDown = true;
  23955. // Metadata
  23956. /**
  23957. * Gets or sets user defined metadata
  23958. */
  23959. _this.metadata = null;
  23960. /**
  23961. * Use this array to add regular expressions used to disable offline support for specific urls
  23962. */
  23963. _this.disableOfflineSupportExceptionRules = new Array();
  23964. /**
  23965. * An event triggered when the scene is disposed.
  23966. */
  23967. _this.onDisposeObservable = new BABYLON.Observable();
  23968. _this._onDisposeObserver = null;
  23969. /**
  23970. * An event triggered before rendering the scene (right after animations and physics)
  23971. */
  23972. _this.onBeforeRenderObservable = new BABYLON.Observable();
  23973. _this._onBeforeRenderObserver = null;
  23974. /**
  23975. * An event triggered after rendering the scene
  23976. */
  23977. _this.onAfterRenderObservable = new BABYLON.Observable();
  23978. _this._onAfterRenderObserver = null;
  23979. /**
  23980. * An event triggered before animating the scene
  23981. */
  23982. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23983. /**
  23984. * An event triggered after animations processing
  23985. */
  23986. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  23987. /**
  23988. * An event triggered before draw calls are ready to be sent
  23989. */
  23990. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23991. /**
  23992. * An event triggered after draw calls have been sent
  23993. */
  23994. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23995. /**
  23996. * An event triggered when physic simulation is about to be run
  23997. */
  23998. _this.onBeforePhysicsObservable = new BABYLON.Observable();
  23999. /**
  24000. * An event triggered when physic simulation has been done
  24001. */
  24002. _this.onAfterPhysicsObservable = new BABYLON.Observable();
  24003. /**
  24004. * An event triggered when the scene is ready
  24005. */
  24006. _this.onReadyObservable = new BABYLON.Observable();
  24007. /**
  24008. * An event triggered before rendering a camera
  24009. */
  24010. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  24011. _this._onBeforeCameraRenderObserver = null;
  24012. /**
  24013. * An event triggered after rendering a camera
  24014. */
  24015. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  24016. _this._onAfterCameraRenderObserver = null;
  24017. /**
  24018. * An event triggered when active meshes evaluation is about to start
  24019. */
  24020. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24021. /**
  24022. * An event triggered when active meshes evaluation is done
  24023. */
  24024. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24025. /**
  24026. * An event triggered when particles rendering is about to start
  24027. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24028. */
  24029. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  24030. /**
  24031. * An event triggered when particles rendering is done
  24032. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24033. */
  24034. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  24035. /**
  24036. * An event triggered when sprites rendering is about to start
  24037. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  24038. */
  24039. _this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  24040. /**
  24041. * An event triggered when sprites rendering is done
  24042. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  24043. */
  24044. _this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  24045. /**
  24046. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  24047. */
  24048. _this.onDataLoadedObservable = new BABYLON.Observable();
  24049. /**
  24050. * An event triggered when a camera is created
  24051. */
  24052. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  24053. /**
  24054. * An event triggered when a camera is removed
  24055. */
  24056. _this.onCameraRemovedObservable = new BABYLON.Observable();
  24057. /**
  24058. * An event triggered when a light is created
  24059. */
  24060. _this.onNewLightAddedObservable = new BABYLON.Observable();
  24061. /**
  24062. * An event triggered when a light is removed
  24063. */
  24064. _this.onLightRemovedObservable = new BABYLON.Observable();
  24065. /**
  24066. * An event triggered when a geometry is created
  24067. */
  24068. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  24069. /**
  24070. * An event triggered when a geometry is removed
  24071. */
  24072. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  24073. /**
  24074. * An event triggered when a transform node is created
  24075. */
  24076. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  24077. /**
  24078. * An event triggered when a transform node is removed
  24079. */
  24080. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  24081. /**
  24082. * An event triggered when a mesh is created
  24083. */
  24084. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  24085. /**
  24086. * An event triggered when a mesh is removed
  24087. */
  24088. _this.onMeshRemovedObservable = new BABYLON.Observable();
  24089. /**
  24090. * An event triggered when render targets are about to be rendered
  24091. * Can happen multiple times per frame.
  24092. */
  24093. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  24094. /**
  24095. * An event triggered when render targets were rendered.
  24096. * Can happen multiple times per frame.
  24097. */
  24098. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  24099. /**
  24100. * An event triggered before calculating deterministic simulation step
  24101. */
  24102. _this.onBeforeStepObservable = new BABYLON.Observable();
  24103. /**
  24104. * An event triggered after calculating deterministic simulation step
  24105. */
  24106. _this.onAfterStepObservable = new BABYLON.Observable();
  24107. /**
  24108. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  24109. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24110. * 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)
  24111. */
  24112. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  24113. /**
  24114. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  24115. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24116. * 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)
  24117. */
  24118. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  24119. // Animations
  24120. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  24121. /**
  24122. * 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).
  24123. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  24124. */
  24125. _this.onPrePointerObservable = new BABYLON.Observable();
  24126. /**
  24127. * Observable event triggered each time an input event is received from the rendering canvas
  24128. */
  24129. _this.onPointerObservable = new BABYLON.Observable();
  24130. _this._meshPickProceed = false;
  24131. _this._currentPickResult = null;
  24132. _this._previousPickResult = null;
  24133. _this._totalPointersPressed = 0;
  24134. _this._doubleClickOccured = false;
  24135. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  24136. _this.cameraToUseForPointers = null;
  24137. _this._pointerX = 0;
  24138. _this._pointerY = 0;
  24139. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  24140. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  24141. _this._startingPointerTime = 0;
  24142. _this._previousStartingPointerTime = 0;
  24143. _this._pointerCaptures = {};
  24144. // Deterministic lockstep
  24145. _this._timeAccumulator = 0;
  24146. _this._currentStepId = 0;
  24147. _this._currentInternalStep = 0;
  24148. // Keyboard
  24149. /**
  24150. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  24151. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  24152. */
  24153. _this.onPreKeyboardObservable = new BABYLON.Observable();
  24154. /**
  24155. * Observable event triggered each time an keyboard event is received from the hosting window
  24156. */
  24157. _this.onKeyboardObservable = new BABYLON.Observable();
  24158. // Coordinates system
  24159. _this._useRightHandedSystem = false;
  24160. // Fog
  24161. _this._fogEnabled = true;
  24162. _this._fogMode = Scene.FOGMODE_NONE;
  24163. /**
  24164. * Gets or sets the fog color to use
  24165. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24166. */
  24167. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24168. /**
  24169. * Gets or sets the fog density to use
  24170. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24171. */
  24172. _this.fogDensity = 0.1;
  24173. /**
  24174. * Gets or sets the fog start distance to use
  24175. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24176. */
  24177. _this.fogStart = 0;
  24178. /**
  24179. * Gets or sets the fog end distance to use
  24180. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24181. */
  24182. _this.fogEnd = 1000.0;
  24183. // Lights
  24184. _this._shadowsEnabled = true;
  24185. _this._lightsEnabled = true;
  24186. /** All of the active cameras added to this scene. */
  24187. _this.activeCameras = new Array();
  24188. // Textures
  24189. _this._texturesEnabled = true;
  24190. // Particles
  24191. /**
  24192. * Gets or sets a boolean indicating if particles are enabled on this scene
  24193. */
  24194. _this.particlesEnabled = true;
  24195. // Sprites
  24196. /**
  24197. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24198. */
  24199. _this.spritesEnabled = true;
  24200. /**
  24201. * All of the sprite managers added to this scene
  24202. * @see http://doc.babylonjs.com/babylon101/sprites
  24203. */
  24204. _this.spriteManagers = new Array();
  24205. // Skeletons
  24206. _this._skeletonsEnabled = true;
  24207. // Lens flares
  24208. /**
  24209. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24210. */
  24211. _this.lensFlaresEnabled = true;
  24212. // Collisions
  24213. /**
  24214. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24215. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24216. */
  24217. _this.collisionsEnabled = true;
  24218. /**
  24219. * Defines the gravity applied to this scene (used only for collisions)
  24220. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24221. */
  24222. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24223. // Postprocesses
  24224. /**
  24225. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24226. */
  24227. _this.postProcessesEnabled = true;
  24228. /**
  24229. * The list of postprocesses added to the scene
  24230. */
  24231. _this.postProcesses = new Array();
  24232. // Customs render targets
  24233. /**
  24234. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24235. */
  24236. _this.renderTargetsEnabled = true;
  24237. /**
  24238. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24239. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24240. */
  24241. _this.dumpNextRenderTargets = false;
  24242. /**
  24243. * The list of user defined render targets added to the scene
  24244. */
  24245. _this.customRenderTargets = new Array();
  24246. /**
  24247. * Gets the list of meshes imported to the scene through SceneLoader
  24248. */
  24249. _this.importedMeshesFiles = new Array();
  24250. // Probes
  24251. /**
  24252. * Gets or sets a boolean indicating if probes are enabled on this scene
  24253. */
  24254. _this.probesEnabled = true;
  24255. /**
  24256. * The list of reflection probes added to the scene
  24257. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24258. */
  24259. _this.reflectionProbes = new Array();
  24260. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24261. // Procedural textures
  24262. /**
  24263. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24264. */
  24265. _this.proceduralTexturesEnabled = true;
  24266. /**
  24267. * The list of procedural textures added to the scene
  24268. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24269. */
  24270. _this.proceduralTextures = new Array();
  24271. /**
  24272. * The list of sound tracks added to the scene
  24273. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24274. */
  24275. _this.soundTracks = new Array();
  24276. _this._audioEnabled = true;
  24277. _this._headphone = false;
  24278. // Performance counters
  24279. _this._totalVertices = new BABYLON.PerfCounter();
  24280. /** @hidden */
  24281. _this._activeIndices = new BABYLON.PerfCounter();
  24282. /** @hidden */
  24283. _this._activeParticles = new BABYLON.PerfCounter();
  24284. /** @hidden */
  24285. _this._activeBones = new BABYLON.PerfCounter();
  24286. _this._animationTime = 0;
  24287. /**
  24288. * Gets or sets a general scale for animation speed
  24289. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24290. */
  24291. _this.animationTimeScale = 1;
  24292. _this._renderId = 0;
  24293. _this._executeWhenReadyTimeoutId = -1;
  24294. _this._intermediateRendering = false;
  24295. _this._viewUpdateFlag = -1;
  24296. _this._projectionUpdateFlag = -1;
  24297. _this._alternateViewUpdateFlag = -1;
  24298. _this._alternateProjectionUpdateFlag = -1;
  24299. /** @hidden */
  24300. _this._toBeDisposed = new BABYLON.SmartArray(256);
  24301. _this._activeRequests = new Array();
  24302. _this._pendingData = new Array();
  24303. _this._isDisposed = false;
  24304. /**
  24305. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24306. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24307. */
  24308. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  24309. _this._activeMeshes = new BABYLON.SmartArray(256);
  24310. _this._processedMaterials = new BABYLON.SmartArray(256);
  24311. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24312. /** @hidden */
  24313. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  24314. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24315. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24316. /** @hidden */
  24317. _this._activeAnimatables = new Array();
  24318. _this._transformMatrix = BABYLON.Matrix.Zero();
  24319. _this._useAlternateCameraConfiguration = false;
  24320. _this._alternateRendering = false;
  24321. /**
  24322. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24323. * This is useful if there are more lights that the maximum simulteanous authorized
  24324. */
  24325. _this.requireLightSorting = false;
  24326. /**
  24327. * @hidden
  24328. * Backing store of defined scene components.
  24329. */
  24330. _this._components = [];
  24331. /**
  24332. * @hidden
  24333. * Backing store of defined scene components.
  24334. */
  24335. _this._serializableComponents = [];
  24336. /**
  24337. * List of components to register on the next registration step.
  24338. */
  24339. _this._transientComponents = [];
  24340. /**
  24341. * @hidden
  24342. * Defines the actions happening before camera updates.
  24343. */
  24344. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  24345. /**
  24346. * @hidden
  24347. * Defines the actions happening before camera updates.
  24348. */
  24349. _this._gatherRenderTargetsStage = BABYLON.Stage.Create();
  24350. /**
  24351. * @hidden
  24352. * Defines the actions happening during the per mesh ready checks.
  24353. */
  24354. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  24355. /**
  24356. * @hidden
  24357. * Defines the actions happening before evaluate active mesh checks.
  24358. */
  24359. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  24360. /**
  24361. * @hidden
  24362. * Defines the actions happening during the evaluate sub mesh checks.
  24363. */
  24364. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  24365. /**
  24366. * @hidden
  24367. * Defines the actions happening during the active mesh stage.
  24368. */
  24369. _this._activeMeshStage = BABYLON.Stage.Create();
  24370. /**
  24371. * @hidden
  24372. * Defines the actions happening during the per camera render target step.
  24373. */
  24374. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  24375. /**
  24376. * @hidden
  24377. * Defines the actions happening just before the active camera is drawing.
  24378. */
  24379. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  24380. /**
  24381. * Defines the actions happening just before a rendering group is drawing.
  24382. */
  24383. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  24384. /**
  24385. * @hidden
  24386. * Defines the actions happening just after a rendering group has been drawn.
  24387. */
  24388. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  24389. /**
  24390. * @hidden
  24391. * Defines the actions happening just after the active camera has been drawn.
  24392. */
  24393. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  24394. /**
  24395. * @hidden
  24396. * Defines the actions happening when Geometries are rebuilding.
  24397. */
  24398. _this._rebuildGeometryStage = BABYLON.Stage.Create();
  24399. _this._activeMeshesFrozen = false;
  24400. /** @hidden */
  24401. _this._allowPostProcessClear = true;
  24402. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24403. /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
  24404. _this.blockMaterialDirtyMechanism = false;
  24405. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24406. _this._engine.scenes.push(_this);
  24407. _this._uid = null;
  24408. _this._renderingManager = new BABYLON.RenderingManager(_this);
  24409. if (BABYLON.PostProcessManager) {
  24410. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  24411. }
  24412. if (BABYLON.OutlineRenderer) {
  24413. _this._outlineRenderer = new BABYLON.OutlineRenderer(_this);
  24414. }
  24415. if (BABYLON.Tools.IsWindowObjectExist()) {
  24416. _this.attachControl();
  24417. }
  24418. //collision coordinator initialization. For now legacy per default.
  24419. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24420. // Uniform Buffer
  24421. _this._createUbo();
  24422. // Default Image processing definition
  24423. if (BABYLON.ImageProcessingConfiguration) {
  24424. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24425. }
  24426. return _this;
  24427. }
  24428. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24429. /**
  24430. * Texture used in all pbr material as the reflection texture.
  24431. * As in the majority of the scene they are the same (exception for multi room and so on),
  24432. * this is easier to reference from here than from all the materials.
  24433. */
  24434. get: function () {
  24435. return this._environmentTexture;
  24436. },
  24437. /**
  24438. * Texture used in all pbr material as the reflection texture.
  24439. * As in the majority of the scene they are the same (exception for multi room and so on),
  24440. * this is easier to set here than in all the materials.
  24441. */
  24442. set: function (value) {
  24443. if (this._environmentTexture === value) {
  24444. return;
  24445. }
  24446. this._environmentTexture = value;
  24447. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24448. },
  24449. enumerable: true,
  24450. configurable: true
  24451. });
  24452. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24453. /**
  24454. * Default image processing configuration used either in the rendering
  24455. * Forward main pass or through the imageProcessingPostProcess if present.
  24456. * As in the majority of the scene they are the same (exception for multi camera),
  24457. * this is easier to reference from here than from all the materials and post process.
  24458. *
  24459. * No setter as we it is a shared configuration, you can set the values instead.
  24460. */
  24461. get: function () {
  24462. return this._imageProcessingConfiguration;
  24463. },
  24464. enumerable: true,
  24465. configurable: true
  24466. });
  24467. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24468. get: function () {
  24469. return this._forceWireframe;
  24470. },
  24471. /**
  24472. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24473. */
  24474. set: function (value) {
  24475. if (this._forceWireframe === value) {
  24476. return;
  24477. }
  24478. this._forceWireframe = value;
  24479. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24480. },
  24481. enumerable: true,
  24482. configurable: true
  24483. });
  24484. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24485. get: function () {
  24486. return this._forcePointsCloud;
  24487. },
  24488. /**
  24489. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24490. */
  24491. set: function (value) {
  24492. if (this._forcePointsCloud === value) {
  24493. return;
  24494. }
  24495. this._forcePointsCloud = value;
  24496. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24497. },
  24498. enumerable: true,
  24499. configurable: true
  24500. });
  24501. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24502. /**
  24503. * Gets or sets the animation properties override
  24504. */
  24505. get: function () {
  24506. return this._animationPropertiesOverride;
  24507. },
  24508. set: function (value) {
  24509. this._animationPropertiesOverride = value;
  24510. },
  24511. enumerable: true,
  24512. configurable: true
  24513. });
  24514. Object.defineProperty(Scene.prototype, "onDispose", {
  24515. /** Sets a function to be executed when this scene is disposed. */
  24516. set: function (callback) {
  24517. if (this._onDisposeObserver) {
  24518. this.onDisposeObservable.remove(this._onDisposeObserver);
  24519. }
  24520. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24521. },
  24522. enumerable: true,
  24523. configurable: true
  24524. });
  24525. Object.defineProperty(Scene.prototype, "beforeRender", {
  24526. /** Sets a function to be executed before rendering this scene */
  24527. set: function (callback) {
  24528. if (this._onBeforeRenderObserver) {
  24529. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24530. }
  24531. if (callback) {
  24532. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24533. }
  24534. },
  24535. enumerable: true,
  24536. configurable: true
  24537. });
  24538. Object.defineProperty(Scene.prototype, "afterRender", {
  24539. /** Sets a function to be executed after rendering this scene */
  24540. set: function (callback) {
  24541. if (this._onAfterRenderObserver) {
  24542. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24543. }
  24544. if (callback) {
  24545. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24546. }
  24547. },
  24548. enumerable: true,
  24549. configurable: true
  24550. });
  24551. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24552. /** Sets a function to be executed before rendering a camera*/
  24553. set: function (callback) {
  24554. if (this._onBeforeCameraRenderObserver) {
  24555. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24556. }
  24557. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24558. },
  24559. enumerable: true,
  24560. configurable: true
  24561. });
  24562. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24563. /** Sets a function to be executed after rendering a camera*/
  24564. set: function (callback) {
  24565. if (this._onAfterCameraRenderObserver) {
  24566. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24567. }
  24568. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24569. },
  24570. enumerable: true,
  24571. configurable: true
  24572. });
  24573. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24574. /**
  24575. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24576. */
  24577. get: function () {
  24578. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24579. },
  24580. enumerable: true,
  24581. configurable: true
  24582. });
  24583. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24584. get: function () {
  24585. return this._useRightHandedSystem;
  24586. },
  24587. /**
  24588. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24589. */
  24590. set: function (value) {
  24591. if (this._useRightHandedSystem === value) {
  24592. return;
  24593. }
  24594. this._useRightHandedSystem = value;
  24595. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24596. },
  24597. enumerable: true,
  24598. configurable: true
  24599. });
  24600. /**
  24601. * Sets the step Id used by deterministic lock step
  24602. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24603. * @param newStepId defines the step Id
  24604. */
  24605. Scene.prototype.setStepId = function (newStepId) {
  24606. this._currentStepId = newStepId;
  24607. };
  24608. ;
  24609. /**
  24610. * Gets the step Id used by deterministic lock step
  24611. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24612. * @returns the step Id
  24613. */
  24614. Scene.prototype.getStepId = function () {
  24615. return this._currentStepId;
  24616. };
  24617. ;
  24618. /**
  24619. * Gets the internal step used by deterministic lock step
  24620. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24621. * @returns the internal step
  24622. */
  24623. Scene.prototype.getInternalStep = function () {
  24624. return this._currentInternalStep;
  24625. };
  24626. ;
  24627. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24628. get: function () {
  24629. return this._fogEnabled;
  24630. },
  24631. /**
  24632. * Gets or sets a boolean indicating if fog is enabled on this scene
  24633. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24634. */
  24635. set: function (value) {
  24636. if (this._fogEnabled === value) {
  24637. return;
  24638. }
  24639. this._fogEnabled = value;
  24640. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24641. },
  24642. enumerable: true,
  24643. configurable: true
  24644. });
  24645. Object.defineProperty(Scene.prototype, "fogMode", {
  24646. get: function () {
  24647. return this._fogMode;
  24648. },
  24649. /**
  24650. * Gets or sets the fog mode to use
  24651. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24652. */
  24653. set: function (value) {
  24654. if (this._fogMode === value) {
  24655. return;
  24656. }
  24657. this._fogMode = value;
  24658. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24659. },
  24660. enumerable: true,
  24661. configurable: true
  24662. });
  24663. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24664. get: function () {
  24665. return this._shadowsEnabled;
  24666. },
  24667. /**
  24668. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24669. */
  24670. set: function (value) {
  24671. if (this._shadowsEnabled === value) {
  24672. return;
  24673. }
  24674. this._shadowsEnabled = value;
  24675. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24676. },
  24677. enumerable: true,
  24678. configurable: true
  24679. });
  24680. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24681. get: function () {
  24682. return this._lightsEnabled;
  24683. },
  24684. /**
  24685. * Gets or sets a boolean indicating if lights are enabled on this scene
  24686. */
  24687. set: function (value) {
  24688. if (this._lightsEnabled === value) {
  24689. return;
  24690. }
  24691. this._lightsEnabled = value;
  24692. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24693. },
  24694. enumerable: true,
  24695. configurable: true
  24696. });
  24697. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24698. /** The default material used on meshes when no material is affected */
  24699. get: function () {
  24700. if (!this._defaultMaterial) {
  24701. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24702. }
  24703. return this._defaultMaterial;
  24704. },
  24705. /** The default material used on meshes when no material is affected */
  24706. set: function (value) {
  24707. this._defaultMaterial = value;
  24708. },
  24709. enumerable: true,
  24710. configurable: true
  24711. });
  24712. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24713. get: function () {
  24714. return this._texturesEnabled;
  24715. },
  24716. /**
  24717. * Gets or sets a boolean indicating if textures are enabled on this scene
  24718. */
  24719. set: function (value) {
  24720. if (this._texturesEnabled === value) {
  24721. return;
  24722. }
  24723. this._texturesEnabled = value;
  24724. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24725. },
  24726. enumerable: true,
  24727. configurable: true
  24728. });
  24729. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24730. get: function () {
  24731. return this._skeletonsEnabled;
  24732. },
  24733. /**
  24734. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24735. */
  24736. set: function (value) {
  24737. if (this._skeletonsEnabled === value) {
  24738. return;
  24739. }
  24740. this._skeletonsEnabled = value;
  24741. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24742. },
  24743. enumerable: true,
  24744. configurable: true
  24745. });
  24746. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24747. /**
  24748. * Gets the main soundtrack associated with the scene
  24749. */
  24750. get: function () {
  24751. if (!this._mainSoundTrack) {
  24752. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24753. }
  24754. return this._mainSoundTrack;
  24755. },
  24756. enumerable: true,
  24757. configurable: true
  24758. });
  24759. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24760. /** @hidden */
  24761. get: function () {
  24762. return this._alternateRendering;
  24763. },
  24764. enumerable: true,
  24765. configurable: true
  24766. });
  24767. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24768. /**
  24769. * Gets the list of frustum planes (built from the active camera)
  24770. */
  24771. get: function () {
  24772. return this._frustumPlanes;
  24773. },
  24774. enumerable: true,
  24775. configurable: true
  24776. });
  24777. /**
  24778. * Registers the transient components if needed.
  24779. */
  24780. Scene.prototype._registerTransientComponents = function () {
  24781. // Register components that have been associated lately to the scene.
  24782. if (this._transientComponents.length > 0) {
  24783. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  24784. var component = _a[_i];
  24785. component.register();
  24786. }
  24787. this._transientComponents = [];
  24788. }
  24789. };
  24790. /**
  24791. * @hidden
  24792. * Add a component to the scene.
  24793. * Note that the ccomponent could be registered on th next frame if this is called after
  24794. * the register component stage.
  24795. * @param component Defines the component to add to the scene
  24796. */
  24797. Scene.prototype._addComponent = function (component) {
  24798. this._components.push(component);
  24799. this._transientComponents.push(component);
  24800. var serializableComponent = component;
  24801. if (serializableComponent.addFromContainer) {
  24802. this._serializableComponents.push(serializableComponent);
  24803. }
  24804. };
  24805. /**
  24806. * @hidden
  24807. * Gets a component from the scene.
  24808. * @param name defines the name of the component to retrieve
  24809. * @returns the component or null if not present
  24810. */
  24811. Scene.prototype._getComponent = function (name) {
  24812. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  24813. var component = _a[_i];
  24814. if (component.name === name) {
  24815. return component;
  24816. }
  24817. }
  24818. return null;
  24819. };
  24820. Object.defineProperty(Scene.prototype, "debugLayer", {
  24821. /**
  24822. * Gets the debug layer (aka Inspector) associated with the scene
  24823. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24824. */
  24825. get: function () {
  24826. if (!this._debugLayer) {
  24827. this._debugLayer = new BABYLON.DebugLayer(this);
  24828. }
  24829. return this._debugLayer;
  24830. },
  24831. enumerable: true,
  24832. configurable: true
  24833. });
  24834. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24835. /**
  24836. * Gets a boolean indicating if collisions are processed on a web worker
  24837. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24838. */
  24839. get: function () {
  24840. return this._workerCollisions;
  24841. },
  24842. set: function (enabled) {
  24843. if (!BABYLON.CollisionCoordinatorLegacy) {
  24844. return;
  24845. }
  24846. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24847. this._workerCollisions = enabled;
  24848. if (this.collisionCoordinator) {
  24849. this.collisionCoordinator.destroy();
  24850. }
  24851. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24852. this.collisionCoordinator.init(this);
  24853. },
  24854. enumerable: true,
  24855. configurable: true
  24856. });
  24857. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24858. /**
  24859. * Gets the octree used to boost mesh selection (picking)
  24860. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24861. */
  24862. get: function () {
  24863. return this._selectionOctree;
  24864. },
  24865. enumerable: true,
  24866. configurable: true
  24867. });
  24868. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24869. /**
  24870. * Gets the mesh that is currently under the pointer
  24871. */
  24872. get: function () {
  24873. return this._pointerOverMesh;
  24874. },
  24875. enumerable: true,
  24876. configurable: true
  24877. });
  24878. Object.defineProperty(Scene.prototype, "pointerX", {
  24879. /**
  24880. * Gets the current on-screen X position of the pointer
  24881. */
  24882. get: function () {
  24883. return this._pointerX;
  24884. },
  24885. enumerable: true,
  24886. configurable: true
  24887. });
  24888. Object.defineProperty(Scene.prototype, "pointerY", {
  24889. /**
  24890. * Gets the current on-screen Y position of the pointer
  24891. */
  24892. get: function () {
  24893. return this._pointerY;
  24894. },
  24895. enumerable: true,
  24896. configurable: true
  24897. });
  24898. /**
  24899. * Gets the cached material (ie. the latest rendered one)
  24900. * @returns the cached material
  24901. */
  24902. Scene.prototype.getCachedMaterial = function () {
  24903. return this._cachedMaterial;
  24904. };
  24905. /**
  24906. * Gets the cached effect (ie. the latest rendered one)
  24907. * @returns the cached effect
  24908. */
  24909. Scene.prototype.getCachedEffect = function () {
  24910. return this._cachedEffect;
  24911. };
  24912. /**
  24913. * Gets the cached visibility state (ie. the latest rendered one)
  24914. * @returns the cached visibility state
  24915. */
  24916. Scene.prototype.getCachedVisibility = function () {
  24917. return this._cachedVisibility;
  24918. };
  24919. /**
  24920. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24921. * @param material defines the current material
  24922. * @param effect defines the current effect
  24923. * @param visibility defines the current visibility state
  24924. * @returns true if one parameter is not cached
  24925. */
  24926. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24927. if (visibility === void 0) { visibility = 1; }
  24928. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24929. };
  24930. /**
  24931. * Gets the outline renderer associated with the scene
  24932. * @returns a OutlineRenderer
  24933. */
  24934. Scene.prototype.getOutlineRenderer = function () {
  24935. return this._outlineRenderer;
  24936. };
  24937. /**
  24938. * Gets the engine associated with the scene
  24939. * @returns an Engine
  24940. */
  24941. Scene.prototype.getEngine = function () {
  24942. return this._engine;
  24943. };
  24944. /**
  24945. * Gets the total number of vertices rendered per frame
  24946. * @returns the total number of vertices rendered per frame
  24947. */
  24948. Scene.prototype.getTotalVertices = function () {
  24949. return this._totalVertices.current;
  24950. };
  24951. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24952. /**
  24953. * Gets the performance counter for total vertices
  24954. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24955. */
  24956. get: function () {
  24957. return this._totalVertices;
  24958. },
  24959. enumerable: true,
  24960. configurable: true
  24961. });
  24962. /**
  24963. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24964. * @returns the total number of active indices rendered per frame
  24965. */
  24966. Scene.prototype.getActiveIndices = function () {
  24967. return this._activeIndices.current;
  24968. };
  24969. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24970. /**
  24971. * Gets the performance counter for active indices
  24972. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24973. */
  24974. get: function () {
  24975. return this._activeIndices;
  24976. },
  24977. enumerable: true,
  24978. configurable: true
  24979. });
  24980. /**
  24981. * Gets the total number of active particles rendered per frame
  24982. * @returns the total number of active particles rendered per frame
  24983. */
  24984. Scene.prototype.getActiveParticles = function () {
  24985. return this._activeParticles.current;
  24986. };
  24987. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24988. /**
  24989. * Gets the performance counter for active particles
  24990. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24991. */
  24992. get: function () {
  24993. return this._activeParticles;
  24994. },
  24995. enumerable: true,
  24996. configurable: true
  24997. });
  24998. /**
  24999. * Gets the total number of active bones rendered per frame
  25000. * @returns the total number of active bones rendered per frame
  25001. */
  25002. Scene.prototype.getActiveBones = function () {
  25003. return this._activeBones.current;
  25004. };
  25005. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  25006. /**
  25007. * Gets the performance counter for active bones
  25008. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25009. */
  25010. get: function () {
  25011. return this._activeBones;
  25012. },
  25013. enumerable: true,
  25014. configurable: true
  25015. });
  25016. /** @hidden */
  25017. Scene.prototype.getInterFramePerfCounter = function () {
  25018. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25019. return 0;
  25020. };
  25021. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  25022. /** @hidden */
  25023. get: function () {
  25024. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25025. return null;
  25026. },
  25027. enumerable: true,
  25028. configurable: true
  25029. });
  25030. /** @hidden */
  25031. Scene.prototype.getLastFrameDuration = function () {
  25032. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  25033. return 0;
  25034. };
  25035. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  25036. /** @hidden */
  25037. get: function () {
  25038. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25039. return null;
  25040. },
  25041. enumerable: true,
  25042. configurable: true
  25043. });
  25044. /** @hidden */
  25045. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  25046. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  25047. return 0;
  25048. };
  25049. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  25050. /** @hidden */
  25051. get: function () {
  25052. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25053. return null;
  25054. },
  25055. enumerable: true,
  25056. configurable: true
  25057. });
  25058. /**
  25059. * Gets the array of active meshes
  25060. * @returns an array of AbstractMesh
  25061. */
  25062. Scene.prototype.getActiveMeshes = function () {
  25063. return this._activeMeshes;
  25064. };
  25065. /** @hidden */
  25066. Scene.prototype.getRenderTargetsDuration = function () {
  25067. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  25068. return 0;
  25069. };
  25070. /** @hidden */
  25071. Scene.prototype.getRenderDuration = function () {
  25072. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  25073. return 0;
  25074. };
  25075. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  25076. /** @hidden */
  25077. get: function () {
  25078. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25079. return null;
  25080. },
  25081. enumerable: true,
  25082. configurable: true
  25083. });
  25084. /** @hidden */
  25085. Scene.prototype.getParticlesDuration = function () {
  25086. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  25087. return 0;
  25088. };
  25089. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  25090. /** @hidden */
  25091. get: function () {
  25092. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25093. return null;
  25094. },
  25095. enumerable: true,
  25096. configurable: true
  25097. });
  25098. /** @hidden */
  25099. Scene.prototype.getSpritesDuration = function () {
  25100. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  25101. return 0;
  25102. };
  25103. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  25104. /** @hidden */
  25105. get: function () {
  25106. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  25107. return null;
  25108. },
  25109. enumerable: true,
  25110. configurable: true
  25111. });
  25112. /**
  25113. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25114. * @returns a number
  25115. */
  25116. Scene.prototype.getAnimationRatio = function () {
  25117. return this._animationRatio !== undefined ? this._animationRatio : 1;
  25118. };
  25119. /**
  25120. * Gets an unique Id for the current frame
  25121. * @returns a number
  25122. */
  25123. Scene.prototype.getRenderId = function () {
  25124. return this._renderId;
  25125. };
  25126. /** Call this function if you want to manually increment the render Id*/
  25127. Scene.prototype.incrementRenderId = function () {
  25128. this._renderId++;
  25129. };
  25130. Scene.prototype._updatePointerPosition = function (evt) {
  25131. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25132. if (!canvasRect) {
  25133. return;
  25134. }
  25135. this._pointerX = evt.clientX - canvasRect.left;
  25136. this._pointerY = evt.clientY - canvasRect.top;
  25137. this._unTranslatedPointerX = this._pointerX;
  25138. this._unTranslatedPointerY = this._pointerY;
  25139. };
  25140. Scene.prototype._createUbo = function () {
  25141. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25142. this._sceneUbo.addUniform("viewProjection", 16);
  25143. this._sceneUbo.addUniform("view", 16);
  25144. };
  25145. Scene.prototype._createAlternateUbo = function () {
  25146. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25147. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25148. this._alternateSceneUbo.addUniform("view", 16);
  25149. };
  25150. // Pointers handling
  25151. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  25152. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  25153. if (result) {
  25154. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  25155. }
  25156. return result;
  25157. };
  25158. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25159. if (pointerInfo.pickInfo) {
  25160. if (!pointerInfo.pickInfo.ray) {
  25161. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25162. }
  25163. }
  25164. };
  25165. /**
  25166. * Use this method to simulate a pointer move on a mesh
  25167. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25168. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25169. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25170. * @returns the current scene
  25171. */
  25172. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25173. var evt = new PointerEvent("pointermove", pointerEventInit);
  25174. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25175. return this;
  25176. }
  25177. return this._processPointerMove(pickResult, evt);
  25178. };
  25179. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25180. var canvas = this._engine.getRenderingCanvas();
  25181. if (!canvas) {
  25182. return this;
  25183. }
  25184. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25185. this.setPointerOverSprite(null);
  25186. this.setPointerOverMesh(pickResult.pickedMesh);
  25187. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25188. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25189. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25190. }
  25191. else {
  25192. canvas.style.cursor = this.hoverCursor;
  25193. }
  25194. }
  25195. else {
  25196. canvas.style.cursor = this.defaultCursor;
  25197. }
  25198. }
  25199. else {
  25200. this.setPointerOverMesh(null);
  25201. // Sprites
  25202. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  25203. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25204. this.setPointerOverSprite(pickResult.pickedSprite);
  25205. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  25206. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  25207. }
  25208. else {
  25209. canvas.style.cursor = this.hoverCursor;
  25210. }
  25211. }
  25212. else {
  25213. this.setPointerOverSprite(null);
  25214. // Restore pointer
  25215. canvas.style.cursor = this.defaultCursor;
  25216. }
  25217. }
  25218. if (pickResult) {
  25219. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25220. if (this.onPointerMove) {
  25221. this.onPointerMove(evt, pickResult, type);
  25222. }
  25223. if (this.onPointerObservable.hasObservers()) {
  25224. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25225. this._setRayOnPointerInfo(pi);
  25226. this.onPointerObservable.notifyObservers(pi, type);
  25227. }
  25228. }
  25229. return this;
  25230. };
  25231. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25232. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25233. if (pickResult) {
  25234. pi.ray = pickResult.ray;
  25235. }
  25236. this.onPrePointerObservable.notifyObservers(pi, type);
  25237. if (pi.skipOnPointerObservable) {
  25238. return true;
  25239. }
  25240. else {
  25241. return false;
  25242. }
  25243. };
  25244. /**
  25245. * Use this method to simulate a pointer down on a mesh
  25246. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25247. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25248. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25249. * @returns the current scene
  25250. */
  25251. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25252. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25253. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25254. return this;
  25255. }
  25256. return this._processPointerDown(pickResult, evt);
  25257. };
  25258. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25259. var _this = this;
  25260. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25261. this._pickedDownMesh = pickResult.pickedMesh;
  25262. var actionManager = pickResult.pickedMesh.actionManager;
  25263. if (actionManager) {
  25264. if (actionManager.hasPickTriggers) {
  25265. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25266. switch (evt.button) {
  25267. case 0:
  25268. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25269. break;
  25270. case 1:
  25271. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25272. break;
  25273. case 2:
  25274. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25275. break;
  25276. }
  25277. }
  25278. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25279. window.setTimeout(function () {
  25280. 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);
  25281. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25282. if (_this._totalPointersPressed !== 0 &&
  25283. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25284. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25285. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25286. _this._startingPointerTime = 0;
  25287. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25288. }
  25289. }
  25290. }, Scene.LongPressDelay);
  25291. }
  25292. }
  25293. }
  25294. if (pickResult) {
  25295. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25296. if (this.onPointerDown) {
  25297. this.onPointerDown(evt, pickResult, type);
  25298. }
  25299. if (this.onPointerObservable.hasObservers()) {
  25300. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25301. this._setRayOnPointerInfo(pi);
  25302. this.onPointerObservable.notifyObservers(pi, type);
  25303. }
  25304. }
  25305. return this;
  25306. };
  25307. /**
  25308. * Use this method to simulate a pointer up on a mesh
  25309. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25310. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25311. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25312. * @returns the current scene
  25313. */
  25314. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25315. var evt = new PointerEvent("pointerup", pointerEventInit);
  25316. var clickInfo = new ClickInfo();
  25317. clickInfo.singleClick = true;
  25318. clickInfo.ignore = true;
  25319. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25320. return this;
  25321. }
  25322. return this._processPointerUp(pickResult, evt, clickInfo);
  25323. };
  25324. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25325. if (pickResult && pickResult && pickResult.pickedMesh) {
  25326. this._pickedUpMesh = pickResult.pickedMesh;
  25327. if (this._pickedDownMesh === this._pickedUpMesh) {
  25328. if (this.onPointerPick) {
  25329. this.onPointerPick(evt, pickResult);
  25330. }
  25331. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25332. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25333. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25334. this._setRayOnPointerInfo(pi);
  25335. this.onPointerObservable.notifyObservers(pi, type_1);
  25336. }
  25337. }
  25338. if (pickResult.pickedMesh.actionManager) {
  25339. if (clickInfo.ignore) {
  25340. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25341. }
  25342. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25343. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25344. }
  25345. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25346. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25347. }
  25348. }
  25349. }
  25350. if (this._pickedDownMesh &&
  25351. this._pickedDownMesh.actionManager &&
  25352. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25353. this._pickedDownMesh !== this._pickedUpMesh) {
  25354. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25355. }
  25356. var type = BABYLON.PointerEventTypes.POINTERUP;
  25357. if (this.onPointerObservable.hasObservers()) {
  25358. if (!clickInfo.ignore) {
  25359. if (!clickInfo.hasSwiped) {
  25360. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25361. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25362. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25363. this._setRayOnPointerInfo(pi);
  25364. this.onPointerObservable.notifyObservers(pi, type_2);
  25365. }
  25366. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25367. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25368. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25369. this._setRayOnPointerInfo(pi);
  25370. this.onPointerObservable.notifyObservers(pi, type_3);
  25371. }
  25372. }
  25373. }
  25374. else {
  25375. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25376. this._setRayOnPointerInfo(pi);
  25377. this.onPointerObservable.notifyObservers(pi, type);
  25378. }
  25379. }
  25380. if (this.onPointerUp) {
  25381. this.onPointerUp(evt, pickResult, type);
  25382. }
  25383. return this;
  25384. };
  25385. /**
  25386. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25387. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25388. * @returns true if the pointer was captured
  25389. */
  25390. Scene.prototype.isPointerCaptured = function (pointerId) {
  25391. if (pointerId === void 0) { pointerId = 0; }
  25392. return this._pointerCaptures[pointerId];
  25393. };
  25394. /**
  25395. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25396. * @param attachUp defines if you want to attach events to pointerup
  25397. * @param attachDown defines if you want to attach events to pointerdown
  25398. * @param attachMove defines if you want to attach events to pointermove
  25399. */
  25400. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25401. var _this = this;
  25402. if (attachUp === void 0) { attachUp = true; }
  25403. if (attachDown === void 0) { attachDown = true; }
  25404. if (attachMove === void 0) { attachMove = true; }
  25405. this._initActionManager = function (act, clickInfo) {
  25406. if (!_this._meshPickProceed) {
  25407. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25408. _this._currentPickResult = pickResult;
  25409. if (pickResult) {
  25410. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25411. }
  25412. _this._meshPickProceed = true;
  25413. }
  25414. return act;
  25415. };
  25416. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25417. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25418. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25419. btn !== _this._previousButtonPressed) {
  25420. _this._doubleClickOccured = false;
  25421. clickInfo.singleClick = true;
  25422. clickInfo.ignore = false;
  25423. cb(clickInfo, _this._currentPickResult);
  25424. }
  25425. };
  25426. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25427. var clickInfo = new ClickInfo();
  25428. _this._currentPickResult = null;
  25429. var act = null;
  25430. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25431. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25432. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25433. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25434. act = _this._initActionManager(act, clickInfo);
  25435. if (act)
  25436. checkPicking = act.hasPickTriggers;
  25437. }
  25438. if (checkPicking) {
  25439. var btn = evt.button;
  25440. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25441. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25442. if (!clickInfo.hasSwiped) {
  25443. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25444. if (!checkSingleClickImmediately) {
  25445. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25446. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25447. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25448. act = _this._initActionManager(act, clickInfo);
  25449. if (act)
  25450. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25451. }
  25452. }
  25453. if (checkSingleClickImmediately) {
  25454. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25455. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25456. btn !== _this._previousButtonPressed) {
  25457. clickInfo.singleClick = true;
  25458. cb(clickInfo, _this._currentPickResult);
  25459. }
  25460. }
  25461. // at least one double click is required to be check and exclusive double click is enabled
  25462. else {
  25463. // wait that no double click has been raised during the double click delay
  25464. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25465. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25466. }
  25467. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25468. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25469. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25470. act = _this._initActionManager(act, clickInfo);
  25471. if (act)
  25472. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25473. }
  25474. if (checkDoubleClick) {
  25475. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25476. if (btn === _this._previousButtonPressed &&
  25477. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25478. !_this._doubleClickOccured) {
  25479. // pointer has not moved for 2 clicks, it's a double click
  25480. if (!clickInfo.hasSwiped &&
  25481. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25482. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25483. _this._previousStartingPointerTime = 0;
  25484. _this._doubleClickOccured = true;
  25485. clickInfo.doubleClick = true;
  25486. clickInfo.ignore = false;
  25487. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25488. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25489. }
  25490. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25491. cb(clickInfo, _this._currentPickResult);
  25492. }
  25493. // if the two successive clicks are too far, it's just two simple clicks
  25494. else {
  25495. _this._doubleClickOccured = false;
  25496. _this._previousStartingPointerTime = _this._startingPointerTime;
  25497. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25498. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25499. _this._previousButtonPressed = btn;
  25500. if (Scene.ExclusiveDoubleClickMode) {
  25501. if (_this._previousDelayedSimpleClickTimeout) {
  25502. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25503. }
  25504. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25505. cb(clickInfo, _this._previousPickResult);
  25506. }
  25507. else {
  25508. cb(clickInfo, _this._currentPickResult);
  25509. }
  25510. }
  25511. }
  25512. // just the first click of the double has been raised
  25513. else {
  25514. _this._doubleClickOccured = false;
  25515. _this._previousStartingPointerTime = _this._startingPointerTime;
  25516. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25517. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25518. _this._previousButtonPressed = btn;
  25519. }
  25520. }
  25521. }
  25522. }
  25523. clickInfo.ignore = true;
  25524. cb(clickInfo, _this._currentPickResult);
  25525. };
  25526. this._spritePredicate = function (sprite) {
  25527. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25528. };
  25529. this._onPointerMove = function (evt) {
  25530. _this._updatePointerPosition(evt);
  25531. // PreObservable support
  25532. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25533. return;
  25534. }
  25535. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25536. return;
  25537. }
  25538. if (!_this.pointerMovePredicate) {
  25539. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25540. }
  25541. // Meshes
  25542. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25543. _this._processPointerMove(pickResult, evt);
  25544. };
  25545. this._onPointerDown = function (evt) {
  25546. _this._totalPointersPressed++;
  25547. _this._pickedDownMesh = null;
  25548. _this._meshPickProceed = false;
  25549. _this._updatePointerPosition(evt);
  25550. if (_this.preventDefaultOnPointerDown && canvas) {
  25551. evt.preventDefault();
  25552. canvas.focus();
  25553. }
  25554. // PreObservable support
  25555. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25556. return;
  25557. }
  25558. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25559. return;
  25560. }
  25561. _this._pointerCaptures[evt.pointerId] = true;
  25562. _this._startingPointerPosition.x = _this._pointerX;
  25563. _this._startingPointerPosition.y = _this._pointerY;
  25564. _this._startingPointerTime = Date.now();
  25565. if (!_this.pointerDownPredicate) {
  25566. _this.pointerDownPredicate = function (mesh) {
  25567. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25568. };
  25569. }
  25570. // Meshes
  25571. _this._pickedDownMesh = null;
  25572. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25573. _this._processPointerDown(pickResult, evt);
  25574. // Sprites
  25575. _this._pickedDownSprite = null;
  25576. if (_this.spriteManagers.length > 0) {
  25577. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25578. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25579. if (pickResult.pickedSprite.actionManager) {
  25580. _this._pickedDownSprite = pickResult.pickedSprite;
  25581. switch (evt.button) {
  25582. case 0:
  25583. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25584. break;
  25585. case 1:
  25586. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25587. break;
  25588. case 2:
  25589. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25590. break;
  25591. }
  25592. if (pickResult.pickedSprite.actionManager) {
  25593. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25594. }
  25595. }
  25596. }
  25597. }
  25598. };
  25599. this._onPointerUp = function (evt) {
  25600. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25601. return; // So we need to test it the pointer down was pressed before.
  25602. }
  25603. _this._totalPointersPressed--;
  25604. _this._pickedUpMesh = null;
  25605. _this._meshPickProceed = false;
  25606. _this._updatePointerPosition(evt);
  25607. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25608. // PreObservable support
  25609. if (_this.onPrePointerObservable.hasObservers()) {
  25610. if (!clickInfo.ignore) {
  25611. if (!clickInfo.hasSwiped) {
  25612. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25613. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25614. return;
  25615. }
  25616. }
  25617. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25618. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25619. return;
  25620. }
  25621. }
  25622. }
  25623. }
  25624. else {
  25625. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25626. return;
  25627. }
  25628. }
  25629. }
  25630. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25631. return;
  25632. }
  25633. _this._pointerCaptures[evt.pointerId] = false;
  25634. if (!_this.pointerUpPredicate) {
  25635. _this.pointerUpPredicate = function (mesh) {
  25636. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25637. };
  25638. }
  25639. // Meshes
  25640. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25641. _this._initActionManager(null, clickInfo);
  25642. }
  25643. if (!pickResult) {
  25644. pickResult = _this._currentPickResult;
  25645. }
  25646. _this._processPointerUp(pickResult, evt, clickInfo);
  25647. // Sprites
  25648. if (!clickInfo.ignore) {
  25649. if (_this.spriteManagers.length > 0) {
  25650. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25651. if (spritePickResult) {
  25652. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25653. if (spritePickResult.pickedSprite.actionManager) {
  25654. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25655. if (spritePickResult.pickedSprite.actionManager) {
  25656. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25657. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25658. }
  25659. }
  25660. }
  25661. }
  25662. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25663. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25664. }
  25665. }
  25666. }
  25667. }
  25668. _this._previousPickResult = _this._currentPickResult;
  25669. });
  25670. };
  25671. this._onKeyDown = function (evt) {
  25672. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25673. if (_this.onPreKeyboardObservable.hasObservers()) {
  25674. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25675. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25676. if (pi.skipOnPointerObservable) {
  25677. return;
  25678. }
  25679. }
  25680. if (_this.onKeyboardObservable.hasObservers()) {
  25681. var pi = new BABYLON.KeyboardInfo(type, evt);
  25682. _this.onKeyboardObservable.notifyObservers(pi, type);
  25683. }
  25684. if (_this.actionManager) {
  25685. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25686. }
  25687. };
  25688. this._onKeyUp = function (evt) {
  25689. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25690. if (_this.onPreKeyboardObservable.hasObservers()) {
  25691. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25692. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25693. if (pi.skipOnPointerObservable) {
  25694. return;
  25695. }
  25696. }
  25697. if (_this.onKeyboardObservable.hasObservers()) {
  25698. var pi = new BABYLON.KeyboardInfo(type, evt);
  25699. _this.onKeyboardObservable.notifyObservers(pi, type);
  25700. }
  25701. if (_this.actionManager) {
  25702. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25703. }
  25704. };
  25705. var engine = this.getEngine();
  25706. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25707. if (!canvas) {
  25708. return;
  25709. }
  25710. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25711. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25712. });
  25713. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25714. if (!canvas) {
  25715. return;
  25716. }
  25717. canvas.removeEventListener("keydown", _this._onKeyDown);
  25718. canvas.removeEventListener("keyup", _this._onKeyUp);
  25719. });
  25720. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25721. var canvas = this._engine.getRenderingCanvas();
  25722. if (!canvas) {
  25723. return;
  25724. }
  25725. if (attachMove) {
  25726. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25727. // Wheel
  25728. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25729. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25730. }
  25731. if (attachDown) {
  25732. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25733. }
  25734. if (attachUp) {
  25735. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25736. }
  25737. canvas.tabIndex = 1;
  25738. };
  25739. /** Detaches all event handlers*/
  25740. Scene.prototype.detachControl = function () {
  25741. var engine = this.getEngine();
  25742. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25743. var canvas = engine.getRenderingCanvas();
  25744. if (!canvas) {
  25745. return;
  25746. }
  25747. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25748. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25749. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25750. if (this._onCanvasBlurObserver) {
  25751. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25752. }
  25753. if (this._onCanvasFocusObserver) {
  25754. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25755. }
  25756. // Wheel
  25757. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25758. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25759. // Keyboard
  25760. canvas.removeEventListener("keydown", this._onKeyDown);
  25761. canvas.removeEventListener("keyup", this._onKeyUp);
  25762. // Observables
  25763. this.onKeyboardObservable.clear();
  25764. this.onPreKeyboardObservable.clear();
  25765. this.onPointerObservable.clear();
  25766. this.onPrePointerObservable.clear();
  25767. };
  25768. /**
  25769. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25770. * Delay loaded resources are not taking in account
  25771. * @return true if all required resources are ready
  25772. */
  25773. Scene.prototype.isReady = function () {
  25774. if (this._isDisposed) {
  25775. return false;
  25776. }
  25777. if (this._pendingData.length > 0) {
  25778. return false;
  25779. }
  25780. var index;
  25781. var engine = this.getEngine();
  25782. // Geometries
  25783. for (index = 0; index < this.geometries.length; index++) {
  25784. var geometry = this.geometries[index];
  25785. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25786. return false;
  25787. }
  25788. }
  25789. // Meshes
  25790. for (index = 0; index < this.meshes.length; index++) {
  25791. var mesh = this.meshes[index];
  25792. if (!mesh.isEnabled()) {
  25793. continue;
  25794. }
  25795. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25796. continue;
  25797. }
  25798. if (!mesh.isReady(true)) {
  25799. return false;
  25800. }
  25801. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25802. // Is Ready For Mesh
  25803. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  25804. var step = _a[_i];
  25805. if (!step.action(mesh, hardwareInstancedRendering)) {
  25806. return false;
  25807. }
  25808. }
  25809. }
  25810. // Post-processes
  25811. if (this.activeCameras && this.activeCameras.length > 0) {
  25812. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  25813. var camera = _c[_b];
  25814. if (!camera.isReady(true)) {
  25815. return false;
  25816. }
  25817. }
  25818. }
  25819. else if (this.activeCamera) {
  25820. if (!this.activeCamera.isReady(true)) {
  25821. return false;
  25822. }
  25823. }
  25824. // Particles
  25825. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  25826. var particleSystem = _e[_d];
  25827. if (!particleSystem.isReady()) {
  25828. return false;
  25829. }
  25830. }
  25831. return true;
  25832. };
  25833. /** Resets all cached information relative to material (including effect and visibility) */
  25834. Scene.prototype.resetCachedMaterial = function () {
  25835. this._cachedMaterial = null;
  25836. this._cachedEffect = null;
  25837. this._cachedVisibility = null;
  25838. };
  25839. /**
  25840. * Registers a function to be called before every frame render
  25841. * @param func defines the function to register
  25842. */
  25843. Scene.prototype.registerBeforeRender = function (func) {
  25844. this.onBeforeRenderObservable.add(func);
  25845. };
  25846. /**
  25847. * Unregisters a function called before every frame render
  25848. * @param func defines the function to unregister
  25849. */
  25850. Scene.prototype.unregisterBeforeRender = function (func) {
  25851. this.onBeforeRenderObservable.removeCallback(func);
  25852. };
  25853. /**
  25854. * Registers a function to be called after every frame render
  25855. * @param func defines the function to register
  25856. */
  25857. Scene.prototype.registerAfterRender = function (func) {
  25858. this.onAfterRenderObservable.add(func);
  25859. };
  25860. /**
  25861. * Unregisters a function called after every frame render
  25862. * @param func defines the function to unregister
  25863. */
  25864. Scene.prototype.unregisterAfterRender = function (func) {
  25865. this.onAfterRenderObservable.removeCallback(func);
  25866. };
  25867. Scene.prototype._executeOnceBeforeRender = function (func) {
  25868. var _this = this;
  25869. var execFunc = function () {
  25870. func();
  25871. setTimeout(function () {
  25872. _this.unregisterBeforeRender(execFunc);
  25873. });
  25874. };
  25875. this.registerBeforeRender(execFunc);
  25876. };
  25877. /**
  25878. * The provided function will run before render once and will be disposed afterwards.
  25879. * A timeout delay can be provided so that the function will be executed in N ms.
  25880. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25881. * @param func The function to be executed.
  25882. * @param timeout optional delay in ms
  25883. */
  25884. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25885. var _this = this;
  25886. if (timeout !== undefined) {
  25887. setTimeout(function () {
  25888. _this._executeOnceBeforeRender(func);
  25889. }, timeout);
  25890. }
  25891. else {
  25892. this._executeOnceBeforeRender(func);
  25893. }
  25894. };
  25895. /** @hidden */
  25896. Scene.prototype._addPendingData = function (data) {
  25897. this._pendingData.push(data);
  25898. };
  25899. /** @hidden */
  25900. Scene.prototype._removePendingData = function (data) {
  25901. var wasLoading = this.isLoading;
  25902. var index = this._pendingData.indexOf(data);
  25903. if (index !== -1) {
  25904. this._pendingData.splice(index, 1);
  25905. }
  25906. if (wasLoading && !this.isLoading) {
  25907. this.onDataLoadedObservable.notifyObservers(this);
  25908. }
  25909. };
  25910. /**
  25911. * Returns the number of items waiting to be loaded
  25912. * @returns the number of items waiting to be loaded
  25913. */
  25914. Scene.prototype.getWaitingItemsCount = function () {
  25915. return this._pendingData.length;
  25916. };
  25917. Object.defineProperty(Scene.prototype, "isLoading", {
  25918. /**
  25919. * Returns a boolean indicating if the scene is still loading data
  25920. */
  25921. get: function () {
  25922. return this._pendingData.length > 0;
  25923. },
  25924. enumerable: true,
  25925. configurable: true
  25926. });
  25927. /**
  25928. * Registers a function to be executed when the scene is ready
  25929. * @param {Function} func - the function to be executed
  25930. */
  25931. Scene.prototype.executeWhenReady = function (func) {
  25932. var _this = this;
  25933. this.onReadyObservable.add(func);
  25934. if (this._executeWhenReadyTimeoutId !== -1) {
  25935. return;
  25936. }
  25937. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25938. _this._checkIsReady();
  25939. }, 150);
  25940. };
  25941. /**
  25942. * Returns a promise that resolves when the scene is ready
  25943. * @returns A promise that resolves when the scene is ready
  25944. */
  25945. Scene.prototype.whenReadyAsync = function () {
  25946. var _this = this;
  25947. return new Promise(function (resolve) {
  25948. _this.executeWhenReady(function () {
  25949. resolve();
  25950. });
  25951. });
  25952. };
  25953. /** @hidden */
  25954. Scene.prototype._checkIsReady = function () {
  25955. var _this = this;
  25956. this._registerTransientComponents();
  25957. if (this.isReady()) {
  25958. this.onReadyObservable.notifyObservers(this);
  25959. this.onReadyObservable.clear();
  25960. this._executeWhenReadyTimeoutId = -1;
  25961. return;
  25962. }
  25963. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25964. _this._checkIsReady();
  25965. }, 150);
  25966. };
  25967. // Animations
  25968. /**
  25969. * Will start the animation sequence of a given target
  25970. * @param target defines the target
  25971. * @param from defines from which frame should animation start
  25972. * @param to defines until which frame should animation run.
  25973. * @param weight defines the weight to apply to the animation (1.0 by default)
  25974. * @param loop defines if the animation loops
  25975. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25976. * @param onAnimationEnd defines the function to be executed when the animation ends
  25977. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25978. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25979. * @returns the animatable object created for this animation
  25980. */
  25981. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  25982. if (weight === void 0) { weight = 1.0; }
  25983. if (speedRatio === void 0) { speedRatio = 1.0; }
  25984. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  25985. returnedAnimatable.weight = weight;
  25986. return returnedAnimatable;
  25987. };
  25988. /**
  25989. * Will start the animation sequence of a given target
  25990. * @param target defines the target
  25991. * @param from defines from which frame should animation start
  25992. * @param to defines until which frame should animation run.
  25993. * @param loop defines if the animation loops
  25994. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25995. * @param onAnimationEnd defines the function to be executed when the animation ends
  25996. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25997. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25998. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25999. * @returns the animatable object created for this animation
  26000. */
  26001. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  26002. if (speedRatio === void 0) { speedRatio = 1.0; }
  26003. if (stopCurrent === void 0) { stopCurrent = true; }
  26004. if (from > to && speedRatio > 0) {
  26005. speedRatio *= -1;
  26006. }
  26007. if (stopCurrent) {
  26008. this.stopAnimation(target, undefined, targetMask);
  26009. }
  26010. if (!animatable) {
  26011. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  26012. }
  26013. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  26014. // Local animations
  26015. if (target.animations && shouldRunTargetAnimations) {
  26016. animatable.appendAnimations(target, target.animations);
  26017. }
  26018. // Children animations
  26019. if (target.getAnimatables) {
  26020. var animatables = target.getAnimatables();
  26021. for (var index = 0; index < animatables.length; index++) {
  26022. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  26023. }
  26024. }
  26025. animatable.reset();
  26026. return animatable;
  26027. };
  26028. /**
  26029. * Begin a new animation on a given node
  26030. * @param target defines the target where the animation will take place
  26031. * @param animations defines the list of animations to start
  26032. * @param from defines the initial value
  26033. * @param to defines the final value
  26034. * @param loop defines if you want animation to loop (off by default)
  26035. * @param speedRatio defines the speed ratio to apply to all animations
  26036. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26037. * @returns the list of created animatables
  26038. */
  26039. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26040. if (speedRatio === undefined) {
  26041. speedRatio = 1.0;
  26042. }
  26043. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  26044. return animatable;
  26045. };
  26046. /**
  26047. * Begin a new animation on a given node and its hierarchy
  26048. * @param target defines the root node where the animation will take place
  26049. * @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.
  26050. * @param animations defines the list of animations to start
  26051. * @param from defines the initial value
  26052. * @param to defines the final value
  26053. * @param loop defines if you want animation to loop (off by default)
  26054. * @param speedRatio defines the speed ratio to apply to all animations
  26055. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26056. * @returns the list of animatables created for all nodes
  26057. */
  26058. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26059. var children = target.getDescendants(directDescendantsOnly);
  26060. var result = [];
  26061. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  26062. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  26063. var child = children_1[_i];
  26064. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  26065. }
  26066. return result;
  26067. };
  26068. /**
  26069. * Gets the animatable associated with a specific target
  26070. * @param target defines the target of the animatable
  26071. * @returns the required animatable if found
  26072. */
  26073. Scene.prototype.getAnimatableByTarget = function (target) {
  26074. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26075. if (this._activeAnimatables[index].target === target) {
  26076. return this._activeAnimatables[index];
  26077. }
  26078. }
  26079. return null;
  26080. };
  26081. /**
  26082. * Gets all animatables associated with a given target
  26083. * @param target defines the target to look animatables for
  26084. * @returns an array of Animatables
  26085. */
  26086. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26087. var result = [];
  26088. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26089. if (this._activeAnimatables[index].target === target) {
  26090. result.push(this._activeAnimatables[index]);
  26091. }
  26092. }
  26093. return result;
  26094. };
  26095. Object.defineProperty(Scene.prototype, "animatables", {
  26096. /**
  26097. * Gets all animatable attached to the scene
  26098. */
  26099. get: function () {
  26100. return this._activeAnimatables;
  26101. },
  26102. enumerable: true,
  26103. configurable: true
  26104. });
  26105. /**
  26106. * Will stop the animation of the given target
  26107. * @param target - the target
  26108. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  26109. * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty)
  26110. */
  26111. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  26112. var animatables = this.getAllAnimatablesByTarget(target);
  26113. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26114. var animatable = animatables_1[_i];
  26115. animatable.stop(animationName, targetMask);
  26116. }
  26117. };
  26118. /**
  26119. * Stops and removes all animations that have been applied to the scene
  26120. */
  26121. Scene.prototype.stopAllAnimations = function () {
  26122. if (this._activeAnimatables) {
  26123. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26124. this._activeAnimatables[i].stop();
  26125. }
  26126. this._activeAnimatables = [];
  26127. }
  26128. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26129. var group = _a[_i];
  26130. group.stop();
  26131. }
  26132. };
  26133. Scene.prototype._animate = function () {
  26134. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26135. return;
  26136. }
  26137. // Getting time
  26138. var now = BABYLON.Tools.Now;
  26139. if (!this._animationTimeLast) {
  26140. if (this._pendingData.length > 0) {
  26141. return;
  26142. }
  26143. this._animationTimeLast = now;
  26144. }
  26145. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26146. this._animationTime += deltaTime;
  26147. this._animationTimeLast = now;
  26148. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26149. this._activeAnimatables[index]._animate(this._animationTime);
  26150. }
  26151. // Late animation bindings
  26152. this._processLateAnimationBindings();
  26153. };
  26154. /** @hidden */
  26155. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26156. var target = runtimeAnimation.target;
  26157. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26158. if (!target._lateAnimationHolders) {
  26159. target._lateAnimationHolders = {};
  26160. }
  26161. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26162. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26163. totalWeight: 0,
  26164. animations: [],
  26165. originalValue: originalValue
  26166. };
  26167. }
  26168. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26169. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26170. };
  26171. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26172. var normalizer = 1.0;
  26173. var finalPosition = BABYLON.Tmp.Vector3[0];
  26174. var finalScaling = BABYLON.Tmp.Vector3[1];
  26175. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26176. var startIndex = 0;
  26177. var originalAnimation = holder.animations[0];
  26178. var originalValue = holder.originalValue;
  26179. var scale = 1;
  26180. if (holder.totalWeight < 1.0) {
  26181. // We need to mix the original value in
  26182. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26183. scale = 1.0 - holder.totalWeight;
  26184. }
  26185. else {
  26186. startIndex = 1;
  26187. // We need to normalize the weights
  26188. normalizer = holder.totalWeight;
  26189. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26190. scale = originalAnimation.weight / normalizer;
  26191. if (scale == 1) {
  26192. return originalAnimation.currentValue;
  26193. }
  26194. }
  26195. finalScaling.scaleInPlace(scale);
  26196. finalPosition.scaleInPlace(scale);
  26197. finalQuaternion.scaleInPlace(scale);
  26198. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26199. var runtimeAnimation = holder.animations[animIndex];
  26200. var scale = runtimeAnimation.weight / normalizer;
  26201. var currentPosition = BABYLON.Tmp.Vector3[2];
  26202. var currentScaling = BABYLON.Tmp.Vector3[3];
  26203. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26204. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26205. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26206. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26207. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26208. }
  26209. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26210. return originalAnimation._workValue;
  26211. };
  26212. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder, refQuaternion) {
  26213. var originalAnimation = holder.animations[0];
  26214. var originalValue = holder.originalValue;
  26215. if (holder.animations.length === 1) {
  26216. BABYLON.Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), refQuaternion);
  26217. return refQuaternion;
  26218. }
  26219. var normalizer = 1.0;
  26220. var quaternions;
  26221. var weights;
  26222. if (holder.totalWeight < 1.0) {
  26223. var scale = 1.0 - holder.totalWeight;
  26224. quaternions = [];
  26225. weights = [];
  26226. quaternions.push(originalValue);
  26227. weights.push(scale);
  26228. }
  26229. else {
  26230. if (holder.animations.length === 2) { // Slerp as soon as we can
  26231. BABYLON.Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion);
  26232. return refQuaternion;
  26233. }
  26234. quaternions = [];
  26235. weights = [];
  26236. normalizer = holder.totalWeight;
  26237. }
  26238. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26239. var runtimeAnimation = holder.animations[animIndex];
  26240. quaternions.push(runtimeAnimation.currentValue);
  26241. weights.push(runtimeAnimation.weight / normalizer);
  26242. }
  26243. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26244. var cumulativeAmount = 0;
  26245. var cumulativeQuaternion = null;
  26246. for (var index = 0; index < quaternions.length;) {
  26247. if (!cumulativeQuaternion) {
  26248. BABYLON.Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion);
  26249. cumulativeQuaternion = refQuaternion;
  26250. cumulativeAmount = weights[index] + weights[index + 1];
  26251. index += 2;
  26252. continue;
  26253. }
  26254. cumulativeAmount += weights[index];
  26255. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26256. index++;
  26257. }
  26258. return cumulativeQuaternion;
  26259. };
  26260. Scene.prototype._processLateAnimationBindings = function () {
  26261. if (!this._registeredForLateAnimationBindings.length) {
  26262. return;
  26263. }
  26264. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26265. var target = this._registeredForLateAnimationBindings.data[index];
  26266. for (var path in target._lateAnimationHolders) {
  26267. var holder = target._lateAnimationHolders[path];
  26268. var originalAnimation = holder.animations[0];
  26269. var originalValue = holder.originalValue;
  26270. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26271. var finalValue = target[path];
  26272. if (matrixDecomposeMode) {
  26273. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26274. }
  26275. else {
  26276. var quaternionMode = originalValue.w !== undefined;
  26277. if (quaternionMode) {
  26278. finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || BABYLON.Quaternion.Identity());
  26279. }
  26280. else {
  26281. var startIndex = 0;
  26282. var normalizer = 1.0;
  26283. if (holder.totalWeight < 1.0) {
  26284. // We need to mix the original value in
  26285. if (originalValue.scale) {
  26286. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26287. }
  26288. else {
  26289. finalValue = originalValue * (1.0 - holder.totalWeight);
  26290. }
  26291. }
  26292. else {
  26293. // We need to normalize the weights
  26294. normalizer = holder.totalWeight;
  26295. var scale_1 = originalAnimation.weight / normalizer;
  26296. if (scale_1 !== 1) {
  26297. if (originalAnimation.currentValue.scale) {
  26298. finalValue = originalAnimation.currentValue.scale(scale_1);
  26299. }
  26300. else {
  26301. finalValue = originalAnimation.currentValue * scale_1;
  26302. }
  26303. }
  26304. else {
  26305. finalValue = originalAnimation.currentValue;
  26306. }
  26307. startIndex = 1;
  26308. }
  26309. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26310. var runtimeAnimation = holder.animations[animIndex];
  26311. var scale = runtimeAnimation.weight / normalizer;
  26312. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26313. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26314. }
  26315. else {
  26316. finalValue += runtimeAnimation.currentValue * scale;
  26317. }
  26318. }
  26319. }
  26320. }
  26321. target[path] = finalValue;
  26322. }
  26323. target._lateAnimationHolders = {};
  26324. }
  26325. this._registeredForLateAnimationBindings.reset();
  26326. };
  26327. // Matrix
  26328. /** @hidden */
  26329. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26330. this._useAlternateCameraConfiguration = active;
  26331. };
  26332. /**
  26333. * Gets the current view matrix
  26334. * @returns a Matrix
  26335. */
  26336. Scene.prototype.getViewMatrix = function () {
  26337. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26338. };
  26339. /**
  26340. * Gets the current projection matrix
  26341. * @returns a Matrix
  26342. */
  26343. Scene.prototype.getProjectionMatrix = function () {
  26344. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26345. };
  26346. /**
  26347. * Gets the current transform matrix
  26348. * @returns a Matrix made of View * Projection
  26349. */
  26350. Scene.prototype.getTransformMatrix = function () {
  26351. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26352. };
  26353. /**
  26354. * Sets the current transform matrix
  26355. * @param view defines the View matrix to use
  26356. * @param projection defines the Projection matrix to use
  26357. */
  26358. Scene.prototype.setTransformMatrix = function (view, projection) {
  26359. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26360. return;
  26361. }
  26362. this._viewUpdateFlag = view.updateFlag;
  26363. this._projectionUpdateFlag = projection.updateFlag;
  26364. this._viewMatrix = view;
  26365. this._projectionMatrix = projection;
  26366. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26367. // Update frustum
  26368. if (!this._frustumPlanes) {
  26369. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26370. }
  26371. else {
  26372. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26373. }
  26374. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26375. var otherCamera = this.activeCamera._alternateCamera;
  26376. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26377. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26378. }
  26379. if (this._sceneUbo.useUbo) {
  26380. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26381. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26382. this._sceneUbo.update();
  26383. }
  26384. };
  26385. /** @hidden */
  26386. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26387. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26388. return;
  26389. }
  26390. this._alternateViewUpdateFlag = view.updateFlag;
  26391. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26392. this._alternateViewMatrix = view;
  26393. this._alternateProjectionMatrix = projection;
  26394. if (!this._alternateTransformMatrix) {
  26395. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26396. }
  26397. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26398. if (!this._alternateSceneUbo) {
  26399. this._createAlternateUbo();
  26400. }
  26401. if (this._alternateSceneUbo.useUbo) {
  26402. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26403. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26404. this._alternateSceneUbo.update();
  26405. }
  26406. };
  26407. /**
  26408. * Gets the uniform buffer used to store scene data
  26409. * @returns a UniformBuffer
  26410. */
  26411. Scene.prototype.getSceneUniformBuffer = function () {
  26412. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26413. };
  26414. /**
  26415. * Gets an unique (relatively to the current scene) Id
  26416. * @returns an unique number for the scene
  26417. */
  26418. Scene.prototype.getUniqueId = function () {
  26419. var result = Scene._uniqueIdCounter;
  26420. Scene._uniqueIdCounter++;
  26421. return result;
  26422. };
  26423. /**
  26424. * Add a mesh to the list of scene's meshes
  26425. * @param newMesh defines the mesh to add
  26426. * @param recursive if all child meshes should also be added to the scene
  26427. */
  26428. Scene.prototype.addMesh = function (newMesh, recursive) {
  26429. var _this = this;
  26430. if (recursive === void 0) { recursive = false; }
  26431. this.meshes.push(newMesh);
  26432. //notify the collision coordinator
  26433. if (this.collisionCoordinator) {
  26434. this.collisionCoordinator.onMeshAdded(newMesh);
  26435. }
  26436. newMesh._resyncLightSources();
  26437. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26438. if (recursive) {
  26439. newMesh.getChildMeshes().forEach(function (m) {
  26440. _this.addMesh(m);
  26441. });
  26442. }
  26443. };
  26444. /**
  26445. * Remove a mesh for the list of scene's meshes
  26446. * @param toRemove defines the mesh to remove
  26447. * @param recursive if all child meshes should also be removed from the scene
  26448. * @returns the index where the mesh was in the mesh list
  26449. */
  26450. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26451. var _this = this;
  26452. if (recursive === void 0) { recursive = false; }
  26453. var index = this.meshes.indexOf(toRemove);
  26454. if (index !== -1) {
  26455. // Remove from the scene if mesh found
  26456. this.meshes.splice(index, 1);
  26457. }
  26458. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26459. if (recursive) {
  26460. toRemove.getChildMeshes().forEach(function (m) {
  26461. _this.removeMesh(m);
  26462. });
  26463. }
  26464. return index;
  26465. };
  26466. /**
  26467. * Add a transform node to the list of scene's transform nodes
  26468. * @param newTransformNode defines the transform node to add
  26469. */
  26470. Scene.prototype.addTransformNode = function (newTransformNode) {
  26471. this.transformNodes.push(newTransformNode);
  26472. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26473. };
  26474. /**
  26475. * Remove a transform node for the list of scene's transform nodes
  26476. * @param toRemove defines the transform node to remove
  26477. * @returns the index where the transform node was in the transform node list
  26478. */
  26479. Scene.prototype.removeTransformNode = function (toRemove) {
  26480. var index = this.transformNodes.indexOf(toRemove);
  26481. if (index !== -1) {
  26482. // Remove from the scene if found
  26483. this.transformNodes.splice(index, 1);
  26484. }
  26485. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26486. return index;
  26487. };
  26488. /**
  26489. * Remove a skeleton for the list of scene's skeletons
  26490. * @param toRemove defines the skeleton to remove
  26491. * @returns the index where the skeleton was in the skeleton list
  26492. */
  26493. Scene.prototype.removeSkeleton = function (toRemove) {
  26494. var index = this.skeletons.indexOf(toRemove);
  26495. if (index !== -1) {
  26496. // Remove from the scene if found
  26497. this.skeletons.splice(index, 1);
  26498. }
  26499. return index;
  26500. };
  26501. /**
  26502. * Remove a morph target for the list of scene's morph targets
  26503. * @param toRemove defines the morph target to remove
  26504. * @returns the index where the morph target was in the morph target list
  26505. */
  26506. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26507. var index = this.morphTargetManagers.indexOf(toRemove);
  26508. if (index !== -1) {
  26509. // Remove from the scene if found
  26510. this.morphTargetManagers.splice(index, 1);
  26511. }
  26512. return index;
  26513. };
  26514. /**
  26515. * Remove a light for the list of scene's lights
  26516. * @param toRemove defines the light to remove
  26517. * @returns the index where the light was in the light list
  26518. */
  26519. Scene.prototype.removeLight = function (toRemove) {
  26520. var index = this.lights.indexOf(toRemove);
  26521. if (index !== -1) {
  26522. // Remove from meshes
  26523. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26524. var mesh = _a[_i];
  26525. mesh._removeLightSource(toRemove);
  26526. }
  26527. // Remove from the scene if mesh found
  26528. this.lights.splice(index, 1);
  26529. this.sortLightsByPriority();
  26530. }
  26531. this.onLightRemovedObservable.notifyObservers(toRemove);
  26532. return index;
  26533. };
  26534. /**
  26535. * Remove a camera for the list of scene's cameras
  26536. * @param toRemove defines the camera to remove
  26537. * @returns the index where the camera was in the camera list
  26538. */
  26539. Scene.prototype.removeCamera = function (toRemove) {
  26540. var index = this.cameras.indexOf(toRemove);
  26541. if (index !== -1) {
  26542. // Remove from the scene if mesh found
  26543. this.cameras.splice(index, 1);
  26544. }
  26545. // Remove from activeCameras
  26546. var index2 = this.activeCameras.indexOf(toRemove);
  26547. if (index2 !== -1) {
  26548. // Remove from the scene if mesh found
  26549. this.activeCameras.splice(index2, 1);
  26550. }
  26551. // Reset the activeCamera
  26552. if (this.activeCamera === toRemove) {
  26553. if (this.cameras.length > 0) {
  26554. this.activeCamera = this.cameras[0];
  26555. }
  26556. else {
  26557. this.activeCamera = null;
  26558. }
  26559. }
  26560. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26561. return index;
  26562. };
  26563. /**
  26564. * Remove a particle system for the list of scene's particle systems
  26565. * @param toRemove defines the particle system to remove
  26566. * @returns the index where the particle system was in the particle system list
  26567. */
  26568. Scene.prototype.removeParticleSystem = function (toRemove) {
  26569. var index = this.particleSystems.indexOf(toRemove);
  26570. if (index !== -1) {
  26571. this.particleSystems.splice(index, 1);
  26572. }
  26573. return index;
  26574. };
  26575. /**
  26576. * Remove a animation for the list of scene's animations
  26577. * @param toRemove defines the animation to remove
  26578. * @returns the index where the animation was in the animation list
  26579. */
  26580. Scene.prototype.removeAnimation = function (toRemove) {
  26581. var index = this.animations.indexOf(toRemove);
  26582. if (index !== -1) {
  26583. this.animations.splice(index, 1);
  26584. }
  26585. return index;
  26586. };
  26587. /**
  26588. * Removes the given animation group from this scene.
  26589. * @param toRemove The animation group to remove
  26590. * @returns The index of the removed animation group
  26591. */
  26592. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26593. var index = this.animationGroups.indexOf(toRemove);
  26594. if (index !== -1) {
  26595. this.animationGroups.splice(index, 1);
  26596. }
  26597. return index;
  26598. };
  26599. /**
  26600. * Removes the given multi-material from this scene.
  26601. * @param toRemove The multi-material to remove
  26602. * @returns The index of the removed multi-material
  26603. */
  26604. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26605. var index = this.multiMaterials.indexOf(toRemove);
  26606. if (index !== -1) {
  26607. this.multiMaterials.splice(index, 1);
  26608. }
  26609. return index;
  26610. };
  26611. /**
  26612. * Removes the given material from this scene.
  26613. * @param toRemove The material to remove
  26614. * @returns The index of the removed material
  26615. */
  26616. Scene.prototype.removeMaterial = function (toRemove) {
  26617. var index = this.materials.indexOf(toRemove);
  26618. if (index !== -1) {
  26619. this.materials.splice(index, 1);
  26620. }
  26621. return index;
  26622. };
  26623. /**
  26624. * Removes the given action manager from this scene.
  26625. * @param toRemove The action manager to remove
  26626. * @returns The index of the removed action manager
  26627. */
  26628. Scene.prototype.removeActionManager = function (toRemove) {
  26629. var index = this.actionManagers.indexOf(toRemove);
  26630. if (index !== -1) {
  26631. this.actionManagers.splice(index, 1);
  26632. }
  26633. return index;
  26634. };
  26635. /**
  26636. * Removes the given texture from this scene.
  26637. * @param toRemove The texture to remove
  26638. * @returns The index of the removed texture
  26639. */
  26640. Scene.prototype.removeTexture = function (toRemove) {
  26641. var index = this.textures.indexOf(toRemove);
  26642. if (index !== -1) {
  26643. this.textures.splice(index, 1);
  26644. }
  26645. return index;
  26646. };
  26647. /**
  26648. * Adds the given light to this scene
  26649. * @param newLight The light to add
  26650. */
  26651. Scene.prototype.addLight = function (newLight) {
  26652. this.lights.push(newLight);
  26653. this.sortLightsByPriority();
  26654. // Add light to all meshes (To support if the light is removed and then readded)
  26655. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26656. var mesh = _a[_i];
  26657. if (mesh._lightSources.indexOf(newLight) === -1) {
  26658. mesh._lightSources.push(newLight);
  26659. mesh._resyncLightSources();
  26660. }
  26661. }
  26662. this.onNewLightAddedObservable.notifyObservers(newLight);
  26663. };
  26664. /**
  26665. * Sorts the list list based on light priorities
  26666. */
  26667. Scene.prototype.sortLightsByPriority = function () {
  26668. if (this.requireLightSorting) {
  26669. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26670. }
  26671. };
  26672. /**
  26673. * Adds the given camera to this scene
  26674. * @param newCamera The camera to add
  26675. */
  26676. Scene.prototype.addCamera = function (newCamera) {
  26677. this.cameras.push(newCamera);
  26678. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26679. };
  26680. /**
  26681. * Adds the given skeleton to this scene
  26682. * @param newSkeleton The skeleton to add
  26683. */
  26684. Scene.prototype.addSkeleton = function (newSkeleton) {
  26685. this.skeletons.push(newSkeleton);
  26686. };
  26687. /**
  26688. * Adds the given particle system to this scene
  26689. * @param newParticleSystem The particle system to add
  26690. */
  26691. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26692. this.particleSystems.push(newParticleSystem);
  26693. };
  26694. /**
  26695. * Adds the given animation to this scene
  26696. * @param newAnimation The animation to add
  26697. */
  26698. Scene.prototype.addAnimation = function (newAnimation) {
  26699. this.animations.push(newAnimation);
  26700. };
  26701. /**
  26702. * Adds the given animation group to this scene.
  26703. * @param newAnimationGroup The animation group to add
  26704. */
  26705. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26706. this.animationGroups.push(newAnimationGroup);
  26707. };
  26708. /**
  26709. * Adds the given multi-material to this scene
  26710. * @param newMultiMaterial The multi-material to add
  26711. */
  26712. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26713. this.multiMaterials.push(newMultiMaterial);
  26714. };
  26715. /**
  26716. * Adds the given material to this scene
  26717. * @param newMaterial The material to add
  26718. */
  26719. Scene.prototype.addMaterial = function (newMaterial) {
  26720. this.materials.push(newMaterial);
  26721. };
  26722. /**
  26723. * Adds the given morph target to this scene
  26724. * @param newMorphTargetManager The morph target to add
  26725. */
  26726. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26727. this.morphTargetManagers.push(newMorphTargetManager);
  26728. };
  26729. /**
  26730. * Adds the given geometry to this scene
  26731. * @param newGeometry The geometry to add
  26732. */
  26733. Scene.prototype.addGeometry = function (newGeometry) {
  26734. this.geometries.push(newGeometry);
  26735. };
  26736. /**
  26737. * Adds the given action manager to this scene
  26738. * @param newActionManager The action manager to add
  26739. */
  26740. Scene.prototype.addActionManager = function (newActionManager) {
  26741. this.actionManagers.push(newActionManager);
  26742. };
  26743. /**
  26744. * Adds the given texture to this scene.
  26745. * @param newTexture The texture to add
  26746. */
  26747. Scene.prototype.addTexture = function (newTexture) {
  26748. this.textures.push(newTexture);
  26749. };
  26750. /**
  26751. * Switch active camera
  26752. * @param newCamera defines the new active camera
  26753. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26754. */
  26755. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26756. if (attachControl === void 0) { attachControl = true; }
  26757. var canvas = this._engine.getRenderingCanvas();
  26758. if (!canvas) {
  26759. return;
  26760. }
  26761. if (this.activeCamera) {
  26762. this.activeCamera.detachControl(canvas);
  26763. }
  26764. this.activeCamera = newCamera;
  26765. if (attachControl) {
  26766. newCamera.attachControl(canvas);
  26767. }
  26768. };
  26769. /**
  26770. * sets the active camera of the scene using its ID
  26771. * @param id defines the camera's ID
  26772. * @return the new active camera or null if none found.
  26773. */
  26774. Scene.prototype.setActiveCameraByID = function (id) {
  26775. var camera = this.getCameraByID(id);
  26776. if (camera) {
  26777. this.activeCamera = camera;
  26778. return camera;
  26779. }
  26780. return null;
  26781. };
  26782. /**
  26783. * sets the active camera of the scene using its name
  26784. * @param name defines the camera's name
  26785. * @returns the new active camera or null if none found.
  26786. */
  26787. Scene.prototype.setActiveCameraByName = function (name) {
  26788. var camera = this.getCameraByName(name);
  26789. if (camera) {
  26790. this.activeCamera = camera;
  26791. return camera;
  26792. }
  26793. return null;
  26794. };
  26795. /**
  26796. * get an animation group using its name
  26797. * @param name defines the material's name
  26798. * @return the animation group or null if none found.
  26799. */
  26800. Scene.prototype.getAnimationGroupByName = function (name) {
  26801. for (var index = 0; index < this.animationGroups.length; index++) {
  26802. if (this.animationGroups[index].name === name) {
  26803. return this.animationGroups[index];
  26804. }
  26805. }
  26806. return null;
  26807. };
  26808. /**
  26809. * get a material using its id
  26810. * @param id defines the material's ID
  26811. * @return the material or null if none found.
  26812. */
  26813. Scene.prototype.getMaterialByID = function (id) {
  26814. for (var index = 0; index < this.materials.length; index++) {
  26815. if (this.materials[index].id === id) {
  26816. return this.materials[index];
  26817. }
  26818. }
  26819. return null;
  26820. };
  26821. /**
  26822. * Gets a material using its name
  26823. * @param name defines the material's name
  26824. * @return the material or null if none found.
  26825. */
  26826. Scene.prototype.getMaterialByName = function (name) {
  26827. for (var index = 0; index < this.materials.length; index++) {
  26828. if (this.materials[index].name === name) {
  26829. return this.materials[index];
  26830. }
  26831. }
  26832. return null;
  26833. };
  26834. /**
  26835. * Gets a camera using its id
  26836. * @param id defines the id to look for
  26837. * @returns the camera or null if not found
  26838. */
  26839. Scene.prototype.getCameraByID = function (id) {
  26840. for (var index = 0; index < this.cameras.length; index++) {
  26841. if (this.cameras[index].id === id) {
  26842. return this.cameras[index];
  26843. }
  26844. }
  26845. return null;
  26846. };
  26847. /**
  26848. * Gets a camera using its unique id
  26849. * @param uniqueId defines the unique id to look for
  26850. * @returns the camera or null if not found
  26851. */
  26852. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26853. for (var index = 0; index < this.cameras.length; index++) {
  26854. if (this.cameras[index].uniqueId === uniqueId) {
  26855. return this.cameras[index];
  26856. }
  26857. }
  26858. return null;
  26859. };
  26860. /**
  26861. * Gets a camera using its name
  26862. * @param name defines the camera's name
  26863. * @return the camera or null if none found.
  26864. */
  26865. Scene.prototype.getCameraByName = function (name) {
  26866. for (var index = 0; index < this.cameras.length; index++) {
  26867. if (this.cameras[index].name === name) {
  26868. return this.cameras[index];
  26869. }
  26870. }
  26871. return null;
  26872. };
  26873. /**
  26874. * Gets a bone using its id
  26875. * @param id defines the bone's id
  26876. * @return the bone or null if not found
  26877. */
  26878. Scene.prototype.getBoneByID = function (id) {
  26879. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26880. var skeleton = this.skeletons[skeletonIndex];
  26881. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26882. if (skeleton.bones[boneIndex].id === id) {
  26883. return skeleton.bones[boneIndex];
  26884. }
  26885. }
  26886. }
  26887. return null;
  26888. };
  26889. /**
  26890. * Gets a bone using its id
  26891. * @param name defines the bone's name
  26892. * @return the bone or null if not found
  26893. */
  26894. Scene.prototype.getBoneByName = function (name) {
  26895. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26896. var skeleton = this.skeletons[skeletonIndex];
  26897. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26898. if (skeleton.bones[boneIndex].name === name) {
  26899. return skeleton.bones[boneIndex];
  26900. }
  26901. }
  26902. }
  26903. return null;
  26904. };
  26905. /**
  26906. * Gets a light node using its name
  26907. * @param name defines the the light's name
  26908. * @return the light or null if none found.
  26909. */
  26910. Scene.prototype.getLightByName = function (name) {
  26911. for (var index = 0; index < this.lights.length; index++) {
  26912. if (this.lights[index].name === name) {
  26913. return this.lights[index];
  26914. }
  26915. }
  26916. return null;
  26917. };
  26918. /**
  26919. * Gets a light node using its id
  26920. * @param id defines the light's id
  26921. * @return the light or null if none found.
  26922. */
  26923. Scene.prototype.getLightByID = function (id) {
  26924. for (var index = 0; index < this.lights.length; index++) {
  26925. if (this.lights[index].id === id) {
  26926. return this.lights[index];
  26927. }
  26928. }
  26929. return null;
  26930. };
  26931. /**
  26932. * Gets a light node using its scene-generated unique ID
  26933. * @param uniqueId defines the light's unique id
  26934. * @return the light or null if none found.
  26935. */
  26936. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26937. for (var index = 0; index < this.lights.length; index++) {
  26938. if (this.lights[index].uniqueId === uniqueId) {
  26939. return this.lights[index];
  26940. }
  26941. }
  26942. return null;
  26943. };
  26944. /**
  26945. * Gets a particle system by id
  26946. * @param id defines the particle system id
  26947. * @return the corresponding system or null if none found
  26948. */
  26949. Scene.prototype.getParticleSystemByID = function (id) {
  26950. for (var index = 0; index < this.particleSystems.length; index++) {
  26951. if (this.particleSystems[index].id === id) {
  26952. return this.particleSystems[index];
  26953. }
  26954. }
  26955. return null;
  26956. };
  26957. /**
  26958. * Gets a geometry using its ID
  26959. * @param id defines the geometry's id
  26960. * @return the geometry or null if none found.
  26961. */
  26962. Scene.prototype.getGeometryByID = function (id) {
  26963. for (var index = 0; index < this.geometries.length; index++) {
  26964. if (this.geometries[index].id === id) {
  26965. return this.geometries[index];
  26966. }
  26967. }
  26968. return null;
  26969. };
  26970. /**
  26971. * Add a new geometry to this scene
  26972. * @param geometry defines the geometry to be added to the scene.
  26973. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26974. * @return a boolean defining if the geometry was added or not
  26975. */
  26976. Scene.prototype.pushGeometry = function (geometry, force) {
  26977. if (!force && this.getGeometryByID(geometry.id)) {
  26978. return false;
  26979. }
  26980. this.geometries.push(geometry);
  26981. //notify the collision coordinator
  26982. if (this.collisionCoordinator) {
  26983. this.collisionCoordinator.onGeometryAdded(geometry);
  26984. }
  26985. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26986. return true;
  26987. };
  26988. /**
  26989. * Removes an existing geometry
  26990. * @param geometry defines the geometry to be removed from the scene
  26991. * @return a boolean defining if the geometry was removed or not
  26992. */
  26993. Scene.prototype.removeGeometry = function (geometry) {
  26994. var index = this.geometries.indexOf(geometry);
  26995. if (index > -1) {
  26996. this.geometries.splice(index, 1);
  26997. //notify the collision coordinator
  26998. if (this.collisionCoordinator) {
  26999. this.collisionCoordinator.onGeometryDeleted(geometry);
  27000. }
  27001. this.onGeometryRemovedObservable.notifyObservers(geometry);
  27002. return true;
  27003. }
  27004. return false;
  27005. };
  27006. /**
  27007. * Gets the list of geometries attached to the scene
  27008. * @returns an array of Geometry
  27009. */
  27010. Scene.prototype.getGeometries = function () {
  27011. return this.geometries;
  27012. };
  27013. /**
  27014. * Gets the first added mesh found of a given ID
  27015. * @param id defines the id to search for
  27016. * @return the mesh found or null if not found at all
  27017. */
  27018. Scene.prototype.getMeshByID = function (id) {
  27019. for (var index = 0; index < this.meshes.length; index++) {
  27020. if (this.meshes[index].id === id) {
  27021. return this.meshes[index];
  27022. }
  27023. }
  27024. return null;
  27025. };
  27026. /**
  27027. * Gets a list of meshes using their id
  27028. * @param id defines the id to search for
  27029. * @returns a list of meshes
  27030. */
  27031. Scene.prototype.getMeshesByID = function (id) {
  27032. return this.meshes.filter(function (m) {
  27033. return m.id === id;
  27034. });
  27035. };
  27036. /**
  27037. * Gets the first added transform node found of a given ID
  27038. * @param id defines the id to search for
  27039. * @return the found transform node or null if not found at all.
  27040. */
  27041. Scene.prototype.getTransformNodeByID = function (id) {
  27042. for (var index = 0; index < this.transformNodes.length; index++) {
  27043. if (this.transformNodes[index].id === id) {
  27044. return this.transformNodes[index];
  27045. }
  27046. }
  27047. return null;
  27048. };
  27049. /**
  27050. * Gets a list of transform nodes using their id
  27051. * @param id defines the id to search for
  27052. * @returns a list of transform nodes
  27053. */
  27054. Scene.prototype.getTransformNodesByID = function (id) {
  27055. return this.transformNodes.filter(function (m) {
  27056. return m.id === id;
  27057. });
  27058. };
  27059. /**
  27060. * Gets a mesh with its auto-generated unique id
  27061. * @param uniqueId defines the unique id to search for
  27062. * @return the found mesh or null if not found at all.
  27063. */
  27064. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27065. for (var index = 0; index < this.meshes.length; index++) {
  27066. if (this.meshes[index].uniqueId === uniqueId) {
  27067. return this.meshes[index];
  27068. }
  27069. }
  27070. return null;
  27071. };
  27072. /**
  27073. * Gets a the last added mesh using a given id
  27074. * @param id defines the id to search for
  27075. * @return the found mesh or null if not found at all.
  27076. */
  27077. Scene.prototype.getLastMeshByID = function (id) {
  27078. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27079. if (this.meshes[index].id === id) {
  27080. return this.meshes[index];
  27081. }
  27082. }
  27083. return null;
  27084. };
  27085. /**
  27086. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27087. * @param id defines the id to search for
  27088. * @return the found node or null if not found at all
  27089. */
  27090. Scene.prototype.getLastEntryByID = function (id) {
  27091. var index;
  27092. for (index = this.meshes.length - 1; index >= 0; index--) {
  27093. if (this.meshes[index].id === id) {
  27094. return this.meshes[index];
  27095. }
  27096. }
  27097. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27098. if (this.transformNodes[index].id === id) {
  27099. return this.transformNodes[index];
  27100. }
  27101. }
  27102. for (index = this.cameras.length - 1; index >= 0; index--) {
  27103. if (this.cameras[index].id === id) {
  27104. return this.cameras[index];
  27105. }
  27106. }
  27107. for (index = this.lights.length - 1; index >= 0; index--) {
  27108. if (this.lights[index].id === id) {
  27109. return this.lights[index];
  27110. }
  27111. }
  27112. return null;
  27113. };
  27114. /**
  27115. * Gets a node (Mesh, Camera, Light) using a given id
  27116. * @param id defines the id to search for
  27117. * @return the found node or null if not found at all
  27118. */
  27119. Scene.prototype.getNodeByID = function (id) {
  27120. var mesh = this.getMeshByID(id);
  27121. if (mesh) {
  27122. return mesh;
  27123. }
  27124. var light = this.getLightByID(id);
  27125. if (light) {
  27126. return light;
  27127. }
  27128. var camera = this.getCameraByID(id);
  27129. if (camera) {
  27130. return camera;
  27131. }
  27132. var bone = this.getBoneByID(id);
  27133. return bone;
  27134. };
  27135. /**
  27136. * Gets a node (Mesh, Camera, Light) using a given name
  27137. * @param name defines the name to search for
  27138. * @return the found node or null if not found at all.
  27139. */
  27140. Scene.prototype.getNodeByName = function (name) {
  27141. var mesh = this.getMeshByName(name);
  27142. if (mesh) {
  27143. return mesh;
  27144. }
  27145. var light = this.getLightByName(name);
  27146. if (light) {
  27147. return light;
  27148. }
  27149. var camera = this.getCameraByName(name);
  27150. if (camera) {
  27151. return camera;
  27152. }
  27153. var bone = this.getBoneByName(name);
  27154. return bone;
  27155. };
  27156. /**
  27157. * Gets a mesh using a given name
  27158. * @param name defines the name to search for
  27159. * @return the found mesh or null if not found at all.
  27160. */
  27161. Scene.prototype.getMeshByName = function (name) {
  27162. for (var index = 0; index < this.meshes.length; index++) {
  27163. if (this.meshes[index].name === name) {
  27164. return this.meshes[index];
  27165. }
  27166. }
  27167. return null;
  27168. };
  27169. /**
  27170. * Gets a transform node using a given name
  27171. * @param name defines the name to search for
  27172. * @return the found transform node or null if not found at all.
  27173. */
  27174. Scene.prototype.getTransformNodeByName = function (name) {
  27175. for (var index = 0; index < this.transformNodes.length; index++) {
  27176. if (this.transformNodes[index].name === name) {
  27177. return this.transformNodes[index];
  27178. }
  27179. }
  27180. return null;
  27181. };
  27182. /**
  27183. * Gets a sound using a given name
  27184. * @param name defines the name to search for
  27185. * @return the found sound or null if not found at all.
  27186. */
  27187. Scene.prototype.getSoundByName = function (name) {
  27188. var index;
  27189. if (BABYLON.AudioEngine) {
  27190. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  27191. if (this.mainSoundTrack.soundCollection[index].name === name) {
  27192. return this.mainSoundTrack.soundCollection[index];
  27193. }
  27194. }
  27195. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27196. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27197. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27198. return this.soundTracks[sdIndex].soundCollection[index];
  27199. }
  27200. }
  27201. }
  27202. }
  27203. return null;
  27204. };
  27205. /**
  27206. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27207. * @param id defines the id to search for
  27208. * @return the found skeleton or null if not found at all.
  27209. */
  27210. Scene.prototype.getLastSkeletonByID = function (id) {
  27211. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27212. if (this.skeletons[index].id === id) {
  27213. return this.skeletons[index];
  27214. }
  27215. }
  27216. return null;
  27217. };
  27218. /**
  27219. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27220. * @param id defines the id to search for
  27221. * @return the found skeleton or null if not found at all.
  27222. */
  27223. Scene.prototype.getSkeletonById = function (id) {
  27224. for (var index = 0; index < this.skeletons.length; index++) {
  27225. if (this.skeletons[index].id === id) {
  27226. return this.skeletons[index];
  27227. }
  27228. }
  27229. return null;
  27230. };
  27231. /**
  27232. * Gets a skeleton using a given name
  27233. * @param name defines the name to search for
  27234. * @return the found skeleton or null if not found at all.
  27235. */
  27236. Scene.prototype.getSkeletonByName = function (name) {
  27237. for (var index = 0; index < this.skeletons.length; index++) {
  27238. if (this.skeletons[index].name === name) {
  27239. return this.skeletons[index];
  27240. }
  27241. }
  27242. return null;
  27243. };
  27244. /**
  27245. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27246. * @param id defines the id to search for
  27247. * @return the found morph target manager or null if not found at all.
  27248. */
  27249. Scene.prototype.getMorphTargetManagerById = function (id) {
  27250. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27251. if (this.morphTargetManagers[index].uniqueId === id) {
  27252. return this.morphTargetManagers[index];
  27253. }
  27254. }
  27255. return null;
  27256. };
  27257. /**
  27258. * Gets a boolean indicating if the given mesh is active
  27259. * @param mesh defines the mesh to look for
  27260. * @returns true if the mesh is in the active list
  27261. */
  27262. Scene.prototype.isActiveMesh = function (mesh) {
  27263. return (this._activeMeshes.indexOf(mesh) !== -1);
  27264. };
  27265. Object.defineProperty(Scene.prototype, "uid", {
  27266. /**
  27267. * Return a unique id as a string which can serve as an identifier for the scene
  27268. */
  27269. get: function () {
  27270. if (!this._uid) {
  27271. this._uid = BABYLON.Tools.RandomId();
  27272. }
  27273. return this._uid;
  27274. },
  27275. enumerable: true,
  27276. configurable: true
  27277. });
  27278. /**
  27279. * Add an externaly attached data from its key.
  27280. * This method call will fail and return false, if such key already exists.
  27281. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27282. * @param key the unique key that identifies the data
  27283. * @param data the data object to associate to the key for this Engine instance
  27284. * @return true if no such key were already present and the data was added successfully, false otherwise
  27285. */
  27286. Scene.prototype.addExternalData = function (key, data) {
  27287. if (!this._externalData) {
  27288. this._externalData = new BABYLON.StringDictionary();
  27289. }
  27290. return this._externalData.add(key, data);
  27291. };
  27292. /**
  27293. * Get an externaly attached data from its key
  27294. * @param key the unique key that identifies the data
  27295. * @return the associated data, if present (can be null), or undefined if not present
  27296. */
  27297. Scene.prototype.getExternalData = function (key) {
  27298. if (!this._externalData) {
  27299. return null;
  27300. }
  27301. return this._externalData.get(key);
  27302. };
  27303. /**
  27304. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27305. * @param key the unique key that identifies the data
  27306. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27307. * @return the associated data, can be null if the factory returned null.
  27308. */
  27309. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27310. if (!this._externalData) {
  27311. this._externalData = new BABYLON.StringDictionary();
  27312. }
  27313. return this._externalData.getOrAddWithFactory(key, factory);
  27314. };
  27315. /**
  27316. * Remove an externaly attached data from the Engine instance
  27317. * @param key the unique key that identifies the data
  27318. * @return true if the data was successfully removed, false if it doesn't exist
  27319. */
  27320. Scene.prototype.removeExternalData = function (key) {
  27321. return this._externalData.remove(key);
  27322. };
  27323. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27324. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27325. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  27326. var step = _a[_i];
  27327. step.action(mesh, subMesh);
  27328. }
  27329. var material = subMesh.getMaterial();
  27330. if (material !== null && material !== undefined) {
  27331. // Render targets
  27332. if (material.getRenderTargetTextures !== undefined) {
  27333. if (this._processedMaterials.indexOf(material) === -1) {
  27334. this._processedMaterials.push(material);
  27335. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27336. }
  27337. }
  27338. // Dispatch
  27339. this._activeIndices.addCount(subMesh.indexCount, false);
  27340. this._renderingManager.dispatch(subMesh, mesh, material);
  27341. }
  27342. }
  27343. };
  27344. /**
  27345. * Clear the processed materials smart array preventing retention point in material dispose.
  27346. */
  27347. Scene.prototype.freeProcessedMaterials = function () {
  27348. this._processedMaterials.dispose();
  27349. };
  27350. /**
  27351. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27352. */
  27353. Scene.prototype.freeActiveMeshes = function () {
  27354. this._activeMeshes.dispose();
  27355. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27356. this.activeCamera._activeMeshes.dispose();
  27357. }
  27358. if (this.activeCameras) {
  27359. for (var i = 0; i < this.activeCameras.length; i++) {
  27360. var activeCamera = this.activeCameras[i];
  27361. if (activeCamera && activeCamera._activeMeshes) {
  27362. activeCamera._activeMeshes.dispose();
  27363. }
  27364. }
  27365. }
  27366. };
  27367. /**
  27368. * Clear the info related to rendering groups preventing retention points during dispose.
  27369. */
  27370. Scene.prototype.freeRenderingGroups = function () {
  27371. if (this._renderingManager) {
  27372. this._renderingManager.freeRenderingGroups();
  27373. }
  27374. if (this.textures) {
  27375. for (var i = 0; i < this.textures.length; i++) {
  27376. var texture = this.textures[i];
  27377. if (texture && texture.renderList) {
  27378. texture.freeRenderingGroups();
  27379. }
  27380. }
  27381. }
  27382. };
  27383. /** @hidden */
  27384. Scene.prototype._isInIntermediateRendering = function () {
  27385. return this._intermediateRendering;
  27386. };
  27387. /**
  27388. * Defines the current active mesh candidate provider
  27389. * @param provider defines the provider to use
  27390. */
  27391. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27392. this._activeMeshCandidateProvider = provider;
  27393. };
  27394. /**
  27395. * Gets the current active mesh candidate provider
  27396. * @returns the current active mesh candidate provider
  27397. */
  27398. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27399. return this._activeMeshCandidateProvider;
  27400. };
  27401. /**
  27402. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27403. * @returns the current scene
  27404. */
  27405. Scene.prototype.freezeActiveMeshes = function () {
  27406. if (!this.activeCamera) {
  27407. return this;
  27408. }
  27409. if (!this._frustumPlanes) {
  27410. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27411. }
  27412. this._evaluateActiveMeshes();
  27413. this._activeMeshesFrozen = true;
  27414. return this;
  27415. };
  27416. /**
  27417. * Use this function to restart evaluating active meshes on every frame
  27418. * @returns the current scene
  27419. */
  27420. Scene.prototype.unfreezeActiveMeshes = function () {
  27421. this._activeMeshesFrozen = false;
  27422. return this;
  27423. };
  27424. Scene.prototype._evaluateActiveMeshes = function () {
  27425. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27426. return;
  27427. }
  27428. if (!this.activeCamera) {
  27429. return;
  27430. }
  27431. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27432. this.activeCamera._activeMeshes.reset();
  27433. this._activeMeshes.reset();
  27434. this._renderingManager.reset();
  27435. this._processedMaterials.reset();
  27436. this._activeParticleSystems.reset();
  27437. this._activeSkeletons.reset();
  27438. this._softwareSkinnedMeshes.reset();
  27439. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  27440. var step = _a[_i];
  27441. step.action();
  27442. }
  27443. // Meshes
  27444. var meshes;
  27445. var len;
  27446. var checkIsEnabled = true;
  27447. // Determine mesh candidates
  27448. if (this._activeMeshCandidateProvider !== undefined) {
  27449. // Use _activeMeshCandidateProvider
  27450. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27451. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27452. if (meshes !== undefined) {
  27453. len = meshes.length;
  27454. }
  27455. else {
  27456. len = 0;
  27457. }
  27458. }
  27459. else if (this._selectionOctree !== undefined) {
  27460. // Octree
  27461. var selection = this._selectionOctree.select(this._frustumPlanes);
  27462. meshes = selection.data;
  27463. len = selection.length;
  27464. }
  27465. else {
  27466. // Full scene traversal
  27467. len = this.meshes.length;
  27468. meshes = this.meshes;
  27469. }
  27470. // Check each mesh
  27471. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27472. mesh = meshes[meshIndex];
  27473. if (mesh.isBlocked) {
  27474. continue;
  27475. }
  27476. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27477. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27478. continue;
  27479. }
  27480. mesh.computeWorldMatrix();
  27481. // Intersections
  27482. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger)) {
  27483. this._meshesForIntersections.pushNoDuplicate(mesh);
  27484. }
  27485. // Switch to current LOD
  27486. meshLOD = mesh.getLOD(this.activeCamera);
  27487. if (meshLOD === undefined || meshLOD === null) {
  27488. continue;
  27489. }
  27490. mesh._preActivate();
  27491. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  27492. this._activeMeshes.push(mesh);
  27493. this.activeCamera._activeMeshes.push(mesh);
  27494. mesh._activate(this._renderId);
  27495. if (meshLOD !== mesh) {
  27496. meshLOD._activate(this._renderId);
  27497. }
  27498. this._activeMesh(mesh, meshLOD);
  27499. }
  27500. }
  27501. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27502. // Particle systems
  27503. if (this.particlesEnabled) {
  27504. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27505. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27506. var particleSystem = this.particleSystems[particleIndex];
  27507. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27508. continue;
  27509. }
  27510. var emitter = particleSystem.emitter;
  27511. if (!emitter.position || emitter.isEnabled()) {
  27512. this._activeParticleSystems.push(particleSystem);
  27513. particleSystem.animate();
  27514. this._renderingManager.dispatchParticles(particleSystem);
  27515. }
  27516. }
  27517. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27518. }
  27519. };
  27520. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27521. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27522. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27523. mesh.skeleton.prepare();
  27524. }
  27525. if (!mesh.computeBonesUsingShaders) {
  27526. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27527. }
  27528. }
  27529. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  27530. var step = _a[_i];
  27531. step.action(sourceMesh, mesh);
  27532. }
  27533. if (mesh !== undefined && mesh !== null
  27534. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27535. // Submeshes Octrees
  27536. var len;
  27537. var subMeshes;
  27538. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27539. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27540. len = intersections.length;
  27541. subMeshes = intersections.data;
  27542. }
  27543. else {
  27544. subMeshes = mesh.subMeshes;
  27545. len = subMeshes.length;
  27546. }
  27547. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27548. subMesh = subMeshes[subIndex];
  27549. this._evaluateSubMesh(subMesh, mesh);
  27550. }
  27551. }
  27552. };
  27553. /**
  27554. * Update the transform matrix to update from the current active camera
  27555. * @param force defines a boolean used to force the update even if cache is up to date
  27556. */
  27557. Scene.prototype.updateTransformMatrix = function (force) {
  27558. if (!this.activeCamera) {
  27559. return;
  27560. }
  27561. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27562. };
  27563. /**
  27564. * 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)
  27565. * @param alternateCamera defines the camera to use
  27566. */
  27567. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27568. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27569. };
  27570. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27571. if (camera && camera._skipRendering) {
  27572. return;
  27573. }
  27574. var engine = this._engine;
  27575. this.activeCamera = camera;
  27576. if (!this.activeCamera)
  27577. throw new Error("Active camera not set");
  27578. // Viewport
  27579. engine.setViewport(this.activeCamera.viewport);
  27580. // Camera
  27581. this.resetCachedMaterial();
  27582. this._renderId++;
  27583. this.updateTransformMatrix();
  27584. if (camera._alternateCamera) {
  27585. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27586. this._alternateRendering = true;
  27587. }
  27588. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27589. // Meshes
  27590. this._evaluateActiveMeshes();
  27591. // Software skinning
  27592. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27593. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27594. mesh.applySkeleton(mesh.skeleton);
  27595. }
  27596. // Render targets
  27597. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27598. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27599. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27600. }
  27601. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27602. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27603. }
  27604. if (this.renderTargetsEnabled) {
  27605. this._intermediateRendering = true;
  27606. if (this._renderTargets.length > 0) {
  27607. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27608. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27609. var renderTarget = this._renderTargets.data[renderIndex];
  27610. if (renderTarget._shouldRender()) {
  27611. this._renderId++;
  27612. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27613. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27614. }
  27615. }
  27616. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27617. this._renderId++;
  27618. }
  27619. for (var _i = 0, _a = this._cameraDrawRenderTargetStage; _i < _a.length; _i++) {
  27620. var step = _a[_i];
  27621. step.action(this.activeCamera);
  27622. }
  27623. this._intermediateRendering = false;
  27624. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  27625. }
  27626. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27627. // Prepare Frame
  27628. if (this.postProcessManager) {
  27629. this.postProcessManager._prepareFrame();
  27630. }
  27631. // Before Camera Draw
  27632. for (var _b = 0, _c = this._beforeCameraDrawStage; _b < _c.length; _b++) {
  27633. var step = _c[_b];
  27634. step.action(this.activeCamera);
  27635. }
  27636. // Render
  27637. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27638. this._renderingManager.render(null, null, true, true);
  27639. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27640. // After Camera Draw
  27641. for (var _d = 0, _e = this._afterCameraDrawStage; _d < _e.length; _d++) {
  27642. var step = _e[_d];
  27643. step.action(this.activeCamera);
  27644. }
  27645. // Finalize frame
  27646. if (this.postProcessManager) {
  27647. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27648. }
  27649. // Reset some special arrays
  27650. this._renderTargets.reset();
  27651. this._alternateRendering = false;
  27652. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27653. };
  27654. Scene.prototype._processSubCameras = function (camera) {
  27655. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27656. this._renderForCamera(camera);
  27657. return;
  27658. }
  27659. // rig cameras
  27660. for (var index = 0; index < camera._rigCameras.length; index++) {
  27661. this._renderForCamera(camera._rigCameras[index], camera);
  27662. }
  27663. this.activeCamera = camera;
  27664. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27665. };
  27666. Scene.prototype._checkIntersections = function () {
  27667. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27668. var sourceMesh = this._meshesForIntersections.data[index];
  27669. if (!sourceMesh.actionManager) {
  27670. continue;
  27671. }
  27672. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27673. var action = sourceMesh.actionManager.actions[actionIndex];
  27674. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27675. var parameters = action.getTriggerParameter();
  27676. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27677. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27678. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27679. if (areIntersecting && currentIntersectionInProgress === -1) {
  27680. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27681. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27682. sourceMesh._intersectionsInProgress.push(otherMesh);
  27683. }
  27684. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27685. sourceMesh._intersectionsInProgress.push(otherMesh);
  27686. }
  27687. }
  27688. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27689. //They intersected, and now they don't.
  27690. //is this trigger an exit trigger? execute an event.
  27691. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27692. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27693. }
  27694. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27695. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27696. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27697. return otherMesh === parameterMesh;
  27698. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27699. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27700. }
  27701. }
  27702. }
  27703. }
  27704. }
  27705. };
  27706. /**
  27707. * Render the scene
  27708. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27709. */
  27710. Scene.prototype.render = function (updateCameras) {
  27711. if (updateCameras === void 0) { updateCameras = true; }
  27712. if (this.isDisposed) {
  27713. return;
  27714. }
  27715. // Register components that have been associated lately to the scene.
  27716. this._registerTransientComponents();
  27717. this._activeParticles.fetchNewFrame();
  27718. this._totalVertices.fetchNewFrame();
  27719. this._activeIndices.fetchNewFrame();
  27720. this._activeBones.fetchNewFrame();
  27721. this._meshesForIntersections.reset();
  27722. this.resetCachedMaterial();
  27723. this.onBeforeAnimationsObservable.notifyObservers(this);
  27724. // Actions
  27725. if (this.actionManager) {
  27726. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27727. }
  27728. if (this._engine.isDeterministicLockStep()) {
  27729. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27730. var defaultFPS = (60.0 / 1000.0);
  27731. var defaultFrameTime = 1000 / 60; // frame time in MS
  27732. if (this._physicsEngine) {
  27733. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27734. }
  27735. var stepsTaken = 0;
  27736. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27737. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27738. internalSteps = Math.min(internalSteps, maxSubSteps);
  27739. do {
  27740. this.onBeforeStepObservable.notifyObservers(this);
  27741. // Animations
  27742. this._animationRatio = defaultFrameTime * defaultFPS;
  27743. this._animate();
  27744. this.onAfterAnimationsObservable.notifyObservers(this);
  27745. // Physics
  27746. if (this._physicsEngine) {
  27747. this.onBeforePhysicsObservable.notifyObservers(this);
  27748. this._physicsEngine._step(defaultFrameTime / 1000);
  27749. this.onAfterPhysicsObservable.notifyObservers(this);
  27750. }
  27751. this.onAfterStepObservable.notifyObservers(this);
  27752. this._currentStepId++;
  27753. stepsTaken++;
  27754. deltaTime -= defaultFrameTime;
  27755. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27756. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27757. }
  27758. else {
  27759. // Animations
  27760. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27761. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27762. this._animate();
  27763. this.onAfterAnimationsObservable.notifyObservers(this);
  27764. // Physics
  27765. if (this._physicsEngine) {
  27766. this.onBeforePhysicsObservable.notifyObservers(this);
  27767. this._physicsEngine._step(deltaTime / 1000.0);
  27768. this.onAfterPhysicsObservable.notifyObservers(this);
  27769. }
  27770. }
  27771. // Before camera update steps
  27772. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  27773. var step = _a[_i];
  27774. step.action();
  27775. }
  27776. // Update Cameras
  27777. if (updateCameras) {
  27778. if (this.activeCameras.length > 0) {
  27779. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27780. var camera = this.activeCameras[cameraIndex];
  27781. camera.update();
  27782. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27783. // rig cameras
  27784. for (var index = 0; index < camera._rigCameras.length; index++) {
  27785. camera._rigCameras[index].update();
  27786. }
  27787. }
  27788. }
  27789. }
  27790. else if (this.activeCamera) {
  27791. this.activeCamera.update();
  27792. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27793. // rig cameras
  27794. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27795. this.activeCamera._rigCameras[index].update();
  27796. }
  27797. }
  27798. }
  27799. }
  27800. // Before render
  27801. this.onBeforeRenderObservable.notifyObservers(this);
  27802. // Customs render targets
  27803. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27804. var engine = this.getEngine();
  27805. var currentActiveCamera = this.activeCamera;
  27806. if (this.renderTargetsEnabled) {
  27807. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27808. this._intermediateRendering = true;
  27809. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27810. var renderTarget = this.customRenderTargets[customIndex];
  27811. if (renderTarget._shouldRender()) {
  27812. this._renderId++;
  27813. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27814. if (!this.activeCamera)
  27815. throw new Error("Active camera not set");
  27816. // Viewport
  27817. engine.setViewport(this.activeCamera.viewport);
  27818. // Camera
  27819. this.updateTransformMatrix();
  27820. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27821. }
  27822. }
  27823. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27824. this._intermediateRendering = false;
  27825. this._renderId++;
  27826. }
  27827. // Restore back buffer
  27828. if (this.customRenderTargets.length > 0) {
  27829. engine.restoreDefaultFramebuffer();
  27830. }
  27831. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27832. this.activeCamera = currentActiveCamera;
  27833. // Procedural textures
  27834. if (this.proceduralTexturesEnabled) {
  27835. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27836. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27837. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27838. if (proceduralTexture._shouldRender()) {
  27839. proceduralTexture.render();
  27840. }
  27841. }
  27842. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27843. }
  27844. // Clear
  27845. if (this.autoClearDepthAndStencil || this.autoClear) {
  27846. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27847. }
  27848. // Shadows
  27849. if (this.shadowsEnabled) {
  27850. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27851. var light = this.lights[lightIndex];
  27852. var shadowGenerator = light.getShadowGenerator();
  27853. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27854. var shadowMap = (shadowGenerator.getShadowMap());
  27855. if (this.textures.indexOf(shadowMap) !== -1) {
  27856. this._renderTargets.push(shadowMap);
  27857. }
  27858. }
  27859. }
  27860. }
  27861. // Collects render targets from external components.
  27862. for (var _b = 0, _c = this._gatherRenderTargetsStage; _b < _c.length; _b++) {
  27863. var step = _c[_b];
  27864. step.action(this._renderTargets);
  27865. }
  27866. // Multi-cameras?
  27867. if (this.activeCameras.length > 0) {
  27868. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27869. if (cameraIndex > 0) {
  27870. this._engine.clear(null, false, true, true);
  27871. }
  27872. this._processSubCameras(this.activeCameras[cameraIndex]);
  27873. }
  27874. }
  27875. else {
  27876. if (!this.activeCamera) {
  27877. throw new Error("No camera defined");
  27878. }
  27879. this._processSubCameras(this.activeCamera);
  27880. }
  27881. // Intersection checks
  27882. this._checkIntersections();
  27883. // Update the audio listener attached to the camera
  27884. if (BABYLON.AudioEngine) {
  27885. this._updateAudioParameters();
  27886. }
  27887. // After render
  27888. if (this.afterRender) {
  27889. this.afterRender();
  27890. }
  27891. this.onAfterRenderObservable.notifyObservers(this);
  27892. // Cleaning
  27893. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27894. var data = this._toBeDisposed.data[index];
  27895. if (data) {
  27896. data.dispose();
  27897. }
  27898. this._toBeDisposed[index] = null;
  27899. }
  27900. this._toBeDisposed.reset();
  27901. if (this.dumpNextRenderTargets) {
  27902. this.dumpNextRenderTargets = false;
  27903. }
  27904. this._activeBones.addCount(0, true);
  27905. this._activeIndices.addCount(0, true);
  27906. this._activeParticles.addCount(0, true);
  27907. };
  27908. Scene.prototype._updateAudioParameters = function () {
  27909. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27910. return;
  27911. }
  27912. var listeningCamera;
  27913. var audioEngine = BABYLON.Engine.audioEngine;
  27914. if (this.activeCameras.length > 0) {
  27915. listeningCamera = this.activeCameras[0];
  27916. }
  27917. else {
  27918. listeningCamera = this.activeCamera;
  27919. }
  27920. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27921. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27922. // for VR cameras
  27923. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27924. listeningCamera = listeningCamera.rigCameras[0];
  27925. }
  27926. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27927. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27928. cameraDirection.normalize();
  27929. // To avoid some errors on GearVR
  27930. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27931. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27932. }
  27933. var i;
  27934. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27935. var sound = this.mainSoundTrack.soundCollection[i];
  27936. if (sound.useCustomAttenuation) {
  27937. sound.updateDistanceFromListener();
  27938. }
  27939. }
  27940. for (i = 0; i < this.soundTracks.length; i++) {
  27941. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27942. sound = this.soundTracks[i].soundCollection[j];
  27943. if (sound.useCustomAttenuation) {
  27944. sound.updateDistanceFromListener();
  27945. }
  27946. }
  27947. }
  27948. }
  27949. };
  27950. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27951. // Audio
  27952. /**
  27953. * Gets or sets if audio support is enabled
  27954. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27955. */
  27956. get: function () {
  27957. return this._audioEnabled;
  27958. },
  27959. set: function (value) {
  27960. this._audioEnabled = value;
  27961. if (BABYLON.AudioEngine) {
  27962. if (this._audioEnabled) {
  27963. this._enableAudio();
  27964. }
  27965. else {
  27966. this._disableAudio();
  27967. }
  27968. }
  27969. },
  27970. enumerable: true,
  27971. configurable: true
  27972. });
  27973. Scene.prototype._disableAudio = function () {
  27974. var i;
  27975. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27976. this.mainSoundTrack.soundCollection[i].pause();
  27977. }
  27978. for (i = 0; i < this.soundTracks.length; i++) {
  27979. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27980. this.soundTracks[i].soundCollection[j].pause();
  27981. }
  27982. }
  27983. };
  27984. Scene.prototype._enableAudio = function () {
  27985. var i;
  27986. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27987. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27988. this.mainSoundTrack.soundCollection[i].play();
  27989. }
  27990. }
  27991. for (i = 0; i < this.soundTracks.length; i++) {
  27992. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27993. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27994. this.soundTracks[i].soundCollection[j].play();
  27995. }
  27996. }
  27997. }
  27998. };
  27999. Object.defineProperty(Scene.prototype, "headphone", {
  28000. /**
  28001. * Gets or sets if audio will be output to headphones
  28002. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28003. */
  28004. get: function () {
  28005. return this._headphone;
  28006. },
  28007. set: function (value) {
  28008. this._headphone = value;
  28009. if (BABYLON.AudioEngine) {
  28010. if (this._headphone) {
  28011. this._switchAudioModeForHeadphones();
  28012. }
  28013. else {
  28014. this._switchAudioModeForNormalSpeakers();
  28015. }
  28016. }
  28017. },
  28018. enumerable: true,
  28019. configurable: true
  28020. });
  28021. Scene.prototype._switchAudioModeForHeadphones = function () {
  28022. this.mainSoundTrack.switchPanningModelToHRTF();
  28023. for (var i = 0; i < this.soundTracks.length; i++) {
  28024. this.soundTracks[i].switchPanningModelToHRTF();
  28025. }
  28026. };
  28027. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  28028. this.mainSoundTrack.switchPanningModelToEqualPower();
  28029. for (var i = 0; i < this.soundTracks.length; i++) {
  28030. this.soundTracks[i].switchPanningModelToEqualPower();
  28031. }
  28032. };
  28033. /**
  28034. * Freeze all materials
  28035. * A frozen material will not be updatable but should be faster to render
  28036. */
  28037. Scene.prototype.freezeMaterials = function () {
  28038. for (var i = 0; i < this.materials.length; i++) {
  28039. this.materials[i].freeze();
  28040. }
  28041. };
  28042. /**
  28043. * Unfreeze all materials
  28044. * A frozen material will not be updatable but should be faster to render
  28045. */
  28046. Scene.prototype.unfreezeMaterials = function () {
  28047. for (var i = 0; i < this.materials.length; i++) {
  28048. this.materials[i].unfreeze();
  28049. }
  28050. };
  28051. /**
  28052. * Releases all held ressources
  28053. */
  28054. Scene.prototype.dispose = function () {
  28055. this.beforeRender = null;
  28056. this.afterRender = null;
  28057. this.skeletons = [];
  28058. this.morphTargetManagers = [];
  28059. this._transientComponents = [];
  28060. this._isReadyForMeshStage.clear();
  28061. this._beforeEvaluateActiveMeshStage.clear();
  28062. this._evaluateSubMeshStage.clear();
  28063. this._activeMeshStage.clear();
  28064. this._cameraDrawRenderTargetStage.clear();
  28065. this._beforeCameraDrawStage.clear();
  28066. this._beforeRenderingGroupDrawStage.clear();
  28067. this._afterRenderingGroupDrawStage.clear();
  28068. this._afterCameraDrawStage.clear();
  28069. this._beforeCameraUpdateStage.clear();
  28070. this._gatherRenderTargetsStage.clear();
  28071. this._rebuildGeometryStage.clear();
  28072. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  28073. var component = _a[_i];
  28074. component.dispose();
  28075. }
  28076. this.importedMeshesFiles = new Array();
  28077. this.stopAllAnimations();
  28078. this.resetCachedMaterial();
  28079. // Smart arrays
  28080. if (this.activeCamera) {
  28081. this.activeCamera._activeMeshes.dispose();
  28082. this.activeCamera = null;
  28083. }
  28084. this._activeMeshes.dispose();
  28085. this._renderingManager.dispose();
  28086. this._processedMaterials.dispose();
  28087. this._activeParticleSystems.dispose();
  28088. this._activeSkeletons.dispose();
  28089. this._softwareSkinnedMeshes.dispose();
  28090. this._renderTargets.dispose();
  28091. this._registeredForLateAnimationBindings.dispose();
  28092. this._meshesForIntersections.dispose();
  28093. this._toBeDisposed.dispose();
  28094. // Abort active requests
  28095. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  28096. var request = _c[_b];
  28097. request.abort();
  28098. }
  28099. // Debug layer
  28100. if (this._debugLayer) {
  28101. this._debugLayer.hide();
  28102. }
  28103. // Events
  28104. this.onDisposeObservable.notifyObservers(this);
  28105. this.onDisposeObservable.clear();
  28106. this.onBeforeRenderObservable.clear();
  28107. this.onAfterRenderObservable.clear();
  28108. this.onBeforeRenderTargetsRenderObservable.clear();
  28109. this.onAfterRenderTargetsRenderObservable.clear();
  28110. this.onAfterStepObservable.clear();
  28111. this.onBeforeStepObservable.clear();
  28112. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28113. this.onAfterActiveMeshesEvaluationObservable.clear();
  28114. this.onBeforeParticlesRenderingObservable.clear();
  28115. this.onAfterParticlesRenderingObservable.clear();
  28116. this.onBeforeSpritesRenderingObservable.clear();
  28117. this.onAfterSpritesRenderingObservable.clear();
  28118. this.onBeforeDrawPhaseObservable.clear();
  28119. this.onAfterDrawPhaseObservable.clear();
  28120. this.onBeforePhysicsObservable.clear();
  28121. this.onAfterPhysicsObservable.clear();
  28122. this.onBeforeAnimationsObservable.clear();
  28123. this.onAfterAnimationsObservable.clear();
  28124. this.onDataLoadedObservable.clear();
  28125. this.onBeforeRenderingGroupObservable.clear();
  28126. this.onAfterRenderingGroupObservable.clear();
  28127. this.detachControl();
  28128. // Release sounds & sounds tracks
  28129. if (BABYLON.AudioEngine) {
  28130. this.disposeSounds();
  28131. }
  28132. // VR Helper
  28133. if (this.VRHelper) {
  28134. this.VRHelper.dispose();
  28135. }
  28136. // Detach cameras
  28137. var canvas = this._engine.getRenderingCanvas();
  28138. if (canvas) {
  28139. var index;
  28140. for (index = 0; index < this.cameras.length; index++) {
  28141. this.cameras[index].detachControl(canvas);
  28142. }
  28143. }
  28144. // Release animation groups
  28145. while (this.animationGroups.length) {
  28146. this.animationGroups[0].dispose();
  28147. }
  28148. // Release lights
  28149. while (this.lights.length) {
  28150. this.lights[0].dispose();
  28151. }
  28152. // Release meshes
  28153. while (this.meshes.length) {
  28154. this.meshes[0].dispose(true);
  28155. }
  28156. while (this.transformNodes.length) {
  28157. this.removeTransformNode(this.transformNodes[0]);
  28158. }
  28159. // Release cameras
  28160. while (this.cameras.length) {
  28161. this.cameras[0].dispose();
  28162. }
  28163. // Release materials
  28164. if (this.defaultMaterial) {
  28165. this.defaultMaterial.dispose();
  28166. }
  28167. while (this.multiMaterials.length) {
  28168. this.multiMaterials[0].dispose();
  28169. }
  28170. while (this.materials.length) {
  28171. this.materials[0].dispose();
  28172. }
  28173. // Release particles
  28174. while (this.particleSystems.length) {
  28175. this.particleSystems[0].dispose();
  28176. }
  28177. // Release sprites
  28178. while (this.spriteManagers.length) {
  28179. this.spriteManagers[0].dispose();
  28180. }
  28181. // Release postProcesses
  28182. while (this.postProcesses.length) {
  28183. this.postProcesses[0].dispose();
  28184. }
  28185. // Release textures
  28186. while (this.textures.length) {
  28187. this.textures[0].dispose();
  28188. }
  28189. // Release UBO
  28190. this._sceneUbo.dispose();
  28191. if (this._alternateSceneUbo) {
  28192. this._alternateSceneUbo.dispose();
  28193. }
  28194. // Post-processes
  28195. this.postProcessManager.dispose();
  28196. // Physics
  28197. if (this._physicsEngine) {
  28198. this.disablePhysicsEngine();
  28199. }
  28200. // Remove from engine
  28201. index = this._engine.scenes.indexOf(this);
  28202. if (index > -1) {
  28203. this._engine.scenes.splice(index, 1);
  28204. }
  28205. this._engine.wipeCaches(true);
  28206. this._isDisposed = true;
  28207. };
  28208. Object.defineProperty(Scene.prototype, "isDisposed", {
  28209. /**
  28210. * Gets if the scene is already disposed
  28211. */
  28212. get: function () {
  28213. return this._isDisposed;
  28214. },
  28215. enumerable: true,
  28216. configurable: true
  28217. });
  28218. /**
  28219. * Releases sounds & soundtracks
  28220. */
  28221. Scene.prototype.disposeSounds = function () {
  28222. if (!this._mainSoundTrack) {
  28223. return;
  28224. }
  28225. this.mainSoundTrack.dispose();
  28226. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28227. this.soundTracks[scIndex].dispose();
  28228. }
  28229. };
  28230. /**
  28231. * Call this function to reduce memory footprint of the scene.
  28232. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28233. */
  28234. Scene.prototype.clearCachedVertexData = function () {
  28235. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28236. var mesh = this.meshes[meshIndex];
  28237. var geometry = mesh.geometry;
  28238. if (geometry) {
  28239. geometry._indices = [];
  28240. for (var vbName in geometry._vertexBuffers) {
  28241. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28242. continue;
  28243. }
  28244. geometry._vertexBuffers[vbName]._buffer._data = null;
  28245. }
  28246. }
  28247. }
  28248. };
  28249. /**
  28250. * This function will remove the local cached buffer data from texture.
  28251. * It will save memory but will prevent the texture from being rebuilt
  28252. */
  28253. Scene.prototype.cleanCachedTextureBuffer = function () {
  28254. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28255. var baseTexture = _a[_i];
  28256. var buffer = baseTexture._buffer;
  28257. if (buffer) {
  28258. baseTexture._buffer = null;
  28259. }
  28260. }
  28261. };
  28262. // Octrees
  28263. /**
  28264. * Get the world extend vectors with an optional filter
  28265. *
  28266. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28267. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28268. */
  28269. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28270. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28271. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28272. filterPredicate = filterPredicate || (function () { return true; });
  28273. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28274. mesh.computeWorldMatrix(true);
  28275. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28276. return;
  28277. }
  28278. var boundingInfo = mesh.getBoundingInfo();
  28279. var minBox = boundingInfo.boundingBox.minimumWorld;
  28280. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28281. BABYLON.Tools.CheckExtends(minBox, min, max);
  28282. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28283. });
  28284. return {
  28285. min: min,
  28286. max: max
  28287. };
  28288. };
  28289. /**
  28290. * Creates or updates the octree used to boost selection (picking)
  28291. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28292. * @param maxCapacity defines the maximum capacity per leaf
  28293. * @param maxDepth defines the maximum depth of the octree
  28294. * @returns an octree of AbstractMesh
  28295. */
  28296. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28297. if (maxCapacity === void 0) { maxCapacity = 64; }
  28298. if (maxDepth === void 0) { maxDepth = 2; }
  28299. if (!this._selectionOctree) {
  28300. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28301. }
  28302. var worldExtends = this.getWorldExtends();
  28303. // Update octree
  28304. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28305. return this._selectionOctree;
  28306. };
  28307. // Picking
  28308. /**
  28309. * Creates a ray that can be used to pick in the scene
  28310. * @param x defines the x coordinate of the origin (on-screen)
  28311. * @param y defines the y coordinate of the origin (on-screen)
  28312. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28313. * @param camera defines the camera to use for the picking
  28314. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28315. * @returns a Ray
  28316. */
  28317. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28318. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28319. var result = BABYLON.Ray.Zero();
  28320. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28321. return result;
  28322. };
  28323. /**
  28324. * Creates a ray that can be used to pick in the scene
  28325. * @param x defines the x coordinate of the origin (on-screen)
  28326. * @param y defines the y coordinate of the origin (on-screen)
  28327. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28328. * @param result defines the ray where to store the picking ray
  28329. * @param camera defines the camera to use for the picking
  28330. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28331. * @returns the current scene
  28332. */
  28333. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28334. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28335. var engine = this._engine;
  28336. if (!camera) {
  28337. if (!this.activeCamera)
  28338. throw new Error("Active camera not set");
  28339. camera = this.activeCamera;
  28340. }
  28341. var cameraViewport = camera.viewport;
  28342. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28343. // Moving coordinates to local viewport world
  28344. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28345. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28346. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28347. return this;
  28348. };
  28349. /**
  28350. * Creates a ray that can be used to pick in the scene
  28351. * @param x defines the x coordinate of the origin (on-screen)
  28352. * @param y defines the y coordinate of the origin (on-screen)
  28353. * @param camera defines the camera to use for the picking
  28354. * @returns a Ray
  28355. */
  28356. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28357. var result = BABYLON.Ray.Zero();
  28358. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28359. return result;
  28360. };
  28361. /**
  28362. * Creates a ray that can be used to pick in the scene
  28363. * @param x defines the x coordinate of the origin (on-screen)
  28364. * @param y defines the y coordinate of the origin (on-screen)
  28365. * @param result defines the ray where to store the picking ray
  28366. * @param camera defines the camera to use for the picking
  28367. * @returns the current scene
  28368. */
  28369. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28370. if (!BABYLON.PickingInfo) {
  28371. return this;
  28372. }
  28373. var engine = this._engine;
  28374. if (!camera) {
  28375. if (!this.activeCamera)
  28376. throw new Error("Active camera not set");
  28377. camera = this.activeCamera;
  28378. }
  28379. var cameraViewport = camera.viewport;
  28380. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28381. var identity = BABYLON.Matrix.Identity();
  28382. // Moving coordinates to local viewport world
  28383. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28384. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28385. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28386. return this;
  28387. };
  28388. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28389. if (!BABYLON.PickingInfo) {
  28390. return null;
  28391. }
  28392. var pickingInfo = null;
  28393. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28394. var mesh = this.meshes[meshIndex];
  28395. if (predicate) {
  28396. if (!predicate(mesh)) {
  28397. continue;
  28398. }
  28399. }
  28400. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28401. continue;
  28402. }
  28403. var world = mesh.getWorldMatrix();
  28404. var ray = rayFunction(world);
  28405. var result = mesh.intersects(ray, fastCheck);
  28406. if (!result || !result.hit)
  28407. continue;
  28408. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28409. continue;
  28410. pickingInfo = result;
  28411. if (fastCheck) {
  28412. break;
  28413. }
  28414. }
  28415. return pickingInfo || new BABYLON.PickingInfo();
  28416. };
  28417. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28418. if (!BABYLON.PickingInfo) {
  28419. return null;
  28420. }
  28421. var pickingInfos = new Array();
  28422. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28423. var mesh = this.meshes[meshIndex];
  28424. if (predicate) {
  28425. if (!predicate(mesh)) {
  28426. continue;
  28427. }
  28428. }
  28429. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28430. continue;
  28431. }
  28432. var world = mesh.getWorldMatrix();
  28433. var ray = rayFunction(world);
  28434. var result = mesh.intersects(ray, false);
  28435. if (!result || !result.hit)
  28436. continue;
  28437. pickingInfos.push(result);
  28438. }
  28439. return pickingInfos;
  28440. };
  28441. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28442. if (!BABYLON.PickingInfo) {
  28443. return null;
  28444. }
  28445. var pickingInfo = null;
  28446. if (!camera) {
  28447. if (!this.activeCamera) {
  28448. return null;
  28449. }
  28450. camera = this.activeCamera;
  28451. }
  28452. if (this.spriteManagers.length > 0) {
  28453. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28454. var spriteManager = this.spriteManagers[spriteIndex];
  28455. if (!spriteManager.isPickable) {
  28456. continue;
  28457. }
  28458. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28459. if (!result || !result.hit)
  28460. continue;
  28461. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28462. continue;
  28463. pickingInfo = result;
  28464. if (fastCheck) {
  28465. break;
  28466. }
  28467. }
  28468. }
  28469. return pickingInfo || new BABYLON.PickingInfo();
  28470. };
  28471. /** Launch a ray to try to pick a mesh in the scene
  28472. * @param x position on screen
  28473. * @param y position on screen
  28474. * @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
  28475. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28476. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28477. * @returns a PickingInfo
  28478. */
  28479. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28480. var _this = this;
  28481. if (!BABYLON.PickingInfo) {
  28482. return null;
  28483. }
  28484. var result = this._internalPick(function (world) {
  28485. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28486. return _this._tempPickingRay;
  28487. }, predicate, fastCheck);
  28488. if (result) {
  28489. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28490. }
  28491. return result;
  28492. };
  28493. /** Launch a ray to try to pick a sprite in the scene
  28494. * @param x position on screen
  28495. * @param y position on screen
  28496. * @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
  28497. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28498. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28499. * @returns a PickingInfo
  28500. */
  28501. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28502. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28503. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28504. };
  28505. /** Use the given ray to pick a sprite in the scene
  28506. * @param ray The ray (in world space) to use to pick meshes
  28507. * @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
  28508. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28509. * @param camera camera to use. Can be set to null. In this case, the scene.activeCamera will be used
  28510. * @returns a PickingInfo
  28511. */
  28512. Scene.prototype.pickSpriteWithRay = function (ray, predicate, fastCheck, camera) {
  28513. if (!this._cachedRayForTransform) {
  28514. this._cachedRayForTransform = BABYLON.Ray.Zero();
  28515. }
  28516. if (!camera) {
  28517. if (!this.activeCamera) {
  28518. return null;
  28519. }
  28520. camera = this.activeCamera;
  28521. }
  28522. BABYLON.Ray.TransformToRef(ray, camera.getViewMatrix(), this._cachedRayForTransform);
  28523. return this._internalPickSprites(this._cachedRayForTransform, predicate, fastCheck, camera);
  28524. };
  28525. /** Use the given ray to pick a mesh in the scene
  28526. * @param ray The ray to use to pick meshes
  28527. * @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
  28528. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28529. * @returns a PickingInfo
  28530. */
  28531. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28532. var _this = this;
  28533. var result = this._internalPick(function (world) {
  28534. if (!_this._pickWithRayInverseMatrix) {
  28535. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28536. }
  28537. world.invertToRef(_this._pickWithRayInverseMatrix);
  28538. if (!_this._cachedRayForTransform) {
  28539. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28540. }
  28541. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28542. return _this._cachedRayForTransform;
  28543. }, predicate, fastCheck);
  28544. if (result) {
  28545. result.ray = ray;
  28546. }
  28547. return result;
  28548. };
  28549. /**
  28550. * Launch a ray to try to pick a mesh in the scene
  28551. * @param x X position on screen
  28552. * @param y Y position on screen
  28553. * @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
  28554. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28555. * @returns an array of PickingInfo
  28556. */
  28557. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28558. var _this = this;
  28559. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28560. };
  28561. /**
  28562. * Launch a ray to try to pick a mesh in the scene
  28563. * @param ray Ray to use
  28564. * @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
  28565. * @returns an array of PickingInfo
  28566. */
  28567. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28568. var _this = this;
  28569. return this._internalMultiPick(function (world) {
  28570. if (!_this._pickWithRayInverseMatrix) {
  28571. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28572. }
  28573. world.invertToRef(_this._pickWithRayInverseMatrix);
  28574. if (!_this._cachedRayForTransform) {
  28575. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28576. }
  28577. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28578. return _this._cachedRayForTransform;
  28579. }, predicate);
  28580. };
  28581. /**
  28582. * Force the value of meshUnderPointer
  28583. * @param mesh defines the mesh to use
  28584. */
  28585. Scene.prototype.setPointerOverMesh = function (mesh) {
  28586. if (this._pointerOverMesh === mesh) {
  28587. return;
  28588. }
  28589. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28590. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28591. }
  28592. this._pointerOverMesh = mesh;
  28593. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28594. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28595. }
  28596. };
  28597. /**
  28598. * Gets the mesh under the pointer
  28599. * @returns a Mesh or null if no mesh is under the pointer
  28600. */
  28601. Scene.prototype.getPointerOverMesh = function () {
  28602. return this._pointerOverMesh;
  28603. };
  28604. /**
  28605. * Force the sprite under the pointer
  28606. * @param sprite defines the sprite to use
  28607. */
  28608. Scene.prototype.setPointerOverSprite = function (sprite) {
  28609. if (this._pointerOverSprite === sprite) {
  28610. return;
  28611. }
  28612. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28613. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28614. }
  28615. this._pointerOverSprite = sprite;
  28616. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28617. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28618. }
  28619. };
  28620. /**
  28621. * Gets the sprite under the pointer
  28622. * @returns a Sprite or null if no sprite is under the pointer
  28623. */
  28624. Scene.prototype.getPointerOverSprite = function () {
  28625. return this._pointerOverSprite;
  28626. };
  28627. // Physics
  28628. /**
  28629. * Gets the current physics engine
  28630. * @returns a PhysicsEngine or null if none attached
  28631. */
  28632. Scene.prototype.getPhysicsEngine = function () {
  28633. return this._physicsEngine;
  28634. };
  28635. /**
  28636. * Enables physics to the current scene
  28637. * @param gravity defines the scene's gravity for the physics engine
  28638. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28639. * @return a boolean indicating if the physics engine was initialized
  28640. */
  28641. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28642. if (gravity === void 0) { gravity = null; }
  28643. if (this._physicsEngine) {
  28644. return true;
  28645. }
  28646. try {
  28647. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28648. return true;
  28649. }
  28650. catch (e) {
  28651. BABYLON.Tools.Error(e.message);
  28652. return false;
  28653. }
  28654. };
  28655. /**
  28656. * Disables and disposes the physics engine associated with the scene
  28657. */
  28658. Scene.prototype.disablePhysicsEngine = function () {
  28659. if (!this._physicsEngine) {
  28660. return;
  28661. }
  28662. this._physicsEngine.dispose();
  28663. this._physicsEngine = null;
  28664. };
  28665. /**
  28666. * Gets a boolean indicating if there is an active physics engine
  28667. * @returns a boolean indicating if there is an active physics engine
  28668. */
  28669. Scene.prototype.isPhysicsEnabled = function () {
  28670. return this._physicsEngine !== undefined;
  28671. };
  28672. /**
  28673. * Deletes a physics compound impostor
  28674. * @param compound defines the compound to delete
  28675. */
  28676. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28677. var mesh = compound.parts[0].mesh;
  28678. if (mesh.physicsImpostor) {
  28679. mesh.physicsImpostor.dispose( /*true*/);
  28680. mesh.physicsImpostor = null;
  28681. }
  28682. };
  28683. // Misc.
  28684. /** @hidden */
  28685. Scene.prototype._rebuildGeometries = function () {
  28686. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  28687. var geometry = _a[_i];
  28688. geometry._rebuild();
  28689. }
  28690. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28691. var mesh = _c[_b];
  28692. mesh._rebuild();
  28693. }
  28694. if (this.postProcessManager) {
  28695. this.postProcessManager._rebuild();
  28696. }
  28697. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  28698. var component = _e[_d];
  28699. component.rebuild();
  28700. }
  28701. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  28702. var system = _g[_f];
  28703. system.rebuild();
  28704. }
  28705. for (var _h = 0, _j = this._rebuildGeometryStage; _h < _j.length; _h++) {
  28706. var step = _j[_h];
  28707. step.action();
  28708. }
  28709. };
  28710. /** @hidden */
  28711. Scene.prototype._rebuildTextures = function () {
  28712. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28713. var texture = _a[_i];
  28714. texture._rebuild();
  28715. }
  28716. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28717. };
  28718. /**
  28719. * Creates a default light for the scene.
  28720. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-light
  28721. * @param replace has the default false, when true replaces the existing lights in the scene with a hemispheric light
  28722. */
  28723. Scene.prototype.createDefaultLight = function (replace) {
  28724. if (replace === void 0) { replace = false; }
  28725. // Dispose existing light in replace mode.
  28726. if (replace) {
  28727. if (this.lights) {
  28728. for (var i = 0; i < this.lights.length; i++) {
  28729. this.lights[i].dispose();
  28730. }
  28731. }
  28732. }
  28733. // Light
  28734. if (this.lights.length === 0) {
  28735. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28736. }
  28737. };
  28738. /**
  28739. * Creates a default camera for the scene.
  28740. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-camera
  28741. * @param createArcRotateCamera has the default false which creates a free camera, when true creates an arc rotate camera
  28742. * @param replace has default false, when true replaces the active camera in the scene
  28743. * @param attachCameraControls has default false, when true attaches camera controls to the canvas.
  28744. */
  28745. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28746. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28747. if (replace === void 0) { replace = false; }
  28748. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28749. // Dispose existing camera in replace mode.
  28750. if (replace) {
  28751. if (this.activeCamera) {
  28752. this.activeCamera.dispose();
  28753. this.activeCamera = null;
  28754. }
  28755. }
  28756. // Camera
  28757. if (!this.activeCamera) {
  28758. var worldExtends = this.getWorldExtends();
  28759. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28760. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28761. var camera;
  28762. var radius = worldSize.length() * 1.5;
  28763. // empty scene scenario!
  28764. if (!isFinite(radius)) {
  28765. radius = 1;
  28766. worldCenter.copyFromFloats(0, 0, 0);
  28767. }
  28768. if (createArcRotateCamera) {
  28769. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28770. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28771. arcRotateCamera.wheelPrecision = 100 / radius;
  28772. camera = arcRotateCamera;
  28773. }
  28774. else {
  28775. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28776. freeCamera.setTarget(worldCenter);
  28777. camera = freeCamera;
  28778. }
  28779. camera.minZ = radius * 0.01;
  28780. camera.maxZ = radius * 1000;
  28781. camera.speed = radius * 0.2;
  28782. this.activeCamera = camera;
  28783. var canvas = this.getEngine().getRenderingCanvas();
  28784. if (attachCameraControls && canvas) {
  28785. camera.attachControl(canvas);
  28786. }
  28787. }
  28788. };
  28789. /**
  28790. * Creates a default camera and a default light.
  28791. * @see http://doc.babylonjs.com/how_to/Fast_Build#create-default-camera-or-light
  28792. * @param createArcRotateCamera has the default false which creates a free camera, when true creates an arc rotate camera
  28793. * @param replace has the default false, when true replaces the active camera/light in the scene
  28794. * @param attachCameraControls has the default false, when true attaches camera controls to the canvas.
  28795. */
  28796. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28797. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28798. if (replace === void 0) { replace = false; }
  28799. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28800. this.createDefaultLight(replace);
  28801. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28802. };
  28803. /**
  28804. * Creates a new sky box
  28805. * @see http://doc.babylonjs.com/how_to/Fast_Build#create-default-skybox
  28806. * @param environmentTexture defines the texture to use as environment texture
  28807. * @param pbr has default false which requires the StandardMaterial to be used, when true PBRMaterial must be used
  28808. * @param scale defines the overall scale of the skybox
  28809. * @param blur is only available when pbr is true, default is 0, no blur, maximum value is 1
  28810. * @param setGlobalEnvTexture has default true indicating that scene.environmentTexture must match the current skybox texture
  28811. * @returns a new mesh holding the sky box
  28812. */
  28813. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28814. if (pbr === void 0) { pbr = false; }
  28815. if (scale === void 0) { scale = 1000; }
  28816. if (blur === void 0) { blur = 0; }
  28817. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28818. if (!environmentTexture) {
  28819. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28820. return null;
  28821. }
  28822. if (setGlobalEnvTexture) {
  28823. if (environmentTexture) {
  28824. this.environmentTexture = environmentTexture;
  28825. }
  28826. }
  28827. // Skybox
  28828. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28829. if (pbr) {
  28830. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28831. hdrSkyboxMaterial.backFaceCulling = false;
  28832. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28833. if (hdrSkyboxMaterial.reflectionTexture) {
  28834. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28835. }
  28836. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28837. hdrSkyboxMaterial.disableLighting = true;
  28838. hdrSkyboxMaterial.twoSidedLighting = true;
  28839. hdrSkybox.infiniteDistance = true;
  28840. hdrSkybox.material = hdrSkyboxMaterial;
  28841. }
  28842. else {
  28843. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28844. skyboxMaterial.backFaceCulling = false;
  28845. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28846. if (skyboxMaterial.reflectionTexture) {
  28847. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28848. }
  28849. skyboxMaterial.disableLighting = true;
  28850. hdrSkybox.infiniteDistance = true;
  28851. hdrSkybox.material = skyboxMaterial;
  28852. }
  28853. return hdrSkybox;
  28854. };
  28855. /**
  28856. * Creates a new environment
  28857. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-environment
  28858. * @param options defines the options you can use to configure the environment
  28859. * @returns the new EnvironmentHelper
  28860. */
  28861. Scene.prototype.createDefaultEnvironment = function (options) {
  28862. if (BABYLON.EnvironmentHelper) {
  28863. return new BABYLON.EnvironmentHelper(options, this);
  28864. }
  28865. return null;
  28866. };
  28867. /**
  28868. * Creates a new VREXperienceHelper
  28869. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28870. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28871. * @returns a new VREXperienceHelper
  28872. */
  28873. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28874. if (webVROptions === void 0) { webVROptions = {}; }
  28875. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28876. };
  28877. // Tags
  28878. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28879. if (tagsQuery === undefined) {
  28880. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28881. return list;
  28882. }
  28883. var listByTags = [];
  28884. forEach = forEach || (function (item) { return; });
  28885. for (var i in list) {
  28886. var item = list[i];
  28887. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28888. listByTags.push(item);
  28889. forEach(item);
  28890. }
  28891. }
  28892. return listByTags;
  28893. };
  28894. /**
  28895. * Get a list of meshes by tags
  28896. * @param tagsQuery defines the tags query to use
  28897. * @param forEach defines a predicate used to filter results
  28898. * @returns an array of Mesh
  28899. */
  28900. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28901. return this._getByTags(this.meshes, tagsQuery, forEach);
  28902. };
  28903. /**
  28904. * Get a list of cameras by tags
  28905. * @param tagsQuery defines the tags query to use
  28906. * @param forEach defines a predicate used to filter results
  28907. * @returns an array of Camera
  28908. */
  28909. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28910. return this._getByTags(this.cameras, tagsQuery, forEach);
  28911. };
  28912. /**
  28913. * Get a list of lights by tags
  28914. * @param tagsQuery defines the tags query to use
  28915. * @param forEach defines a predicate used to filter results
  28916. * @returns an array of Light
  28917. */
  28918. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28919. return this._getByTags(this.lights, tagsQuery, forEach);
  28920. };
  28921. /**
  28922. * Get a list of materials by tags
  28923. * @param tagsQuery defines the tags query to use
  28924. * @param forEach defines a predicate used to filter results
  28925. * @returns an array of Material
  28926. */
  28927. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28928. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28929. };
  28930. /**
  28931. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28932. * This allowed control for front to back rendering or reversly depending of the special needs.
  28933. *
  28934. * @param renderingGroupId The rendering group id corresponding to its index
  28935. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28936. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28937. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28938. */
  28939. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28940. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28941. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28942. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28943. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28944. };
  28945. /**
  28946. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28947. *
  28948. * @param renderingGroupId The rendering group id corresponding to its index
  28949. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28950. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28951. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28952. */
  28953. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28954. if (depth === void 0) { depth = true; }
  28955. if (stencil === void 0) { stencil = true; }
  28956. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28957. };
  28958. /**
  28959. * Gets the current auto clear configuration for one rendering group of the rendering
  28960. * manager.
  28961. * @param index the rendering group index to get the information for
  28962. * @returns The auto clear setup for the requested rendering group
  28963. */
  28964. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  28965. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  28966. };
  28967. /**
  28968. * Will flag all materials as dirty to trigger new shader compilation
  28969. * @param flag defines the flag used to specify which material part must be marked as dirty
  28970. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28971. */
  28972. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28973. if (this.blockMaterialDirtyMechanism) {
  28974. return;
  28975. }
  28976. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28977. var material = _a[_i];
  28978. if (predicate && !predicate(material)) {
  28979. continue;
  28980. }
  28981. material.markAsDirty(flag);
  28982. }
  28983. };
  28984. /** @hidden */
  28985. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28986. var _this = this;
  28987. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28988. this._activeRequests.push(request);
  28989. request.onCompleteObservable.add(function (request) {
  28990. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28991. });
  28992. return request;
  28993. };
  28994. /** @hidden */
  28995. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28996. var _this = this;
  28997. return new Promise(function (resolve, reject) {
  28998. _this._loadFile(url, function (data) {
  28999. resolve(data);
  29000. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  29001. reject(exception);
  29002. });
  29003. });
  29004. };
  29005. // Statics
  29006. Scene._uniqueIdCounter = 0;
  29007. /** The fog is deactivated */
  29008. Scene.FOGMODE_NONE = 0;
  29009. /** The fog density is following an exponential function */
  29010. Scene.FOGMODE_EXP = 1;
  29011. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  29012. Scene.FOGMODE_EXP2 = 2;
  29013. /** The fog density is following a linear function. */
  29014. Scene.FOGMODE_LINEAR = 3;
  29015. /**
  29016. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29017. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29018. */
  29019. Scene.MinDeltaTime = 1.0;
  29020. /**
  29021. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29022. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29023. */
  29024. Scene.MaxDeltaTime = 1000.0;
  29025. /** The distance in pixel that you have to move to prevent some events */
  29026. Scene.DragMovementThreshold = 10; // in pixels
  29027. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29028. Scene.LongPressDelay = 500; // in milliseconds
  29029. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29030. Scene.DoubleClickDelay = 300; // in milliseconds
  29031. /** If you need to check double click without raising a single click at first click, enable this flag */
  29032. Scene.ExclusiveDoubleClickMode = false;
  29033. return Scene;
  29034. }(BABYLON.AbstractScene));
  29035. BABYLON.Scene = Scene;
  29036. })(BABYLON || (BABYLON = {}));
  29037. //# sourceMappingURL=babylon.scene.js.map
  29038. var BABYLON;
  29039. (function (BABYLON) {
  29040. /**
  29041. * Set of assets to keep when moving a scene into an asset container.
  29042. */
  29043. var KeepAssets = /** @class */ (function (_super) {
  29044. __extends(KeepAssets, _super);
  29045. function KeepAssets() {
  29046. return _super !== null && _super.apply(this, arguments) || this;
  29047. }
  29048. return KeepAssets;
  29049. }(BABYLON.AbstractScene));
  29050. BABYLON.KeepAssets = KeepAssets;
  29051. /**
  29052. * Container with a set of assets that can be added or removed from a scene.
  29053. */
  29054. var AssetContainer = /** @class */ (function (_super) {
  29055. __extends(AssetContainer, _super);
  29056. /**
  29057. * Instantiates an AssetContainer.
  29058. * @param scene The scene the AssetContainer belongs to.
  29059. */
  29060. function AssetContainer(scene) {
  29061. var _this = _super.call(this) || this;
  29062. _this.scene = scene;
  29063. return _this;
  29064. }
  29065. /**
  29066. * Adds all the assets from the container to the scene.
  29067. */
  29068. AssetContainer.prototype.addAllToScene = function () {
  29069. var _this = this;
  29070. this.cameras.forEach(function (o) {
  29071. _this.scene.addCamera(o);
  29072. });
  29073. this.lights.forEach(function (o) {
  29074. _this.scene.addLight(o);
  29075. });
  29076. this.meshes.forEach(function (o) {
  29077. _this.scene.addMesh(o);
  29078. });
  29079. this.skeletons.forEach(function (o) {
  29080. _this.scene.addSkeleton(o);
  29081. });
  29082. this.animations.forEach(function (o) {
  29083. _this.scene.addAnimation(o);
  29084. });
  29085. this.animationGroups.forEach(function (o) {
  29086. _this.scene.addAnimationGroup(o);
  29087. });
  29088. this.multiMaterials.forEach(function (o) {
  29089. _this.scene.addMultiMaterial(o);
  29090. });
  29091. this.materials.forEach(function (o) {
  29092. _this.scene.addMaterial(o);
  29093. });
  29094. this.morphTargetManagers.forEach(function (o) {
  29095. _this.scene.addMorphTargetManager(o);
  29096. });
  29097. this.geometries.forEach(function (o) {
  29098. _this.scene.addGeometry(o);
  29099. });
  29100. this.transformNodes.forEach(function (o) {
  29101. _this.scene.addTransformNode(o);
  29102. });
  29103. this.actionManagers.forEach(function (o) {
  29104. _this.scene.addActionManager(o);
  29105. });
  29106. this.sounds.forEach(function (o) {
  29107. o.play();
  29108. o.autoplay = true;
  29109. _this.scene.mainSoundTrack.AddSound(o);
  29110. });
  29111. this.textures.forEach(function (o) {
  29112. _this.scene.addTexture(o);
  29113. });
  29114. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29115. var component = _a[_i];
  29116. component.addFromContainer(this.scene);
  29117. }
  29118. };
  29119. /**
  29120. * Removes all the assets in the container from the scene
  29121. */
  29122. AssetContainer.prototype.removeAllFromScene = function () {
  29123. var _this = this;
  29124. this.cameras.forEach(function (o) {
  29125. _this.scene.removeCamera(o);
  29126. });
  29127. this.lights.forEach(function (o) {
  29128. _this.scene.removeLight(o);
  29129. });
  29130. this.meshes.forEach(function (o) {
  29131. _this.scene.removeMesh(o);
  29132. });
  29133. this.skeletons.forEach(function (o) {
  29134. _this.scene.removeSkeleton(o);
  29135. });
  29136. this.animations.forEach(function (o) {
  29137. _this.scene.removeAnimation(o);
  29138. });
  29139. this.animationGroups.forEach(function (o) {
  29140. _this.scene.removeAnimationGroup(o);
  29141. });
  29142. this.multiMaterials.forEach(function (o) {
  29143. _this.scene.removeMultiMaterial(o);
  29144. });
  29145. this.materials.forEach(function (o) {
  29146. _this.scene.removeMaterial(o);
  29147. });
  29148. this.morphTargetManagers.forEach(function (o) {
  29149. _this.scene.removeMorphTargetManager(o);
  29150. });
  29151. this.geometries.forEach(function (o) {
  29152. _this.scene.removeGeometry(o);
  29153. });
  29154. this.transformNodes.forEach(function (o) {
  29155. _this.scene.removeTransformNode(o);
  29156. });
  29157. this.actionManagers.forEach(function (o) {
  29158. _this.scene.removeActionManager(o);
  29159. });
  29160. this.sounds.forEach(function (o) {
  29161. o.stop();
  29162. o.autoplay = false;
  29163. _this.scene.mainSoundTrack.RemoveSound(o);
  29164. });
  29165. this.textures.forEach(function (o) {
  29166. _this.scene.removeTexture(o);
  29167. });
  29168. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29169. var component = _a[_i];
  29170. component.removeFromContainer(this.scene);
  29171. }
  29172. };
  29173. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29174. if (!sourceAssets) {
  29175. return;
  29176. }
  29177. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29178. var asset = sourceAssets_1[_i];
  29179. var move = true;
  29180. if (keepAssets) {
  29181. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29182. var keepAsset = keepAssets_1[_a];
  29183. if (asset === keepAsset) {
  29184. move = false;
  29185. break;
  29186. }
  29187. }
  29188. }
  29189. if (move) {
  29190. targetAssets.push(asset);
  29191. }
  29192. }
  29193. };
  29194. /**
  29195. * Removes all the assets contained in the scene and adds them to the container.
  29196. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29197. */
  29198. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29199. if (keepAssets === undefined) {
  29200. keepAssets = new KeepAssets();
  29201. }
  29202. for (var key in this) {
  29203. if (this.hasOwnProperty(key)) {
  29204. this[key] = this[key] || [];
  29205. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  29206. }
  29207. }
  29208. this.removeAllFromScene();
  29209. };
  29210. /**
  29211. * 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.
  29212. * @returns the root mesh
  29213. */
  29214. AssetContainer.prototype.createRootMesh = function () {
  29215. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29216. this.meshes.forEach(function (m) {
  29217. if (!m.parent) {
  29218. rootMesh.addChild(m);
  29219. }
  29220. });
  29221. this.meshes.unshift(rootMesh);
  29222. return rootMesh;
  29223. };
  29224. return AssetContainer;
  29225. }(BABYLON.AbstractScene));
  29226. BABYLON.AssetContainer = AssetContainer;
  29227. })(BABYLON || (BABYLON = {}));
  29228. //# sourceMappingURL=babylon.assetContainer.js.map
  29229. var BABYLON;
  29230. (function (BABYLON) {
  29231. var Buffer = /** @class */ (function () {
  29232. /**
  29233. * Constructor
  29234. * @param engine the engine
  29235. * @param data the data to use for this buffer
  29236. * @param updatable whether the data is updatable
  29237. * @param stride the stride (optional)
  29238. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29239. * @param instanced whether the buffer is instanced (optional)
  29240. * @param useBytes set to true if the stride in in bytes (optional)
  29241. */
  29242. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29243. if (stride === void 0) { stride = 0; }
  29244. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29245. if (instanced === void 0) { instanced = false; }
  29246. if (useBytes === void 0) { useBytes = false; }
  29247. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29248. this._engine = engine.getScene().getEngine();
  29249. }
  29250. else {
  29251. this._engine = engine;
  29252. }
  29253. this._updatable = updatable;
  29254. this._instanced = instanced;
  29255. this._data = data;
  29256. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29257. if (!postponeInternalCreation) { // by default
  29258. this.create();
  29259. }
  29260. }
  29261. /**
  29262. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29263. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29264. * @param offset defines offset in the buffer (0 by default)
  29265. * @param size defines the size in floats of attributes (position is 3 for instance)
  29266. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29267. * @param instanced defines if the vertex buffer contains indexed data
  29268. * @param useBytes defines if the offset and stride are in bytes
  29269. * @returns the new vertex buffer
  29270. */
  29271. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29272. if (useBytes === void 0) { useBytes = false; }
  29273. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29274. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29275. // a lot of these parameters are ignored as they are overriden by the buffer
  29276. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29277. };
  29278. // Properties
  29279. Buffer.prototype.isUpdatable = function () {
  29280. return this._updatable;
  29281. };
  29282. Buffer.prototype.getData = function () {
  29283. return this._data;
  29284. };
  29285. Buffer.prototype.getBuffer = function () {
  29286. return this._buffer;
  29287. };
  29288. /**
  29289. * Gets the stride in float32 units (i.e. byte stride / 4).
  29290. * May not be an integer if the byte stride is not divisible by 4.
  29291. * DEPRECATED. Use byteStride instead.
  29292. * @returns the stride in float32 units
  29293. */
  29294. Buffer.prototype.getStrideSize = function () {
  29295. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29296. };
  29297. // Methods
  29298. Buffer.prototype.create = function (data) {
  29299. if (data === void 0) { data = null; }
  29300. if (!data && this._buffer) {
  29301. return; // nothing to do
  29302. }
  29303. data = data || this._data;
  29304. if (!data) {
  29305. return;
  29306. }
  29307. if (!this._buffer) { // create buffer
  29308. if (this._updatable) {
  29309. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29310. this._data = data;
  29311. }
  29312. else {
  29313. this._buffer = this._engine.createVertexBuffer(data);
  29314. }
  29315. }
  29316. else if (this._updatable) { // update buffer
  29317. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29318. this._data = data;
  29319. }
  29320. };
  29321. /** @hidden */
  29322. Buffer.prototype._rebuild = function () {
  29323. this._buffer = null;
  29324. this.create(this._data);
  29325. };
  29326. Buffer.prototype.update = function (data) {
  29327. this.create(data);
  29328. };
  29329. /**
  29330. * Updates the data directly.
  29331. * @param data the new data
  29332. * @param offset the new offset
  29333. * @param vertexCount the vertex count (optional)
  29334. * @param useBytes set to true if the offset is in bytes
  29335. */
  29336. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29337. if (useBytes === void 0) { useBytes = false; }
  29338. if (!this._buffer) {
  29339. return;
  29340. }
  29341. if (this._updatable) { // update buffer
  29342. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29343. this._data = null;
  29344. }
  29345. };
  29346. Buffer.prototype.dispose = function () {
  29347. if (!this._buffer) {
  29348. return;
  29349. }
  29350. if (this._engine._releaseBuffer(this._buffer)) {
  29351. this._buffer = null;
  29352. }
  29353. };
  29354. return Buffer;
  29355. }());
  29356. BABYLON.Buffer = Buffer;
  29357. })(BABYLON || (BABYLON = {}));
  29358. //# sourceMappingURL=babylon.buffer.js.map
  29359. var BABYLON;
  29360. (function (BABYLON) {
  29361. var VertexBuffer = /** @class */ (function () {
  29362. /**
  29363. * Constructor
  29364. * @param engine the engine
  29365. * @param data the data to use for this vertex buffer
  29366. * @param kind the vertex buffer kind
  29367. * @param updatable whether the data is updatable
  29368. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29369. * @param stride the stride (optional)
  29370. * @param instanced whether the buffer is instanced (optional)
  29371. * @param offset the offset of the data (optional)
  29372. * @param size the number of components (optional)
  29373. * @param type the type of the component (optional)
  29374. * @param normalized whether the data contains normalized data (optional)
  29375. * @param useBytes set to true if stride and offset are in bytes (optional)
  29376. */
  29377. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29378. if (normalized === void 0) { normalized = false; }
  29379. if (useBytes === void 0) { useBytes = false; }
  29380. if (data instanceof BABYLON.Buffer) {
  29381. this._buffer = data;
  29382. this._ownsBuffer = false;
  29383. }
  29384. else {
  29385. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29386. this._ownsBuffer = true;
  29387. }
  29388. this._kind = kind;
  29389. if (type == undefined) {
  29390. var data_1 = this.getData();
  29391. this.type = VertexBuffer.FLOAT;
  29392. if (data_1 instanceof Int8Array)
  29393. this.type = VertexBuffer.BYTE;
  29394. else if (data_1 instanceof Uint8Array)
  29395. this.type = VertexBuffer.UNSIGNED_BYTE;
  29396. else if (data_1 instanceof Int16Array)
  29397. this.type = VertexBuffer.SHORT;
  29398. else if (data_1 instanceof Uint16Array)
  29399. this.type = VertexBuffer.UNSIGNED_SHORT;
  29400. else if (data_1 instanceof Int32Array)
  29401. this.type = VertexBuffer.INT;
  29402. else if (data_1 instanceof Uint32Array)
  29403. this.type = VertexBuffer.UNSIGNED_INT;
  29404. }
  29405. else {
  29406. this.type = type;
  29407. }
  29408. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29409. if (useBytes) {
  29410. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29411. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29412. this.byteOffset = offset || 0;
  29413. }
  29414. else {
  29415. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29416. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29417. this.byteOffset = (offset || 0) * typeByteLength;
  29418. }
  29419. this.normalized = normalized;
  29420. this._instanced = instanced !== undefined ? instanced : false;
  29421. this._instanceDivisor = instanced ? 1 : 0;
  29422. }
  29423. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29424. /**
  29425. * Gets or sets the instance divisor when in instanced mode
  29426. */
  29427. get: function () {
  29428. return this._instanceDivisor;
  29429. },
  29430. set: function (value) {
  29431. this._instanceDivisor = value;
  29432. if (value == 0) {
  29433. this._instanced = false;
  29434. }
  29435. else {
  29436. this._instanced = true;
  29437. }
  29438. },
  29439. enumerable: true,
  29440. configurable: true
  29441. });
  29442. /** @hidden */
  29443. VertexBuffer.prototype._rebuild = function () {
  29444. if (!this._buffer) {
  29445. return;
  29446. }
  29447. this._buffer._rebuild();
  29448. };
  29449. /**
  29450. * Returns the kind of the VertexBuffer (string).
  29451. */
  29452. VertexBuffer.prototype.getKind = function () {
  29453. return this._kind;
  29454. };
  29455. // Properties
  29456. /**
  29457. * Boolean : is the VertexBuffer updatable ?
  29458. */
  29459. VertexBuffer.prototype.isUpdatable = function () {
  29460. return this._buffer.isUpdatable();
  29461. };
  29462. /**
  29463. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29464. */
  29465. VertexBuffer.prototype.getData = function () {
  29466. return this._buffer.getData();
  29467. };
  29468. /**
  29469. * Returns the WebGLBuffer associated to the VertexBuffer.
  29470. */
  29471. VertexBuffer.prototype.getBuffer = function () {
  29472. return this._buffer.getBuffer();
  29473. };
  29474. /**
  29475. * Returns the stride as a multiple of the type byte length.
  29476. * DEPRECATED. Use byteStride instead.
  29477. */
  29478. VertexBuffer.prototype.getStrideSize = function () {
  29479. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29480. };
  29481. /**
  29482. * Returns the offset as a multiple of the type byte length.
  29483. * DEPRECATED. Use byteOffset instead.
  29484. */
  29485. VertexBuffer.prototype.getOffset = function () {
  29486. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29487. };
  29488. /**
  29489. * Returns the number of components per vertex attribute (integer).
  29490. */
  29491. VertexBuffer.prototype.getSize = function () {
  29492. return this._size;
  29493. };
  29494. /**
  29495. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29496. */
  29497. VertexBuffer.prototype.getIsInstanced = function () {
  29498. return this._instanced;
  29499. };
  29500. /**
  29501. * Returns the instancing divisor, zero for non-instanced (integer).
  29502. */
  29503. VertexBuffer.prototype.getInstanceDivisor = function () {
  29504. return this._instanceDivisor;
  29505. };
  29506. // Methods
  29507. /**
  29508. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29509. * Returns the created WebGLBuffer.
  29510. */
  29511. VertexBuffer.prototype.create = function (data) {
  29512. return this._buffer.create(data);
  29513. };
  29514. /**
  29515. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29516. * This function will create a new buffer if the current one is not updatable
  29517. * Returns the updated WebGLBuffer.
  29518. */
  29519. VertexBuffer.prototype.update = function (data) {
  29520. return this._buffer.update(data);
  29521. };
  29522. /**
  29523. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29524. * Returns the directly updated WebGLBuffer.
  29525. * @param data the new data
  29526. * @param offset the new offset
  29527. * @param useBytes set to true if the offset is in bytes
  29528. */
  29529. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29530. if (useBytes === void 0) { useBytes = false; }
  29531. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29532. };
  29533. /**
  29534. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29535. */
  29536. VertexBuffer.prototype.dispose = function () {
  29537. if (this._ownsBuffer) {
  29538. this._buffer.dispose();
  29539. }
  29540. };
  29541. /**
  29542. * Enumerates each value of this vertex buffer as numbers.
  29543. * @param count the number of values to enumerate
  29544. * @param callback the callback function called for each value
  29545. */
  29546. VertexBuffer.prototype.forEach = function (count, callback) {
  29547. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29548. };
  29549. Object.defineProperty(VertexBuffer, "PositionKind", {
  29550. get: function () {
  29551. return VertexBuffer._PositionKind;
  29552. },
  29553. enumerable: true,
  29554. configurable: true
  29555. });
  29556. Object.defineProperty(VertexBuffer, "NormalKind", {
  29557. get: function () {
  29558. return VertexBuffer._NormalKind;
  29559. },
  29560. enumerable: true,
  29561. configurable: true
  29562. });
  29563. Object.defineProperty(VertexBuffer, "TangentKind", {
  29564. get: function () {
  29565. return VertexBuffer._TangentKind;
  29566. },
  29567. enumerable: true,
  29568. configurable: true
  29569. });
  29570. Object.defineProperty(VertexBuffer, "UVKind", {
  29571. get: function () {
  29572. return VertexBuffer._UVKind;
  29573. },
  29574. enumerable: true,
  29575. configurable: true
  29576. });
  29577. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29578. get: function () {
  29579. return VertexBuffer._UV2Kind;
  29580. },
  29581. enumerable: true,
  29582. configurable: true
  29583. });
  29584. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29585. get: function () {
  29586. return VertexBuffer._UV3Kind;
  29587. },
  29588. enumerable: true,
  29589. configurable: true
  29590. });
  29591. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29592. get: function () {
  29593. return VertexBuffer._UV4Kind;
  29594. },
  29595. enumerable: true,
  29596. configurable: true
  29597. });
  29598. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29599. get: function () {
  29600. return VertexBuffer._UV5Kind;
  29601. },
  29602. enumerable: true,
  29603. configurable: true
  29604. });
  29605. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29606. get: function () {
  29607. return VertexBuffer._UV6Kind;
  29608. },
  29609. enumerable: true,
  29610. configurable: true
  29611. });
  29612. Object.defineProperty(VertexBuffer, "ColorKind", {
  29613. get: function () {
  29614. return VertexBuffer._ColorKind;
  29615. },
  29616. enumerable: true,
  29617. configurable: true
  29618. });
  29619. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29620. get: function () {
  29621. return VertexBuffer._MatricesIndicesKind;
  29622. },
  29623. enumerable: true,
  29624. configurable: true
  29625. });
  29626. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29627. get: function () {
  29628. return VertexBuffer._MatricesWeightsKind;
  29629. },
  29630. enumerable: true,
  29631. configurable: true
  29632. });
  29633. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29634. get: function () {
  29635. return VertexBuffer._MatricesIndicesExtraKind;
  29636. },
  29637. enumerable: true,
  29638. configurable: true
  29639. });
  29640. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29641. get: function () {
  29642. return VertexBuffer._MatricesWeightsExtraKind;
  29643. },
  29644. enumerable: true,
  29645. configurable: true
  29646. });
  29647. /**
  29648. * Deduces the stride given a kind.
  29649. * @param kind The kind string to deduce
  29650. * @returns The deduced stride
  29651. */
  29652. VertexBuffer.DeduceStride = function (kind) {
  29653. switch (kind) {
  29654. case VertexBuffer.UVKind:
  29655. case VertexBuffer.UV2Kind:
  29656. case VertexBuffer.UV3Kind:
  29657. case VertexBuffer.UV4Kind:
  29658. case VertexBuffer.UV5Kind:
  29659. case VertexBuffer.UV6Kind:
  29660. return 2;
  29661. case VertexBuffer.NormalKind:
  29662. case VertexBuffer.PositionKind:
  29663. return 3;
  29664. case VertexBuffer.ColorKind:
  29665. case VertexBuffer.MatricesIndicesKind:
  29666. case VertexBuffer.MatricesIndicesExtraKind:
  29667. case VertexBuffer.MatricesWeightsKind:
  29668. case VertexBuffer.MatricesWeightsExtraKind:
  29669. case VertexBuffer.TangentKind:
  29670. return 4;
  29671. default:
  29672. throw new Error("Invalid kind '" + kind + "'");
  29673. }
  29674. };
  29675. /**
  29676. * Gets the byte length of the given type.
  29677. * @param type the type
  29678. * @returns the number of bytes
  29679. */
  29680. VertexBuffer.GetTypeByteLength = function (type) {
  29681. switch (type) {
  29682. case VertexBuffer.BYTE:
  29683. case VertexBuffer.UNSIGNED_BYTE:
  29684. return 1;
  29685. case VertexBuffer.SHORT:
  29686. case VertexBuffer.UNSIGNED_SHORT:
  29687. return 2;
  29688. case VertexBuffer.INT:
  29689. case VertexBuffer.FLOAT:
  29690. return 4;
  29691. default:
  29692. throw new Error("Invalid type '" + type + "'");
  29693. }
  29694. };
  29695. /**
  29696. * Enumerates each value of the given parameters as numbers.
  29697. * @param data the data to enumerate
  29698. * @param byteOffset the byte offset of the data
  29699. * @param byteStride the byte stride of the data
  29700. * @param componentCount the number of components per element
  29701. * @param componentType the type of the component
  29702. * @param count the total number of components
  29703. * @param normalized whether the data is normalized
  29704. * @param callback the callback function called for each value
  29705. */
  29706. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29707. if (data instanceof Array) {
  29708. var offset = byteOffset / 4;
  29709. var stride = byteStride / 4;
  29710. for (var index = 0; index < count; index += componentCount) {
  29711. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29712. callback(data[offset + componentIndex], index + componentIndex);
  29713. }
  29714. offset += stride;
  29715. }
  29716. }
  29717. else {
  29718. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29719. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29720. for (var index = 0; index < count; index += componentCount) {
  29721. var componentByteOffset = byteOffset;
  29722. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29723. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29724. callback(value, index + componentIndex);
  29725. componentByteOffset += componentByteLength;
  29726. }
  29727. byteOffset += byteStride;
  29728. }
  29729. }
  29730. };
  29731. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29732. switch (type) {
  29733. case VertexBuffer.BYTE: {
  29734. var value = dataView.getInt8(byteOffset);
  29735. if (normalized) {
  29736. value = Math.max(value / 127, -1);
  29737. }
  29738. return value;
  29739. }
  29740. case VertexBuffer.UNSIGNED_BYTE: {
  29741. var value = dataView.getUint8(byteOffset);
  29742. if (normalized) {
  29743. value = value / 255;
  29744. }
  29745. return value;
  29746. }
  29747. case VertexBuffer.SHORT: {
  29748. var value = dataView.getInt16(byteOffset, true);
  29749. if (normalized) {
  29750. value = Math.max(value / 16383, -1);
  29751. }
  29752. return value;
  29753. }
  29754. case VertexBuffer.UNSIGNED_SHORT: {
  29755. var value = dataView.getUint16(byteOffset, true);
  29756. if (normalized) {
  29757. value = value / 65535;
  29758. }
  29759. return value;
  29760. }
  29761. case VertexBuffer.FLOAT: {
  29762. return dataView.getFloat32(byteOffset, true);
  29763. }
  29764. default: {
  29765. throw new Error("Invalid component type " + type);
  29766. }
  29767. }
  29768. };
  29769. /**
  29770. * The byte type.
  29771. */
  29772. VertexBuffer.BYTE = 5120;
  29773. /**
  29774. * The unsigned byte type.
  29775. */
  29776. VertexBuffer.UNSIGNED_BYTE = 5121;
  29777. /**
  29778. * The short type.
  29779. */
  29780. VertexBuffer.SHORT = 5122;
  29781. /**
  29782. * The unsigned short type.
  29783. */
  29784. VertexBuffer.UNSIGNED_SHORT = 5123;
  29785. /**
  29786. * The integer type.
  29787. */
  29788. VertexBuffer.INT = 5124;
  29789. /**
  29790. * The unsigned integer type.
  29791. */
  29792. VertexBuffer.UNSIGNED_INT = 5125;
  29793. /**
  29794. * The float type.
  29795. */
  29796. VertexBuffer.FLOAT = 5126;
  29797. // Enums
  29798. VertexBuffer._PositionKind = "position";
  29799. VertexBuffer._NormalKind = "normal";
  29800. VertexBuffer._TangentKind = "tangent";
  29801. VertexBuffer._UVKind = "uv";
  29802. VertexBuffer._UV2Kind = "uv2";
  29803. VertexBuffer._UV3Kind = "uv3";
  29804. VertexBuffer._UV4Kind = "uv4";
  29805. VertexBuffer._UV5Kind = "uv5";
  29806. VertexBuffer._UV6Kind = "uv6";
  29807. VertexBuffer._ColorKind = "color";
  29808. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29809. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29810. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29811. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29812. return VertexBuffer;
  29813. }());
  29814. BABYLON.VertexBuffer = VertexBuffer;
  29815. })(BABYLON || (BABYLON = {}));
  29816. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29817. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  29818. var BABYLON;
  29819. (function (BABYLON) {
  29820. /**
  29821. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29822. */
  29823. var DummyInternalTextureTracker = /** @class */ (function () {
  29824. function DummyInternalTextureTracker() {
  29825. /**
  29826. * Gets or set the previous tracker in the list
  29827. */
  29828. this.previous = null;
  29829. /**
  29830. * Gets or set the next tracker in the list
  29831. */
  29832. this.next = null;
  29833. }
  29834. return DummyInternalTextureTracker;
  29835. }());
  29836. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29837. })(BABYLON || (BABYLON = {}));
  29838. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29839. var BABYLON;
  29840. (function (BABYLON) {
  29841. /**
  29842. * Class used to store data associated with WebGL texture data for the engine
  29843. * This class should not be used directly
  29844. */
  29845. var InternalTexture = /** @class */ (function () {
  29846. /**
  29847. * Creates a new InternalTexture
  29848. * @param engine defines the engine to use
  29849. * @param dataSource defines the type of data that will be used
  29850. */
  29851. function InternalTexture(engine, dataSource) {
  29852. /**
  29853. * Observable called when the texture is loaded
  29854. */
  29855. this.onLoadedObservable = new BABYLON.Observable();
  29856. /**
  29857. * Gets or set the previous tracker in the list
  29858. */
  29859. this.previous = null;
  29860. /**
  29861. * Gets or set the next tracker in the list
  29862. */
  29863. this.next = null;
  29864. // Private
  29865. /** @hidden */
  29866. this._initialSlot = -1;
  29867. /** @hidden */
  29868. this._designatedSlot = -1;
  29869. /** @hidden */
  29870. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29871. /** @hidden */
  29872. this._comparisonFunction = 0;
  29873. /** @hidden */
  29874. this._sphericalPolynomial = null;
  29875. /** @hidden */
  29876. this._lodGenerationScale = 0;
  29877. /** @hidden */
  29878. this._lodGenerationOffset = 0;
  29879. /** @hidden */
  29880. this._isRGBD = false;
  29881. /** @hidden */
  29882. this._references = 1;
  29883. this._engine = engine;
  29884. this._dataSource = dataSource;
  29885. this._webGLTexture = engine._createTexture();
  29886. }
  29887. /**
  29888. * Gets the Engine the texture belongs to.
  29889. * @returns The babylon engine
  29890. */
  29891. InternalTexture.prototype.getEngine = function () {
  29892. return this._engine;
  29893. };
  29894. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29895. /**
  29896. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29897. */
  29898. get: function () {
  29899. return this._dataSource;
  29900. },
  29901. enumerable: true,
  29902. configurable: true
  29903. });
  29904. /**
  29905. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29906. */
  29907. InternalTexture.prototype.incrementReferences = function () {
  29908. this._references++;
  29909. };
  29910. /**
  29911. * Change the size of the texture (not the size of the content)
  29912. * @param width defines the new width
  29913. * @param height defines the new height
  29914. * @param depth defines the new depth (1 by default)
  29915. */
  29916. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29917. if (depth === void 0) { depth = 1; }
  29918. this.width = width;
  29919. this.height = height;
  29920. this.depth = depth;
  29921. this.baseWidth = width;
  29922. this.baseHeight = height;
  29923. this.baseDepth = depth;
  29924. this._size = width * height * depth;
  29925. };
  29926. /** @hidden */
  29927. InternalTexture.prototype._rebuild = function () {
  29928. var _this = this;
  29929. var proxy;
  29930. this.isReady = false;
  29931. this._cachedCoordinatesMode = null;
  29932. this._cachedWrapU = null;
  29933. this._cachedWrapV = null;
  29934. this._cachedAnisotropicFilteringLevel = null;
  29935. switch (this._dataSource) {
  29936. case InternalTexture.DATASOURCE_TEMP:
  29937. return;
  29938. case InternalTexture.DATASOURCE_URL:
  29939. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29940. _this.isReady = true;
  29941. }, null, this._buffer, undefined, this.format);
  29942. proxy._swapAndDie(this);
  29943. return;
  29944. case InternalTexture.DATASOURCE_RAW:
  29945. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29946. proxy._swapAndDie(this);
  29947. this.isReady = true;
  29948. return;
  29949. case InternalTexture.DATASOURCE_RAW3D:
  29950. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29951. proxy._swapAndDie(this);
  29952. this.isReady = true;
  29953. return;
  29954. case InternalTexture.DATASOURCE_DYNAMIC:
  29955. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29956. proxy._swapAndDie(this);
  29957. // The engine will make sure to update content so no need to flag it as isReady = true
  29958. return;
  29959. case InternalTexture.DATASOURCE_RENDERTARGET:
  29960. var options = new BABYLON.RenderTargetCreationOptions();
  29961. options.generateDepthBuffer = this._generateDepthBuffer;
  29962. options.generateMipMaps = this.generateMipMaps;
  29963. options.generateStencilBuffer = this._generateStencilBuffer;
  29964. options.samplingMode = this.samplingMode;
  29965. options.type = this.type;
  29966. if (this.isCube) {
  29967. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29968. }
  29969. else {
  29970. var size = {
  29971. width: this.width,
  29972. height: this.height
  29973. };
  29974. proxy = this._engine.createRenderTargetTexture(size, options);
  29975. }
  29976. proxy._swapAndDie(this);
  29977. this.isReady = true;
  29978. return;
  29979. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29980. var depthTextureOptions = {
  29981. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29982. comparisonFunction: this._comparisonFunction,
  29983. generateStencil: this._generateStencilBuffer,
  29984. isCube: this.isCube
  29985. };
  29986. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29987. proxy._swapAndDie(this);
  29988. this.isReady = true;
  29989. return;
  29990. case InternalTexture.DATASOURCE_CUBE:
  29991. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29992. _this.isReady = true;
  29993. }, null, this.format, this._extension);
  29994. proxy._swapAndDie(this);
  29995. return;
  29996. case InternalTexture.DATASOURCE_CUBERAW:
  29997. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29998. proxy._swapAndDie(this);
  29999. this.isReady = true;
  30000. return;
  30001. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  30002. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30003. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  30004. _this.isReady = true;
  30005. });
  30006. proxy._swapAndDie(this);
  30007. return;
  30008. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30009. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30010. if (proxy) {
  30011. proxy._swapAndDie(_this);
  30012. }
  30013. _this.isReady = true;
  30014. }, null, this.format, this._extension);
  30015. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30016. return;
  30017. }
  30018. };
  30019. /** @hidden */
  30020. InternalTexture.prototype._swapAndDie = function (target) {
  30021. target._webGLTexture = this._webGLTexture;
  30022. if (this._framebuffer) {
  30023. target._framebuffer = this._framebuffer;
  30024. }
  30025. if (this._depthStencilBuffer) {
  30026. target._depthStencilBuffer = this._depthStencilBuffer;
  30027. }
  30028. if (this._lodTextureHigh) {
  30029. if (target._lodTextureHigh) {
  30030. target._lodTextureHigh.dispose();
  30031. }
  30032. target._lodTextureHigh = this._lodTextureHigh;
  30033. }
  30034. if (this._lodTextureMid) {
  30035. if (target._lodTextureMid) {
  30036. target._lodTextureMid.dispose();
  30037. }
  30038. target._lodTextureMid = this._lodTextureMid;
  30039. }
  30040. if (this._lodTextureLow) {
  30041. if (target._lodTextureLow) {
  30042. target._lodTextureLow.dispose();
  30043. }
  30044. target._lodTextureLow = this._lodTextureLow;
  30045. }
  30046. var cache = this._engine.getLoadedTexturesCache();
  30047. var index = cache.indexOf(this);
  30048. if (index !== -1) {
  30049. cache.splice(index, 1);
  30050. }
  30051. };
  30052. /**
  30053. * Dispose the current allocated resources
  30054. */
  30055. InternalTexture.prototype.dispose = function () {
  30056. if (!this._webGLTexture) {
  30057. return;
  30058. }
  30059. this._references--;
  30060. if (this._references === 0) {
  30061. this._engine._releaseTexture(this);
  30062. this._webGLTexture = null;
  30063. this.previous = null;
  30064. this.next = null;
  30065. }
  30066. };
  30067. /**
  30068. * The source of the texture data is unknown
  30069. */
  30070. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30071. /**
  30072. * Texture data comes from an URL
  30073. */
  30074. InternalTexture.DATASOURCE_URL = 1;
  30075. /**
  30076. * Texture data is only used for temporary storage
  30077. */
  30078. InternalTexture.DATASOURCE_TEMP = 2;
  30079. /**
  30080. * Texture data comes from raw data (ArrayBuffer)
  30081. */
  30082. InternalTexture.DATASOURCE_RAW = 3;
  30083. /**
  30084. * Texture content is dynamic (video or dynamic texture)
  30085. */
  30086. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30087. /**
  30088. * Texture content is generated by rendering to it
  30089. */
  30090. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30091. /**
  30092. * Texture content is part of a multi render target process
  30093. */
  30094. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30095. /**
  30096. * Texture data comes from a cube data file
  30097. */
  30098. InternalTexture.DATASOURCE_CUBE = 7;
  30099. /**
  30100. * Texture data comes from a raw cube data
  30101. */
  30102. InternalTexture.DATASOURCE_CUBERAW = 8;
  30103. /**
  30104. * Texture data come from a prefiltered cube data file
  30105. */
  30106. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30107. /**
  30108. * Texture content is raw 3D data
  30109. */
  30110. InternalTexture.DATASOURCE_RAW3D = 10;
  30111. /**
  30112. * Texture content is a depth texture
  30113. */
  30114. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30115. /**
  30116. * Texture data comes from a raw cube data encoded with RGBD
  30117. */
  30118. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  30119. return InternalTexture;
  30120. }());
  30121. BABYLON.InternalTexture = InternalTexture;
  30122. })(BABYLON || (BABYLON = {}));
  30123. //# sourceMappingURL=babylon.internalTexture.js.map
  30124. var BABYLON;
  30125. (function (BABYLON) {
  30126. var BaseTexture = /** @class */ (function () {
  30127. function BaseTexture(scene) {
  30128. this._hasAlpha = false;
  30129. this.getAlphaFromRGB = false;
  30130. this.level = 1;
  30131. this.coordinatesIndex = 0;
  30132. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30133. /**
  30134. * | Value | Type | Description |
  30135. * | ----- | ------------------ | ----------- |
  30136. * | 0 | CLAMP_ADDRESSMODE | |
  30137. * | 1 | WRAP_ADDRESSMODE | |
  30138. * | 2 | MIRROR_ADDRESSMODE | |
  30139. */
  30140. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30141. /**
  30142. * | Value | Type | Description |
  30143. * | ----- | ------------------ | ----------- |
  30144. * | 0 | CLAMP_ADDRESSMODE | |
  30145. * | 1 | WRAP_ADDRESSMODE | |
  30146. * | 2 | MIRROR_ADDRESSMODE | |
  30147. */
  30148. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30149. /**
  30150. * | Value | Type | Description |
  30151. * | ----- | ------------------ | ----------- |
  30152. * | 0 | CLAMP_ADDRESSMODE | |
  30153. * | 1 | WRAP_ADDRESSMODE | |
  30154. * | 2 | MIRROR_ADDRESSMODE | |
  30155. */
  30156. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30157. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30158. this.isCube = false;
  30159. this.is3D = false;
  30160. this.gammaSpace = true;
  30161. this.invertZ = false;
  30162. this.lodLevelInAlpha = false;
  30163. this.isRenderTarget = false;
  30164. this.animations = new Array();
  30165. /**
  30166. * An event triggered when the texture is disposed.
  30167. */
  30168. this.onDisposeObservable = new BABYLON.Observable();
  30169. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30170. this._cachedSize = BABYLON.Size.Zero();
  30171. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30172. if (this._scene) {
  30173. this._scene.textures.push(this);
  30174. }
  30175. this._uid = null;
  30176. }
  30177. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30178. get: function () {
  30179. return this._hasAlpha;
  30180. },
  30181. set: function (value) {
  30182. if (this._hasAlpha === value) {
  30183. return;
  30184. }
  30185. this._hasAlpha = value;
  30186. if (this._scene) {
  30187. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30188. }
  30189. },
  30190. enumerable: true,
  30191. configurable: true
  30192. });
  30193. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30194. get: function () {
  30195. return this._coordinatesMode;
  30196. },
  30197. /**
  30198. * How a texture is mapped.
  30199. *
  30200. * | Value | Type | Description |
  30201. * | ----- | ----------------------------------- | ----------- |
  30202. * | 0 | EXPLICIT_MODE | |
  30203. * | 1 | SPHERICAL_MODE | |
  30204. * | 2 | PLANAR_MODE | |
  30205. * | 3 | CUBIC_MODE | |
  30206. * | 4 | PROJECTION_MODE | |
  30207. * | 5 | SKYBOX_MODE | |
  30208. * | 6 | INVCUBIC_MODE | |
  30209. * | 7 | EQUIRECTANGULAR_MODE | |
  30210. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30211. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30212. */
  30213. set: function (value) {
  30214. if (this._coordinatesMode === value) {
  30215. return;
  30216. }
  30217. this._coordinatesMode = value;
  30218. if (this._scene) {
  30219. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30220. }
  30221. },
  30222. enumerable: true,
  30223. configurable: true
  30224. });
  30225. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30226. /**
  30227. * Gets whether or not the texture contains RGBD data.
  30228. */
  30229. get: function () {
  30230. return this._texture != null && this._texture._isRGBD;
  30231. },
  30232. enumerable: true,
  30233. configurable: true
  30234. });
  30235. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30236. get: function () {
  30237. if (this._texture)
  30238. return this._texture._lodGenerationOffset;
  30239. return 0.0;
  30240. },
  30241. set: function (value) {
  30242. if (this._texture)
  30243. this._texture._lodGenerationOffset = value;
  30244. },
  30245. enumerable: true,
  30246. configurable: true
  30247. });
  30248. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30249. get: function () {
  30250. if (this._texture)
  30251. return this._texture._lodGenerationScale;
  30252. return 0.0;
  30253. },
  30254. set: function (value) {
  30255. if (this._texture)
  30256. this._texture._lodGenerationScale = value;
  30257. },
  30258. enumerable: true,
  30259. configurable: true
  30260. });
  30261. Object.defineProperty(BaseTexture.prototype, "uid", {
  30262. get: function () {
  30263. if (!this._uid) {
  30264. this._uid = BABYLON.Tools.RandomId();
  30265. }
  30266. return this._uid;
  30267. },
  30268. enumerable: true,
  30269. configurable: true
  30270. });
  30271. BaseTexture.prototype.toString = function () {
  30272. return this.name;
  30273. };
  30274. BaseTexture.prototype.getClassName = function () {
  30275. return "BaseTexture";
  30276. };
  30277. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30278. set: function (callback) {
  30279. if (this._onDisposeObserver) {
  30280. this.onDisposeObservable.remove(this._onDisposeObserver);
  30281. }
  30282. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30283. },
  30284. enumerable: true,
  30285. configurable: true
  30286. });
  30287. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30288. get: function () {
  30289. return true;
  30290. },
  30291. enumerable: true,
  30292. configurable: true
  30293. });
  30294. BaseTexture.prototype.getScene = function () {
  30295. return this._scene;
  30296. };
  30297. BaseTexture.prototype.getTextureMatrix = function () {
  30298. return BABYLON.Matrix.IdentityReadOnly;
  30299. };
  30300. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30301. return BABYLON.Matrix.IdentityReadOnly;
  30302. };
  30303. BaseTexture.prototype.getInternalTexture = function () {
  30304. return this._texture;
  30305. };
  30306. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30307. return !this.isBlocking || this.isReady();
  30308. };
  30309. BaseTexture.prototype.isReady = function () {
  30310. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30311. this.delayLoad();
  30312. return false;
  30313. }
  30314. if (this._texture) {
  30315. return this._texture.isReady;
  30316. }
  30317. return false;
  30318. };
  30319. BaseTexture.prototype.getSize = function () {
  30320. if (this._texture) {
  30321. if (this._texture.width) {
  30322. this._cachedSize.width = this._texture.width;
  30323. this._cachedSize.height = this._texture.height;
  30324. return this._cachedSize;
  30325. }
  30326. if (this._texture._size) {
  30327. this._cachedSize.width = this._texture._size;
  30328. this._cachedSize.height = this._texture._size;
  30329. return this._cachedSize;
  30330. }
  30331. }
  30332. return this._cachedSize;
  30333. };
  30334. BaseTexture.prototype.getBaseSize = function () {
  30335. if (!this.isReady() || !this._texture)
  30336. return BABYLON.Size.Zero();
  30337. if (this._texture._size) {
  30338. return new BABYLON.Size(this._texture._size, this._texture._size);
  30339. }
  30340. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30341. };
  30342. BaseTexture.prototype.scale = function (ratio) {
  30343. };
  30344. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30345. get: function () {
  30346. return false;
  30347. },
  30348. enumerable: true,
  30349. configurable: true
  30350. });
  30351. /** @hidden */
  30352. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30353. if (!this._scene) {
  30354. return null;
  30355. }
  30356. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30357. for (var index = 0; index < texturesCache.length; index++) {
  30358. var texturesCacheEntry = texturesCache[index];
  30359. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30360. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30361. texturesCacheEntry.incrementReferences();
  30362. return texturesCacheEntry;
  30363. }
  30364. }
  30365. }
  30366. return null;
  30367. };
  30368. /** @hidden */
  30369. BaseTexture.prototype._rebuild = function () {
  30370. };
  30371. BaseTexture.prototype.delayLoad = function () {
  30372. };
  30373. BaseTexture.prototype.clone = function () {
  30374. return null;
  30375. };
  30376. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30377. get: function () {
  30378. if (!this._texture) {
  30379. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30380. }
  30381. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30382. },
  30383. enumerable: true,
  30384. configurable: true
  30385. });
  30386. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30387. get: function () {
  30388. if (!this._texture) {
  30389. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30390. }
  30391. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30392. },
  30393. enumerable: true,
  30394. configurable: true
  30395. });
  30396. /**
  30397. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30398. * This will returns an RGBA array buffer containing either in values (0-255) or
  30399. * float values (0-1) depending of the underlying buffer type.
  30400. * @param faceIndex The face of the texture to read (in case of cube texture)
  30401. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30402. * @returns The Array buffer containing the pixels data.
  30403. */
  30404. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30405. if (faceIndex === void 0) { faceIndex = 0; }
  30406. if (level === void 0) { level = 0; }
  30407. if (!this._texture) {
  30408. return null;
  30409. }
  30410. var size = this.getSize();
  30411. var width = size.width;
  30412. var height = size.height;
  30413. var scene = this.getScene();
  30414. if (!scene) {
  30415. return null;
  30416. }
  30417. var engine = scene.getEngine();
  30418. if (level != 0) {
  30419. width = width / Math.pow(2, level);
  30420. height = height / Math.pow(2, level);
  30421. width = Math.round(width);
  30422. height = Math.round(height);
  30423. }
  30424. if (this._texture.isCube) {
  30425. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30426. }
  30427. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30428. };
  30429. BaseTexture.prototype.releaseInternalTexture = function () {
  30430. if (this._texture) {
  30431. this._texture.dispose();
  30432. this._texture = null;
  30433. }
  30434. };
  30435. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30436. get: function () {
  30437. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30438. return null;
  30439. }
  30440. if (!this._texture._sphericalPolynomial) {
  30441. this._texture._sphericalPolynomial =
  30442. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30443. }
  30444. return this._texture._sphericalPolynomial;
  30445. },
  30446. set: function (value) {
  30447. if (this._texture) {
  30448. this._texture._sphericalPolynomial = value;
  30449. }
  30450. },
  30451. enumerable: true,
  30452. configurable: true
  30453. });
  30454. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30455. get: function () {
  30456. if (this._texture) {
  30457. return this._texture._lodTextureHigh;
  30458. }
  30459. return null;
  30460. },
  30461. enumerable: true,
  30462. configurable: true
  30463. });
  30464. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30465. get: function () {
  30466. if (this._texture) {
  30467. return this._texture._lodTextureMid;
  30468. }
  30469. return null;
  30470. },
  30471. enumerable: true,
  30472. configurable: true
  30473. });
  30474. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30475. get: function () {
  30476. if (this._texture) {
  30477. return this._texture._lodTextureLow;
  30478. }
  30479. return null;
  30480. },
  30481. enumerable: true,
  30482. configurable: true
  30483. });
  30484. BaseTexture.prototype.dispose = function () {
  30485. if (!this._scene) {
  30486. return;
  30487. }
  30488. // Animations
  30489. this._scene.stopAnimation(this);
  30490. // Remove from scene
  30491. this._scene._removePendingData(this);
  30492. var index = this._scene.textures.indexOf(this);
  30493. if (index >= 0) {
  30494. this._scene.textures.splice(index, 1);
  30495. }
  30496. if (this._texture === undefined) {
  30497. return;
  30498. }
  30499. // Release
  30500. this.releaseInternalTexture();
  30501. // Callback
  30502. this.onDisposeObservable.notifyObservers(this);
  30503. this.onDisposeObservable.clear();
  30504. };
  30505. BaseTexture.prototype.serialize = function () {
  30506. if (!this.name) {
  30507. return null;
  30508. }
  30509. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30510. // Animations
  30511. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30512. return serializationObject;
  30513. };
  30514. BaseTexture.WhenAllReady = function (textures, callback) {
  30515. var numRemaining = textures.length;
  30516. if (numRemaining === 0) {
  30517. callback();
  30518. return;
  30519. }
  30520. var _loop_1 = function () {
  30521. texture = textures[i];
  30522. if (texture.isReady()) {
  30523. if (--numRemaining === 0) {
  30524. callback();
  30525. }
  30526. }
  30527. else {
  30528. onLoadObservable = texture.onLoadObservable;
  30529. var onLoadCallback_1 = function () {
  30530. onLoadObservable.removeCallback(onLoadCallback_1);
  30531. if (--numRemaining === 0) {
  30532. callback();
  30533. }
  30534. };
  30535. onLoadObservable.add(onLoadCallback_1);
  30536. }
  30537. };
  30538. var texture, onLoadObservable;
  30539. for (var i = 0; i < textures.length; i++) {
  30540. _loop_1();
  30541. }
  30542. };
  30543. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30544. __decorate([
  30545. BABYLON.serialize()
  30546. ], BaseTexture.prototype, "name", void 0);
  30547. __decorate([
  30548. BABYLON.serialize("hasAlpha")
  30549. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30550. __decorate([
  30551. BABYLON.serialize()
  30552. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30553. __decorate([
  30554. BABYLON.serialize()
  30555. ], BaseTexture.prototype, "level", void 0);
  30556. __decorate([
  30557. BABYLON.serialize()
  30558. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30559. __decorate([
  30560. BABYLON.serialize("coordinatesMode")
  30561. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30562. __decorate([
  30563. BABYLON.serialize()
  30564. ], BaseTexture.prototype, "wrapU", void 0);
  30565. __decorate([
  30566. BABYLON.serialize()
  30567. ], BaseTexture.prototype, "wrapV", void 0);
  30568. __decorate([
  30569. BABYLON.serialize()
  30570. ], BaseTexture.prototype, "wrapR", void 0);
  30571. __decorate([
  30572. BABYLON.serialize()
  30573. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30574. __decorate([
  30575. BABYLON.serialize()
  30576. ], BaseTexture.prototype, "isCube", void 0);
  30577. __decorate([
  30578. BABYLON.serialize()
  30579. ], BaseTexture.prototype, "is3D", void 0);
  30580. __decorate([
  30581. BABYLON.serialize()
  30582. ], BaseTexture.prototype, "gammaSpace", void 0);
  30583. __decorate([
  30584. BABYLON.serialize()
  30585. ], BaseTexture.prototype, "invertZ", void 0);
  30586. __decorate([
  30587. BABYLON.serialize()
  30588. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30589. __decorate([
  30590. BABYLON.serialize()
  30591. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30592. __decorate([
  30593. BABYLON.serialize()
  30594. ], BaseTexture.prototype, "lodGenerationScale", null);
  30595. __decorate([
  30596. BABYLON.serialize()
  30597. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30598. return BaseTexture;
  30599. }());
  30600. BABYLON.BaseTexture = BaseTexture;
  30601. })(BABYLON || (BABYLON = {}));
  30602. //# sourceMappingURL=babylon.baseTexture.js.map
  30603. var BABYLON;
  30604. (function (BABYLON) {
  30605. var Texture = /** @class */ (function (_super) {
  30606. __extends(Texture, _super);
  30607. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30608. if (noMipmap === void 0) { noMipmap = false; }
  30609. if (invertY === void 0) { invertY = true; }
  30610. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30611. if (onLoad === void 0) { onLoad = null; }
  30612. if (onError === void 0) { onError = null; }
  30613. if (buffer === void 0) { buffer = null; }
  30614. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30615. var _this = _super.call(this, scene) || this;
  30616. _this.uOffset = 0;
  30617. _this.vOffset = 0;
  30618. _this.uScale = 1.0;
  30619. _this.vScale = 1.0;
  30620. _this.uAng = 0;
  30621. _this.vAng = 0;
  30622. _this.wAng = 0;
  30623. /**
  30624. * Defines the center of rotation (U)
  30625. */
  30626. _this.uRotationCenter = 0.5;
  30627. /**
  30628. * Defines the center of rotation (V)
  30629. */
  30630. _this.vRotationCenter = 0.5;
  30631. /**
  30632. * Defines the center of rotation (W)
  30633. */
  30634. _this.wRotationCenter = 0.5;
  30635. _this._isBlocking = true;
  30636. _this.name = url || "";
  30637. _this.url = url;
  30638. _this._noMipmap = noMipmap;
  30639. _this._invertY = invertY;
  30640. _this._samplingMode = samplingMode;
  30641. _this._buffer = buffer;
  30642. _this._deleteBuffer = deleteBuffer;
  30643. if (format) {
  30644. _this._format = format;
  30645. }
  30646. scene = _this.getScene();
  30647. if (!scene) {
  30648. return _this;
  30649. }
  30650. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30651. var load = function () {
  30652. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30653. _this.onLoadObservable.notifyObservers(_this);
  30654. }
  30655. if (onLoad) {
  30656. onLoad();
  30657. }
  30658. if (!_this.isBlocking && scene) {
  30659. scene.resetCachedMaterial();
  30660. }
  30661. };
  30662. if (!_this.url) {
  30663. _this._delayedOnLoad = load;
  30664. _this._delayedOnError = onError;
  30665. return _this;
  30666. }
  30667. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30668. if (!_this._texture) {
  30669. if (!scene.useDelayedTextureLoading) {
  30670. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30671. if (deleteBuffer) {
  30672. delete _this._buffer;
  30673. }
  30674. }
  30675. else {
  30676. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30677. _this._delayedOnLoad = load;
  30678. _this._delayedOnError = onError;
  30679. }
  30680. }
  30681. else {
  30682. if (_this._texture.isReady) {
  30683. BABYLON.Tools.SetImmediate(function () { return load(); });
  30684. }
  30685. else {
  30686. _this._texture.onLoadedObservable.add(load);
  30687. }
  30688. }
  30689. return _this;
  30690. }
  30691. Object.defineProperty(Texture.prototype, "noMipmap", {
  30692. get: function () {
  30693. return this._noMipmap;
  30694. },
  30695. enumerable: true,
  30696. configurable: true
  30697. });
  30698. Object.defineProperty(Texture.prototype, "isBlocking", {
  30699. get: function () {
  30700. return this._isBlocking;
  30701. },
  30702. set: function (value) {
  30703. this._isBlocking = value;
  30704. },
  30705. enumerable: true,
  30706. configurable: true
  30707. });
  30708. Object.defineProperty(Texture.prototype, "samplingMode", {
  30709. get: function () {
  30710. return this._samplingMode;
  30711. },
  30712. enumerable: true,
  30713. configurable: true
  30714. });
  30715. /**
  30716. * Update the url (and optional buffer) of this texture if url was null during construction.
  30717. * @param url the url of the texture
  30718. * @param buffer the buffer of the texture (defaults to null)
  30719. */
  30720. Texture.prototype.updateURL = function (url, buffer) {
  30721. if (buffer === void 0) { buffer = null; }
  30722. if (this.url) {
  30723. throw new Error("URL is already set");
  30724. }
  30725. this.url = url;
  30726. this._buffer = buffer;
  30727. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30728. this.delayLoad();
  30729. };
  30730. Texture.prototype.delayLoad = function () {
  30731. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30732. return;
  30733. }
  30734. var scene = this.getScene();
  30735. if (!scene) {
  30736. return;
  30737. }
  30738. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30739. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30740. if (!this._texture) {
  30741. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30742. if (this._deleteBuffer) {
  30743. delete this._buffer;
  30744. }
  30745. }
  30746. else {
  30747. if (this._delayedOnLoad) {
  30748. if (this._texture.isReady) {
  30749. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30750. }
  30751. else {
  30752. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30753. }
  30754. }
  30755. }
  30756. this._delayedOnLoad = null;
  30757. this._delayedOnError = null;
  30758. };
  30759. /**
  30760. * Default is Trilinear mode.
  30761. *
  30762. * | Value | Type | Description |
  30763. * | ----- | ------------------ | ----------- |
  30764. * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear |
  30765. * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
  30766. * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
  30767. * | 4 | NEAREST_NEAREST_MIPNEAREST | |
  30768. * | 5 | NEAREST_LINEAR_MIPNEAREST | |
  30769. * | 6 | NEAREST_LINEAR_MIPLINEAR | |
  30770. * | 7 | NEAREST_LINEAR | |
  30771. * | 8 | NEAREST_NEAREST | |
  30772. * | 9 | LINEAR_NEAREST_MIPNEAREST | |
  30773. * | 10 | LINEAR_NEAREST_MIPLINEAR | |
  30774. * | 11 | LINEAR_LINEAR | |
  30775. * | 12 | LINEAR_NEAREST | |
  30776. *
  30777. * > _mag_: magnification filter (close to the viewer)
  30778. * > _min_: minification filter (far from the viewer)
  30779. * > _mip_: filter used between mip map levels
  30780. *
  30781. */
  30782. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30783. if (!this._texture) {
  30784. return;
  30785. }
  30786. var scene = this.getScene();
  30787. if (!scene) {
  30788. return;
  30789. }
  30790. this._samplingMode = samplingMode;
  30791. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30792. };
  30793. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30794. x *= this.uScale;
  30795. y *= this.vScale;
  30796. x -= this.uRotationCenter * this.uScale;
  30797. y -= this.vRotationCenter * this.vScale;
  30798. z -= this.wRotationCenter;
  30799. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30800. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30801. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30802. t.z += this.wRotationCenter;
  30803. };
  30804. Texture.prototype.getTextureMatrix = function () {
  30805. var _this = this;
  30806. if (this.uOffset === this._cachedUOffset &&
  30807. this.vOffset === this._cachedVOffset &&
  30808. this.uScale === this._cachedUScale &&
  30809. this.vScale === this._cachedVScale &&
  30810. this.uAng === this._cachedUAng &&
  30811. this.vAng === this._cachedVAng &&
  30812. this.wAng === this._cachedWAng) {
  30813. return this._cachedTextureMatrix;
  30814. }
  30815. this._cachedUOffset = this.uOffset;
  30816. this._cachedVOffset = this.vOffset;
  30817. this._cachedUScale = this.uScale;
  30818. this._cachedVScale = this.vScale;
  30819. this._cachedUAng = this.uAng;
  30820. this._cachedVAng = this.vAng;
  30821. this._cachedWAng = this.wAng;
  30822. if (!this._cachedTextureMatrix) {
  30823. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30824. this._rowGenerationMatrix = new BABYLON.Matrix();
  30825. this._t0 = BABYLON.Vector3.Zero();
  30826. this._t1 = BABYLON.Vector3.Zero();
  30827. this._t2 = BABYLON.Vector3.Zero();
  30828. }
  30829. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30830. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30831. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30832. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30833. this._t1.subtractInPlace(this._t0);
  30834. this._t2.subtractInPlace(this._t0);
  30835. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30836. this._cachedTextureMatrix.m[0] = this._t1.x;
  30837. this._cachedTextureMatrix.m[1] = this._t1.y;
  30838. this._cachedTextureMatrix.m[2] = this._t1.z;
  30839. this._cachedTextureMatrix.m[4] = this._t2.x;
  30840. this._cachedTextureMatrix.m[5] = this._t2.y;
  30841. this._cachedTextureMatrix.m[6] = this._t2.z;
  30842. this._cachedTextureMatrix.m[8] = this._t0.x;
  30843. this._cachedTextureMatrix.m[9] = this._t0.y;
  30844. this._cachedTextureMatrix.m[10] = this._t0.z;
  30845. var scene = this.getScene();
  30846. if (!scene) {
  30847. return this._cachedTextureMatrix;
  30848. }
  30849. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30850. return mat.hasTexture(_this);
  30851. });
  30852. return this._cachedTextureMatrix;
  30853. };
  30854. Texture.prototype.getReflectionTextureMatrix = function () {
  30855. var _this = this;
  30856. var scene = this.getScene();
  30857. if (!scene) {
  30858. return this._cachedTextureMatrix;
  30859. }
  30860. if (this.uOffset === this._cachedUOffset &&
  30861. this.vOffset === this._cachedVOffset &&
  30862. this.uScale === this._cachedUScale &&
  30863. this.vScale === this._cachedVScale &&
  30864. this.coordinatesMode === this._cachedCoordinatesMode) {
  30865. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30866. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30867. return this._cachedTextureMatrix;
  30868. }
  30869. }
  30870. else {
  30871. return this._cachedTextureMatrix;
  30872. }
  30873. }
  30874. if (!this._cachedTextureMatrix) {
  30875. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30876. }
  30877. if (!this._projectionModeMatrix) {
  30878. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30879. }
  30880. this._cachedUOffset = this.uOffset;
  30881. this._cachedVOffset = this.vOffset;
  30882. this._cachedUScale = this.uScale;
  30883. this._cachedVScale = this.vScale;
  30884. this._cachedCoordinatesMode = this.coordinatesMode;
  30885. switch (this.coordinatesMode) {
  30886. case Texture.PLANAR_MODE:
  30887. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30888. this._cachedTextureMatrix[0] = this.uScale;
  30889. this._cachedTextureMatrix[5] = this.vScale;
  30890. this._cachedTextureMatrix[12] = this.uOffset;
  30891. this._cachedTextureMatrix[13] = this.vOffset;
  30892. break;
  30893. case Texture.PROJECTION_MODE:
  30894. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30895. this._projectionModeMatrix.m[0] = 0.5;
  30896. this._projectionModeMatrix.m[5] = -0.5;
  30897. this._projectionModeMatrix.m[10] = 0.0;
  30898. this._projectionModeMatrix.m[12] = 0.5;
  30899. this._projectionModeMatrix.m[13] = 0.5;
  30900. this._projectionModeMatrix.m[14] = 1.0;
  30901. this._projectionModeMatrix.m[15] = 1.0;
  30902. var projectionMatrix = scene.getProjectionMatrix();
  30903. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30904. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30905. break;
  30906. default:
  30907. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30908. break;
  30909. }
  30910. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30911. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30912. });
  30913. return this._cachedTextureMatrix;
  30914. };
  30915. Texture.prototype.clone = function () {
  30916. var _this = this;
  30917. return BABYLON.SerializationHelper.Clone(function () {
  30918. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30919. }, this);
  30920. };
  30921. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30922. get: function () {
  30923. if (!this._onLoadObservable) {
  30924. this._onLoadObservable = new BABYLON.Observable();
  30925. }
  30926. return this._onLoadObservable;
  30927. },
  30928. enumerable: true,
  30929. configurable: true
  30930. });
  30931. Texture.prototype.serialize = function () {
  30932. var serializationObject = _super.prototype.serialize.call(this);
  30933. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30934. serializationObject.base64String = this._buffer;
  30935. serializationObject.name = serializationObject.name.replace("data:", "");
  30936. }
  30937. serializationObject.invertY = this._invertY;
  30938. serializationObject.samplingMode = this.samplingMode;
  30939. return serializationObject;
  30940. };
  30941. Texture.prototype.getClassName = function () {
  30942. return "Texture";
  30943. };
  30944. Texture.prototype.dispose = function () {
  30945. _super.prototype.dispose.call(this);
  30946. if (this._onLoadObservable) {
  30947. this._onLoadObservable.clear();
  30948. this._onLoadObservable = null;
  30949. }
  30950. this._delayedOnLoad = null;
  30951. this._delayedOnError = null;
  30952. };
  30953. // Statics
  30954. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30955. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30956. if (onLoad === void 0) { onLoad = null; }
  30957. if (onError === void 0) { onError = null; }
  30958. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30959. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30960. };
  30961. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30962. if (parsedTexture.customType) {
  30963. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30964. // Update Sampling Mode
  30965. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30966. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30967. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30968. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30969. }
  30970. }
  30971. return parsedCustomTexture;
  30972. }
  30973. if (parsedTexture.isCube) {
  30974. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30975. }
  30976. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30977. return null;
  30978. }
  30979. var texture = BABYLON.SerializationHelper.Parse(function () {
  30980. var generateMipMaps = true;
  30981. if (parsedTexture.noMipmap) {
  30982. generateMipMaps = false;
  30983. }
  30984. if (parsedTexture.mirrorPlane) {
  30985. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30986. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30987. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30988. return mirrorTexture;
  30989. }
  30990. else if (parsedTexture.isRenderTarget) {
  30991. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30992. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30993. return renderTargetTexture;
  30994. }
  30995. else {
  30996. var texture;
  30997. if (parsedTexture.base64String) {
  30998. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30999. }
  31000. else {
  31001. var url = rootUrl + parsedTexture.name;
  31002. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31003. url = parsedTexture.url;
  31004. }
  31005. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31006. }
  31007. return texture;
  31008. }
  31009. }, parsedTexture, scene);
  31010. // Update Sampling Mode
  31011. if (parsedTexture.samplingMode) {
  31012. var sampling = parsedTexture.samplingMode;
  31013. if (texture._samplingMode !== sampling) {
  31014. texture.updateSamplingMode(sampling);
  31015. }
  31016. }
  31017. // Animations
  31018. if (parsedTexture.animations) {
  31019. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31020. var parsedAnimation = parsedTexture.animations[animationIndex];
  31021. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31022. }
  31023. }
  31024. return texture;
  31025. };
  31026. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31027. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31028. if (noMipmap === void 0) { noMipmap = false; }
  31029. if (invertY === void 0) { invertY = true; }
  31030. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31031. if (onLoad === void 0) { onLoad = null; }
  31032. if (onError === void 0) { onError = null; }
  31033. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31034. if (name.substr(0, 5) !== "data:") {
  31035. name = "data:" + name;
  31036. }
  31037. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31038. };
  31039. // Constants
  31040. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  31041. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  31042. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  31043. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  31044. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  31045. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  31046. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  31047. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  31048. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  31049. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  31050. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  31051. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  31052. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  31053. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  31054. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  31055. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  31056. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  31057. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  31058. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  31059. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  31060. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  31061. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  31062. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  31063. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  31064. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  31065. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  31066. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  31067. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  31068. /**
  31069. * 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
  31070. */
  31071. Texture.UseSerializedUrlIfAny = false;
  31072. __decorate([
  31073. BABYLON.serialize()
  31074. ], Texture.prototype, "url", void 0);
  31075. __decorate([
  31076. BABYLON.serialize()
  31077. ], Texture.prototype, "uOffset", void 0);
  31078. __decorate([
  31079. BABYLON.serialize()
  31080. ], Texture.prototype, "vOffset", void 0);
  31081. __decorate([
  31082. BABYLON.serialize()
  31083. ], Texture.prototype, "uScale", void 0);
  31084. __decorate([
  31085. BABYLON.serialize()
  31086. ], Texture.prototype, "vScale", void 0);
  31087. __decorate([
  31088. BABYLON.serialize()
  31089. ], Texture.prototype, "uAng", void 0);
  31090. __decorate([
  31091. BABYLON.serialize()
  31092. ], Texture.prototype, "vAng", void 0);
  31093. __decorate([
  31094. BABYLON.serialize()
  31095. ], Texture.prototype, "wAng", void 0);
  31096. __decorate([
  31097. BABYLON.serialize()
  31098. ], Texture.prototype, "uRotationCenter", void 0);
  31099. __decorate([
  31100. BABYLON.serialize()
  31101. ], Texture.prototype, "vRotationCenter", void 0);
  31102. __decorate([
  31103. BABYLON.serialize()
  31104. ], Texture.prototype, "wRotationCenter", void 0);
  31105. __decorate([
  31106. BABYLON.serialize()
  31107. ], Texture.prototype, "isBlocking", null);
  31108. return Texture;
  31109. }(BABYLON.BaseTexture));
  31110. BABYLON.Texture = Texture;
  31111. })(BABYLON || (BABYLON = {}));
  31112. //# sourceMappingURL=babylon.texture.js.map
  31113. var BABYLON;
  31114. (function (BABYLON) {
  31115. /**
  31116. * @hidden
  31117. **/
  31118. var _InstancesBatch = /** @class */ (function () {
  31119. function _InstancesBatch() {
  31120. this.mustReturn = false;
  31121. this.visibleInstances = new Array();
  31122. this.renderSelf = new Array();
  31123. }
  31124. return _InstancesBatch;
  31125. }());
  31126. BABYLON._InstancesBatch = _InstancesBatch;
  31127. var Mesh = /** @class */ (function (_super) {
  31128. __extends(Mesh, _super);
  31129. /**
  31130. * @constructor
  31131. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  31132. * @param {Scene} scene The scene to add this mesh to.
  31133. * @param {Node} parent The parent of this mesh, if it has one
  31134. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  31135. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31136. * When false, achieved by calling a clone(), also passing False.
  31137. * This will make creation of children, recursive.
  31138. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31139. */
  31140. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31141. if (scene === void 0) { scene = null; }
  31142. if (parent === void 0) { parent = null; }
  31143. if (source === void 0) { source = null; }
  31144. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31145. var _this = _super.call(this, name, scene) || this;
  31146. // Members
  31147. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31148. _this.instances = new Array();
  31149. _this._LODLevels = new Array();
  31150. /** @hidden */
  31151. _this._visibleInstances = {};
  31152. _this._renderIdForInstances = new Array();
  31153. _this._batchCache = new _InstancesBatch();
  31154. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31155. // Use by builder only to know what orientation were the mesh build in.
  31156. /** @hidden */
  31157. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  31158. _this.overrideMaterialSideOrientation = null;
  31159. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31160. // Will be used to save a source mesh reference, If any
  31161. _this._source = null;
  31162. scene = _this.getScene();
  31163. if (source) {
  31164. // Geometry
  31165. if (source._geometry) {
  31166. source._geometry.applyToMesh(_this);
  31167. }
  31168. // Deep copy
  31169. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31170. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  31171. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw"
  31172. ], ["_poseMatrix"]);
  31173. // Source mesh
  31174. _this._source = source;
  31175. // Construction Params
  31176. // Clone parameters allowing mesh to be updated in case of parametric shapes.
  31177. _this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
  31178. var myAnyThis = _this;
  31179. var myAnySource = source;
  31180. myAnyThis._closePath = myAnySource._closePath;
  31181. myAnyThis._idx = myAnySource._idx;
  31182. myAnyThis.dashSize = myAnySource.dashSize;
  31183. myAnyThis.gapSize = myAnySource.gapSize;
  31184. myAnyThis.path3D = myAnySource.path3D;
  31185. myAnyThis.pathArray = myAnySource.pathArray;
  31186. myAnyThis.arc = myAnySource.arc;
  31187. myAnyThis.radius = myAnySource.radius;
  31188. // Animation ranges
  31189. if (_this._source._ranges) {
  31190. var ranges = _this._source._ranges;
  31191. for (var name in ranges) {
  31192. if (!ranges.hasOwnProperty(name)) {
  31193. continue;
  31194. }
  31195. if (!ranges[name]) {
  31196. continue;
  31197. }
  31198. _this.createAnimationRange(name, ranges[name].from, ranges[name].to);
  31199. }
  31200. }
  31201. // Metadata
  31202. if (source.metadata && source.metadata.clone) {
  31203. _this.metadata = source.metadata.clone();
  31204. }
  31205. else {
  31206. _this.metadata = source.metadata;
  31207. }
  31208. // Tags
  31209. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31210. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31211. }
  31212. // Parent
  31213. _this.parent = source.parent;
  31214. // Pivot
  31215. _this.setPivotMatrix(source.getPivotMatrix());
  31216. _this.id = name + "." + source.id;
  31217. // Material
  31218. _this.material = source.material;
  31219. var index;
  31220. if (!doNotCloneChildren) {
  31221. // Children
  31222. var directDescendants = source.getDescendants(true);
  31223. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31224. var child = directDescendants[index_1];
  31225. if (child.clone) {
  31226. child.clone(name + "." + child.name, _this);
  31227. }
  31228. }
  31229. }
  31230. // Physics clone
  31231. var physicsEngine = _this.getScene().getPhysicsEngine();
  31232. if (clonePhysicsImpostor && physicsEngine) {
  31233. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31234. if (impostor) {
  31235. _this.physicsImpostor = impostor.clone(_this);
  31236. }
  31237. }
  31238. // Particles
  31239. for (index = 0; index < scene.particleSystems.length; index++) {
  31240. var system = scene.particleSystems[index];
  31241. if (system.emitter === source) {
  31242. system.clone(system.name, _this);
  31243. }
  31244. }
  31245. _this.refreshBoundingInfo();
  31246. _this.computeWorldMatrix(true);
  31247. }
  31248. // Parent
  31249. if (parent !== null) {
  31250. _this.parent = parent;
  31251. }
  31252. return _this;
  31253. }
  31254. Object.defineProperty(Mesh, "FRONTSIDE", {
  31255. /**
  31256. * Mesh side orientation : usually the external or front surface
  31257. */
  31258. get: function () {
  31259. return Mesh._FRONTSIDE;
  31260. },
  31261. enumerable: true,
  31262. configurable: true
  31263. });
  31264. Object.defineProperty(Mesh, "BACKSIDE", {
  31265. /**
  31266. * Mesh side orientation : usually the internal or back surface
  31267. */
  31268. get: function () {
  31269. return Mesh._BACKSIDE;
  31270. },
  31271. enumerable: true,
  31272. configurable: true
  31273. });
  31274. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31275. /**
  31276. * Mesh side orientation : both internal and external or front and back surfaces
  31277. */
  31278. get: function () {
  31279. return Mesh._DOUBLESIDE;
  31280. },
  31281. enumerable: true,
  31282. configurable: true
  31283. });
  31284. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31285. /**
  31286. * Mesh side orientation : by default, `FRONTSIDE`
  31287. */
  31288. get: function () {
  31289. return Mesh._DEFAULTSIDE;
  31290. },
  31291. enumerable: true,
  31292. configurable: true
  31293. });
  31294. Object.defineProperty(Mesh, "NO_CAP", {
  31295. /**
  31296. * Mesh cap setting : no cap
  31297. */
  31298. get: function () {
  31299. return Mesh._NO_CAP;
  31300. },
  31301. enumerable: true,
  31302. configurable: true
  31303. });
  31304. Object.defineProperty(Mesh, "CAP_START", {
  31305. /**
  31306. * Mesh cap setting : one cap at the beginning of the mesh
  31307. */
  31308. get: function () {
  31309. return Mesh._CAP_START;
  31310. },
  31311. enumerable: true,
  31312. configurable: true
  31313. });
  31314. Object.defineProperty(Mesh, "CAP_END", {
  31315. /**
  31316. * Mesh cap setting : one cap at the end of the mesh
  31317. */
  31318. get: function () {
  31319. return Mesh._CAP_END;
  31320. },
  31321. enumerable: true,
  31322. configurable: true
  31323. });
  31324. Object.defineProperty(Mesh, "CAP_ALL", {
  31325. /**
  31326. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31327. */
  31328. get: function () {
  31329. return Mesh._CAP_ALL;
  31330. },
  31331. enumerable: true,
  31332. configurable: true
  31333. });
  31334. Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
  31335. /**
  31336. * An event triggered before rendering the mesh
  31337. */
  31338. get: function () {
  31339. if (!this._onBeforeRenderObservable) {
  31340. this._onBeforeRenderObservable = new BABYLON.Observable();
  31341. }
  31342. return this._onBeforeRenderObservable;
  31343. },
  31344. enumerable: true,
  31345. configurable: true
  31346. });
  31347. Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
  31348. /**
  31349. * An event triggered after rendering the mesh
  31350. */
  31351. get: function () {
  31352. if (!this._onAfterRenderObservable) {
  31353. this._onAfterRenderObservable = new BABYLON.Observable();
  31354. }
  31355. return this._onAfterRenderObservable;
  31356. },
  31357. enumerable: true,
  31358. configurable: true
  31359. });
  31360. Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
  31361. /**
  31362. * An event triggered before drawing the mesh
  31363. */
  31364. get: function () {
  31365. if (!this._onBeforeDrawObservable) {
  31366. this._onBeforeDrawObservable = new BABYLON.Observable();
  31367. }
  31368. return this._onBeforeDrawObservable;
  31369. },
  31370. enumerable: true,
  31371. configurable: true
  31372. });
  31373. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31374. set: function (callback) {
  31375. if (this._onBeforeDrawObserver) {
  31376. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31377. }
  31378. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31379. },
  31380. enumerable: true,
  31381. configurable: true
  31382. });
  31383. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31384. get: function () {
  31385. return this._morphTargetManager;
  31386. },
  31387. set: function (value) {
  31388. if (this._morphTargetManager === value) {
  31389. return;
  31390. }
  31391. this._morphTargetManager = value;
  31392. this._syncGeometryWithMorphTargetManager();
  31393. },
  31394. enumerable: true,
  31395. configurable: true
  31396. });
  31397. Object.defineProperty(Mesh.prototype, "source", {
  31398. get: function () {
  31399. return this._source;
  31400. },
  31401. enumerable: true,
  31402. configurable: true
  31403. });
  31404. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31405. get: function () {
  31406. return this._unIndexed;
  31407. },
  31408. set: function (value) {
  31409. if (this._unIndexed !== value) {
  31410. this._unIndexed = value;
  31411. this._markSubMeshesAsAttributesDirty();
  31412. }
  31413. },
  31414. enumerable: true,
  31415. configurable: true
  31416. });
  31417. // Methods
  31418. /**
  31419. * Returns the string "Mesh".
  31420. */
  31421. Mesh.prototype.getClassName = function () {
  31422. return "Mesh";
  31423. };
  31424. /**
  31425. * Returns a string.
  31426. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31427. */
  31428. Mesh.prototype.toString = function (fullDetails) {
  31429. var ret = _super.prototype.toString.call(this, fullDetails);
  31430. ret += ", n vertices: " + this.getTotalVertices();
  31431. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31432. if (this.animations) {
  31433. for (var i = 0; i < this.animations.length; i++) {
  31434. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31435. }
  31436. }
  31437. if (fullDetails) {
  31438. if (this._geometry) {
  31439. var ib = this.getIndices();
  31440. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31441. if (vb && ib) {
  31442. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31443. }
  31444. }
  31445. else {
  31446. ret += ", flat shading: UNKNOWN";
  31447. }
  31448. }
  31449. return ret;
  31450. };
  31451. /** @hidden */
  31452. Mesh.prototype._unBindEffect = function () {
  31453. _super.prototype._unBindEffect.call(this);
  31454. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31455. var instance = _a[_i];
  31456. instance._unBindEffect();
  31457. }
  31458. };
  31459. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31460. /**
  31461. * True if the mesh has some Levels Of Details (LOD).
  31462. * Returns a boolean.
  31463. */
  31464. get: function () {
  31465. return this._LODLevels.length > 0;
  31466. },
  31467. enumerable: true,
  31468. configurable: true
  31469. });
  31470. /**
  31471. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31472. * @returns an array of {BABYLON.MeshLODLevel}
  31473. */
  31474. Mesh.prototype.getLODLevels = function () {
  31475. return this._LODLevels;
  31476. };
  31477. Mesh.prototype._sortLODLevels = function () {
  31478. this._LODLevels.sort(function (a, b) {
  31479. if (a.distance < b.distance) {
  31480. return 1;
  31481. }
  31482. if (a.distance > b.distance) {
  31483. return -1;
  31484. }
  31485. return 0;
  31486. });
  31487. };
  31488. /**
  31489. * Add a mesh as LOD level triggered at the given distance.
  31490. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31491. * @param distance The distance from the center of the object to show this level
  31492. * @param mesh The mesh to be added as LOD level (can be null)
  31493. * @return This mesh (for chaining)
  31494. */
  31495. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31496. if (mesh && mesh._masterMesh) {
  31497. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31498. return this;
  31499. }
  31500. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31501. this._LODLevels.push(level);
  31502. if (mesh) {
  31503. mesh._masterMesh = this;
  31504. }
  31505. this._sortLODLevels();
  31506. return this;
  31507. };
  31508. /**
  31509. * Returns the LOD level mesh at the passed distance or null if not found.
  31510. * It is related to the method `addLODLevel(distance, mesh)`.
  31511. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31512. * Returns an object Mesh or `null`.
  31513. */
  31514. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31515. for (var index = 0; index < this._LODLevels.length; index++) {
  31516. var level = this._LODLevels[index];
  31517. if (level.distance === distance) {
  31518. return level.mesh;
  31519. }
  31520. }
  31521. return null;
  31522. };
  31523. /**
  31524. * Remove a mesh from the LOD array
  31525. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31526. * @param {Mesh} mesh The mesh to be removed.
  31527. * @return {Mesh} This mesh (for chaining)
  31528. */
  31529. Mesh.prototype.removeLODLevel = function (mesh) {
  31530. for (var index = 0; index < this._LODLevels.length; index++) {
  31531. if (this._LODLevels[index].mesh === mesh) {
  31532. this._LODLevels.splice(index, 1);
  31533. if (mesh) {
  31534. mesh._masterMesh = null;
  31535. }
  31536. }
  31537. }
  31538. this._sortLODLevels();
  31539. return this;
  31540. };
  31541. /**
  31542. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31543. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31544. */
  31545. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31546. if (!this._LODLevels || this._LODLevels.length === 0) {
  31547. return this;
  31548. }
  31549. var bSphere;
  31550. if (boundingSphere) {
  31551. bSphere = boundingSphere;
  31552. }
  31553. else {
  31554. var boundingInfo = this.getBoundingInfo();
  31555. bSphere = boundingInfo.boundingSphere;
  31556. }
  31557. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31558. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31559. if (this.onLODLevelSelection) {
  31560. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31561. }
  31562. return this;
  31563. }
  31564. for (var index = 0; index < this._LODLevels.length; index++) {
  31565. var level = this._LODLevels[index];
  31566. if (level.distance < distanceToCamera) {
  31567. if (level.mesh) {
  31568. level.mesh._preActivate();
  31569. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31570. }
  31571. if (this.onLODLevelSelection) {
  31572. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31573. }
  31574. return level.mesh;
  31575. }
  31576. }
  31577. if (this.onLODLevelSelection) {
  31578. this.onLODLevelSelection(distanceToCamera, this, this);
  31579. }
  31580. return this;
  31581. };
  31582. Object.defineProperty(Mesh.prototype, "geometry", {
  31583. /**
  31584. * Returns the mesh internal Geometry object.
  31585. */
  31586. get: function () {
  31587. return this._geometry;
  31588. },
  31589. enumerable: true,
  31590. configurable: true
  31591. });
  31592. /**
  31593. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31594. */
  31595. Mesh.prototype.getTotalVertices = function () {
  31596. if (this._geometry === null || this._geometry === undefined) {
  31597. return 0;
  31598. }
  31599. return this._geometry.getTotalVertices();
  31600. };
  31601. /**
  31602. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31603. * 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.
  31604. * You can force the copy with forceCopy === true
  31605. * Returns null if the mesh has no geometry or no vertex buffer.
  31606. * Possible `kind` values :
  31607. * - BABYLON.VertexBuffer.PositionKind
  31608. * - BABYLON.VertexBuffer.UVKind
  31609. * - BABYLON.VertexBuffer.UV2Kind
  31610. * - BABYLON.VertexBuffer.UV3Kind
  31611. * - BABYLON.VertexBuffer.UV4Kind
  31612. * - BABYLON.VertexBuffer.UV5Kind
  31613. * - BABYLON.VertexBuffer.UV6Kind
  31614. * - BABYLON.VertexBuffer.ColorKind
  31615. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31616. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31617. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31618. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31619. */
  31620. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31621. if (!this._geometry) {
  31622. return null;
  31623. }
  31624. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31625. };
  31626. /**
  31627. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31628. * Returns `null` if the mesh has no geometry.
  31629. * Possible `kind` values :
  31630. * - BABYLON.VertexBuffer.PositionKind
  31631. * - BABYLON.VertexBuffer.UVKind
  31632. * - BABYLON.VertexBuffer.UV2Kind
  31633. * - BABYLON.VertexBuffer.UV3Kind
  31634. * - BABYLON.VertexBuffer.UV4Kind
  31635. * - BABYLON.VertexBuffer.UV5Kind
  31636. * - BABYLON.VertexBuffer.UV6Kind
  31637. * - BABYLON.VertexBuffer.ColorKind
  31638. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31639. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31640. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31641. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31642. */
  31643. Mesh.prototype.getVertexBuffer = function (kind) {
  31644. if (!this._geometry) {
  31645. return null;
  31646. }
  31647. return this._geometry.getVertexBuffer(kind);
  31648. };
  31649. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31650. if (!this._geometry) {
  31651. if (this._delayInfo) {
  31652. return this._delayInfo.indexOf(kind) !== -1;
  31653. }
  31654. return false;
  31655. }
  31656. return this._geometry.isVerticesDataPresent(kind);
  31657. };
  31658. /**
  31659. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31660. * Possible `kind` values :
  31661. * - BABYLON.VertexBuffer.PositionKind
  31662. * - BABYLON.VertexBuffer.UVKind
  31663. * - BABYLON.VertexBuffer.UV2Kind
  31664. * - BABYLON.VertexBuffer.UV3Kind
  31665. * - BABYLON.VertexBuffer.UV4Kind
  31666. * - BABYLON.VertexBuffer.UV5Kind
  31667. * - BABYLON.VertexBuffer.UV6Kind
  31668. * - BABYLON.VertexBuffer.ColorKind
  31669. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31670. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31671. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31672. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31673. */
  31674. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31675. if (!this._geometry) {
  31676. if (this._delayInfo) {
  31677. return this._delayInfo.indexOf(kind) !== -1;
  31678. }
  31679. return false;
  31680. }
  31681. return this._geometry.isVertexBufferUpdatable(kind);
  31682. };
  31683. /**
  31684. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31685. * Possible `kind` values :
  31686. * - BABYLON.VertexBuffer.PositionKind
  31687. * - BABYLON.VertexBuffer.UVKind
  31688. * - BABYLON.VertexBuffer.UV2Kind
  31689. * - BABYLON.VertexBuffer.UV3Kind
  31690. * - BABYLON.VertexBuffer.UV4Kind
  31691. * - BABYLON.VertexBuffer.UV5Kind
  31692. * - BABYLON.VertexBuffer.UV6Kind
  31693. * - BABYLON.VertexBuffer.ColorKind
  31694. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31695. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31696. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31697. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31698. */
  31699. Mesh.prototype.getVerticesDataKinds = function () {
  31700. if (!this._geometry) {
  31701. var result = new Array();
  31702. if (this._delayInfo) {
  31703. this._delayInfo.forEach(function (kind, index, array) {
  31704. result.push(kind);
  31705. });
  31706. }
  31707. return result;
  31708. }
  31709. return this._geometry.getVerticesDataKinds();
  31710. };
  31711. /**
  31712. * Returns a positive integer : the total number of indices in this mesh geometry.
  31713. * Returns zero if the mesh has no geometry.
  31714. */
  31715. Mesh.prototype.getTotalIndices = function () {
  31716. if (!this._geometry) {
  31717. return 0;
  31718. }
  31719. return this._geometry.getTotalIndices();
  31720. };
  31721. /**
  31722. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31723. * @param copyWhenShared If true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  31724. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  31725. * @returns the indices array or an empty array if the mesh has no geometry
  31726. */
  31727. Mesh.prototype.getIndices = function (copyWhenShared, forceCopy) {
  31728. if (!this._geometry) {
  31729. return [];
  31730. }
  31731. return this._geometry.getIndices(copyWhenShared, forceCopy);
  31732. };
  31733. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31734. get: function () {
  31735. return this._masterMesh !== null && this._masterMesh !== undefined;
  31736. },
  31737. enumerable: true,
  31738. configurable: true
  31739. });
  31740. /**
  31741. * Determine if the current mesh is ready to be rendered
  31742. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31743. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31744. * @returns true if all associated assets are ready (material, textures, shaders)
  31745. */
  31746. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31747. if (completeCheck === void 0) { completeCheck = false; }
  31748. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31749. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31750. return false;
  31751. }
  31752. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31753. return false;
  31754. }
  31755. if (!this.subMeshes || this.subMeshes.length === 0) {
  31756. return true;
  31757. }
  31758. if (!completeCheck) {
  31759. return true;
  31760. }
  31761. var engine = this.getEngine();
  31762. var scene = this.getScene();
  31763. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31764. this.computeWorldMatrix();
  31765. var mat = this.material || scene.defaultMaterial;
  31766. if (mat) {
  31767. if (mat.storeEffectOnSubMeshes) {
  31768. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31769. var subMesh = _a[_i];
  31770. var effectiveMaterial = subMesh.getMaterial();
  31771. if (effectiveMaterial) {
  31772. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31773. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31774. return false;
  31775. }
  31776. }
  31777. else {
  31778. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31779. return false;
  31780. }
  31781. }
  31782. }
  31783. }
  31784. }
  31785. else {
  31786. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31787. return false;
  31788. }
  31789. }
  31790. }
  31791. // Shadows
  31792. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31793. var light = _c[_b];
  31794. var generator = light.getShadowGenerator();
  31795. if (generator) {
  31796. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31797. var subMesh = _e[_d];
  31798. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31799. return false;
  31800. }
  31801. }
  31802. }
  31803. }
  31804. // LOD
  31805. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31806. var lod = _g[_f];
  31807. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31808. return false;
  31809. }
  31810. }
  31811. return true;
  31812. };
  31813. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31814. /**
  31815. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31816. * This property is pertinent only for updatable parametric shapes.
  31817. */
  31818. get: function () {
  31819. return this._areNormalsFrozen;
  31820. },
  31821. enumerable: true,
  31822. configurable: true
  31823. });
  31824. /**
  31825. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31826. * It has no effect at all on other shapes.
  31827. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31828. * Returns the Mesh.
  31829. */
  31830. Mesh.prototype.freezeNormals = function () {
  31831. this._areNormalsFrozen = true;
  31832. return this;
  31833. };
  31834. /**
  31835. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31836. * It has no effect at all on other shapes.
  31837. * It reactivates the mesh normals computation if it was previously frozen.
  31838. * Returns the Mesh.
  31839. */
  31840. Mesh.prototype.unfreezeNormals = function () {
  31841. this._areNormalsFrozen = false;
  31842. return this;
  31843. };
  31844. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31845. /**
  31846. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31847. */
  31848. set: function (count) {
  31849. this._overridenInstanceCount = count;
  31850. },
  31851. enumerable: true,
  31852. configurable: true
  31853. });
  31854. // Methods
  31855. /** @hidden */
  31856. Mesh.prototype._preActivate = function () {
  31857. var sceneRenderId = this.getScene().getRenderId();
  31858. if (this._preActivateId === sceneRenderId) {
  31859. return this;
  31860. }
  31861. this._preActivateId = sceneRenderId;
  31862. this._visibleInstances = null;
  31863. return this;
  31864. };
  31865. /** @hidden */
  31866. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31867. if (this._visibleInstances) {
  31868. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31869. }
  31870. return this;
  31871. };
  31872. /** @hidden */
  31873. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31874. if (!this._visibleInstances) {
  31875. this._visibleInstances = {};
  31876. this._visibleInstances.defaultRenderId = renderId;
  31877. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31878. }
  31879. if (!this._visibleInstances[renderId]) {
  31880. this._visibleInstances[renderId] = new Array();
  31881. }
  31882. this._visibleInstances[renderId].push(instance);
  31883. return this;
  31884. };
  31885. /**
  31886. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31887. * This means the mesh underlying bounding box and sphere are recomputed.
  31888. * Returns the Mesh.
  31889. */
  31890. Mesh.prototype.refreshBoundingInfo = function () {
  31891. return this._refreshBoundingInfo(false);
  31892. };
  31893. /** @hidden */
  31894. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31895. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31896. return this;
  31897. }
  31898. var data = this._getPositionData(applySkeleton);
  31899. if (data) {
  31900. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31901. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31902. }
  31903. if (this.subMeshes) {
  31904. for (var index = 0; index < this.subMeshes.length; index++) {
  31905. this.subMeshes[index].refreshBoundingInfo();
  31906. }
  31907. }
  31908. this._updateBoundingInfo();
  31909. return this;
  31910. };
  31911. Mesh.prototype._getPositionData = function (applySkeleton) {
  31912. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31913. if (data && applySkeleton && this.skeleton) {
  31914. data = BABYLON.Tools.Slice(data);
  31915. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31916. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31917. if (matricesWeightsData && matricesIndicesData) {
  31918. var needExtras = this.numBoneInfluencers > 4;
  31919. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31920. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31921. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31922. var tempVector = BABYLON.Tmp.Vector3[0];
  31923. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31924. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31925. var matWeightIdx = 0;
  31926. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31927. finalMatrix.reset();
  31928. var inf;
  31929. var weight;
  31930. for (inf = 0; inf < 4; inf++) {
  31931. weight = matricesWeightsData[matWeightIdx + inf];
  31932. if (weight > 0) {
  31933. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31934. finalMatrix.addToSelf(tempMatrix);
  31935. }
  31936. }
  31937. if (needExtras) {
  31938. for (inf = 0; inf < 4; inf++) {
  31939. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31940. if (weight > 0) {
  31941. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31942. finalMatrix.addToSelf(tempMatrix);
  31943. }
  31944. }
  31945. }
  31946. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31947. tempVector.toArray(data, index);
  31948. }
  31949. }
  31950. }
  31951. return data;
  31952. };
  31953. /** @hidden */
  31954. Mesh.prototype._createGlobalSubMesh = function (force) {
  31955. var totalVertices = this.getTotalVertices();
  31956. if (!totalVertices || !this.getIndices()) {
  31957. return null;
  31958. }
  31959. // Check if we need to recreate the submeshes
  31960. if (this.subMeshes && this.subMeshes.length > 0) {
  31961. var ib = this.getIndices();
  31962. if (!ib) {
  31963. return null;
  31964. }
  31965. var totalIndices = ib.length;
  31966. var needToRecreate = false;
  31967. if (force) {
  31968. needToRecreate = true;
  31969. }
  31970. else {
  31971. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31972. var submesh = _a[_i];
  31973. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31974. needToRecreate = true;
  31975. break;
  31976. }
  31977. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31978. needToRecreate = true;
  31979. break;
  31980. }
  31981. }
  31982. }
  31983. if (!needToRecreate) {
  31984. return this.subMeshes[0];
  31985. }
  31986. }
  31987. this.releaseSubMeshes();
  31988. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31989. };
  31990. Mesh.prototype.subdivide = function (count) {
  31991. if (count < 1) {
  31992. return;
  31993. }
  31994. var totalIndices = this.getTotalIndices();
  31995. var subdivisionSize = (totalIndices / count) | 0;
  31996. var offset = 0;
  31997. // Ensure that subdivisionSize is a multiple of 3
  31998. while (subdivisionSize % 3 !== 0) {
  31999. subdivisionSize++;
  32000. }
  32001. this.releaseSubMeshes();
  32002. for (var index = 0; index < count; index++) {
  32003. if (offset >= totalIndices) {
  32004. break;
  32005. }
  32006. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  32007. offset += subdivisionSize;
  32008. }
  32009. this.synchronizeInstances();
  32010. };
  32011. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32012. if (updatable === void 0) { updatable = false; }
  32013. if (!this._geometry) {
  32014. var vertexData = new BABYLON.VertexData();
  32015. vertexData.set(data, kind);
  32016. var scene = this.getScene();
  32017. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32018. }
  32019. else {
  32020. this._geometry.setVerticesData(kind, data, updatable, stride);
  32021. }
  32022. return this;
  32023. };
  32024. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  32025. if (updatable === void 0) { updatable = true; }
  32026. var vb = this.getVertexBuffer(kind);
  32027. if (!vb || vb.isUpdatable() === updatable) {
  32028. return;
  32029. }
  32030. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  32031. };
  32032. /**
  32033. * Sets the mesh VertexBuffer.
  32034. * Returns the Mesh.
  32035. */
  32036. Mesh.prototype.setVerticesBuffer = function (buffer) {
  32037. if (!this._geometry) {
  32038. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  32039. }
  32040. this._geometry.setVerticesBuffer(buffer);
  32041. return this;
  32042. };
  32043. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  32044. if (!this._geometry) {
  32045. return this;
  32046. }
  32047. if (!makeItUnique) {
  32048. this._geometry.updateVerticesData(kind, data, updateExtends);
  32049. }
  32050. else {
  32051. this.makeGeometryUnique();
  32052. this.updateVerticesData(kind, data, updateExtends, false);
  32053. }
  32054. return this;
  32055. };
  32056. /**
  32057. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  32058. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  32059. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  32060. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  32061. * Returns the Mesh.
  32062. */
  32063. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  32064. if (computeNormals === void 0) { computeNormals = true; }
  32065. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32066. if (!positions) {
  32067. return this;
  32068. }
  32069. positionFunction(positions);
  32070. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  32071. if (computeNormals) {
  32072. var indices = this.getIndices();
  32073. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32074. if (!normals) {
  32075. return this;
  32076. }
  32077. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  32078. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  32079. }
  32080. return this;
  32081. };
  32082. /**
  32083. * Creates a un-shared specific occurence of the geometry for the mesh.
  32084. * Returns the Mesh.
  32085. */
  32086. Mesh.prototype.makeGeometryUnique = function () {
  32087. if (!this._geometry) {
  32088. return this;
  32089. }
  32090. var oldGeometry = this._geometry;
  32091. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  32092. oldGeometry.releaseForMesh(this, true);
  32093. geometry.applyToMesh(this);
  32094. return this;
  32095. };
  32096. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  32097. if (totalVertices === void 0) { totalVertices = null; }
  32098. if (updatable === void 0) { updatable = false; }
  32099. if (!this._geometry) {
  32100. var vertexData = new BABYLON.VertexData();
  32101. vertexData.indices = indices;
  32102. var scene = this.getScene();
  32103. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32104. }
  32105. else {
  32106. this._geometry.setIndices(indices, totalVertices, updatable);
  32107. }
  32108. return this;
  32109. };
  32110. /**
  32111. * Update the current index buffer
  32112. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  32113. * Returns the Mesh.
  32114. */
  32115. Mesh.prototype.updateIndices = function (indices, offset) {
  32116. if (!this._geometry) {
  32117. return this;
  32118. }
  32119. this._geometry.updateIndices(indices, offset);
  32120. return this;
  32121. };
  32122. /**
  32123. * Invert the geometry to move from a right handed system to a left handed one.
  32124. * Returns the Mesh.
  32125. */
  32126. Mesh.prototype.toLeftHanded = function () {
  32127. if (!this._geometry) {
  32128. return this;
  32129. }
  32130. this._geometry.toLeftHanded();
  32131. return this;
  32132. };
  32133. /** @hidden */
  32134. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32135. if (!this._geometry) {
  32136. return this;
  32137. }
  32138. var engine = this.getScene().getEngine();
  32139. // Wireframe
  32140. var indexToBind;
  32141. if (this._unIndexed) {
  32142. indexToBind = null;
  32143. }
  32144. else {
  32145. switch (fillMode) {
  32146. case BABYLON.Material.PointFillMode:
  32147. indexToBind = null;
  32148. break;
  32149. case BABYLON.Material.WireFrameFillMode:
  32150. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  32151. break;
  32152. default:
  32153. case BABYLON.Material.TriangleFillMode:
  32154. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32155. break;
  32156. }
  32157. }
  32158. // VBOs
  32159. this._geometry._bind(effect, indexToBind);
  32160. return this;
  32161. };
  32162. /** @hidden */
  32163. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32164. if (alternate === void 0) { alternate = false; }
  32165. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32166. return this;
  32167. }
  32168. if (this._onBeforeDrawObservable) {
  32169. this._onBeforeDrawObservable.notifyObservers(this);
  32170. }
  32171. var scene = this.getScene();
  32172. var engine = scene.getEngine();
  32173. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32174. // or triangles as points
  32175. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32176. }
  32177. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32178. // Triangles as wireframe
  32179. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32180. }
  32181. else {
  32182. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32183. }
  32184. if (scene._isAlternateRenderingEnabled && !alternate) {
  32185. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32186. if (!effect || !scene.activeCamera) {
  32187. return this;
  32188. }
  32189. scene._switchToAlternateCameraConfiguration(true);
  32190. this._effectiveMaterial.bindView(effect);
  32191. this._effectiveMaterial.bindViewProjection(effect);
  32192. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32193. this._draw(subMesh, fillMode, instancesCount, true);
  32194. engine.setViewport(scene.activeCamera.viewport);
  32195. scene._switchToAlternateCameraConfiguration(false);
  32196. this._effectiveMaterial.bindView(effect);
  32197. this._effectiveMaterial.bindViewProjection(effect);
  32198. }
  32199. return this;
  32200. };
  32201. /**
  32202. * Registers for this mesh a javascript function called just before the rendering process.
  32203. * This function is passed the current mesh.
  32204. * Return the Mesh.
  32205. */
  32206. Mesh.prototype.registerBeforeRender = function (func) {
  32207. this.onBeforeRenderObservable.add(func);
  32208. return this;
  32209. };
  32210. /**
  32211. * Disposes a previously registered javascript function called before the rendering.
  32212. * This function is passed the current mesh.
  32213. * Returns the Mesh.
  32214. */
  32215. Mesh.prototype.unregisterBeforeRender = function (func) {
  32216. this.onBeforeRenderObservable.removeCallback(func);
  32217. return this;
  32218. };
  32219. /**
  32220. * Registers for this mesh a javascript function called just after the rendering is complete.
  32221. * This function is passed the current mesh.
  32222. * Returns the Mesh.
  32223. */
  32224. Mesh.prototype.registerAfterRender = function (func) {
  32225. this.onAfterRenderObservable.add(func);
  32226. return this;
  32227. };
  32228. /**
  32229. * Disposes a previously registered javascript function called after the rendering.
  32230. * This function is passed the current mesh.
  32231. * Return the Mesh.
  32232. */
  32233. Mesh.prototype.unregisterAfterRender = function (func) {
  32234. this.onAfterRenderObservable.removeCallback(func);
  32235. return this;
  32236. };
  32237. /** @hidden */
  32238. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32239. var scene = this.getScene();
  32240. this._batchCache.mustReturn = false;
  32241. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32242. this._batchCache.visibleInstances[subMeshId] = null;
  32243. if (this._visibleInstances) {
  32244. var currentRenderId = scene.getRenderId();
  32245. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32246. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32247. var selfRenderId = this._renderId;
  32248. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32249. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32250. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32251. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32252. }
  32253. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32254. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32255. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32256. this._batchCache.mustReturn = true;
  32257. return this._batchCache;
  32258. }
  32259. if (currentRenderId !== selfRenderId) {
  32260. this._batchCache.renderSelf[subMeshId] = false;
  32261. }
  32262. }
  32263. this._renderIdForInstances[subMeshId] = currentRenderId;
  32264. }
  32265. return this._batchCache;
  32266. };
  32267. /** @hidden */
  32268. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32269. var visibleInstances = batch.visibleInstances[subMesh._id];
  32270. if (!visibleInstances) {
  32271. return this;
  32272. }
  32273. var matricesCount = visibleInstances.length + 1;
  32274. var bufferSize = matricesCount * 16 * 4;
  32275. var currentInstancesBufferSize = this._instancesBufferSize;
  32276. var instancesBuffer = this._instancesBuffer;
  32277. while (this._instancesBufferSize < bufferSize) {
  32278. this._instancesBufferSize *= 2;
  32279. }
  32280. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32281. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32282. }
  32283. var offset = 0;
  32284. var instancesCount = 0;
  32285. var world = this.getWorldMatrix();
  32286. if (batch.renderSelf[subMesh._id]) {
  32287. world.copyToArray(this._instancesData, offset);
  32288. offset += 16;
  32289. instancesCount++;
  32290. }
  32291. if (visibleInstances) {
  32292. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32293. var instance = visibleInstances[instanceIndex];
  32294. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32295. offset += 16;
  32296. instancesCount++;
  32297. }
  32298. }
  32299. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32300. if (instancesBuffer) {
  32301. instancesBuffer.dispose();
  32302. }
  32303. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32304. this._instancesBuffer = instancesBuffer;
  32305. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32306. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32307. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32308. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32309. }
  32310. else {
  32311. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32312. }
  32313. this._bind(subMesh, effect, fillMode);
  32314. this._draw(subMesh, fillMode, instancesCount);
  32315. engine.unbindInstanceAttributes();
  32316. return this;
  32317. };
  32318. /** @hidden */
  32319. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32320. var scene = this.getScene();
  32321. var engine = scene.getEngine();
  32322. if (hardwareInstancedRendering) {
  32323. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32324. }
  32325. else {
  32326. if (batch.renderSelf[subMesh._id]) {
  32327. // Draw
  32328. if (onBeforeDraw) {
  32329. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32330. }
  32331. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32332. }
  32333. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32334. if (visibleInstancesForSubMesh) {
  32335. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32336. var instance = visibleInstancesForSubMesh[instanceIndex];
  32337. // World
  32338. var world = instance.getWorldMatrix();
  32339. if (onBeforeDraw) {
  32340. onBeforeDraw(true, world, effectiveMaterial);
  32341. }
  32342. // Draw
  32343. this._draw(subMesh, fillMode);
  32344. }
  32345. }
  32346. }
  32347. return this;
  32348. };
  32349. /**
  32350. * Triggers the draw call for the mesh. Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager
  32351. * @param subMesh defines the subMesh to render
  32352. * @param enableAlphaMode defines if alpha mode can be changed
  32353. * @returns the current mesh
  32354. */
  32355. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32356. this._checkOcclusionQuery();
  32357. if (this._isOccluded) {
  32358. return this;
  32359. }
  32360. var scene = this.getScene();
  32361. // Managing instances
  32362. var batch = this._getInstancesRenderList(subMesh._id);
  32363. if (batch.mustReturn) {
  32364. return this;
  32365. }
  32366. // Checking geometry state
  32367. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32368. return this;
  32369. }
  32370. if (this._onBeforeRenderObservable) {
  32371. this._onBeforeRenderObservable.notifyObservers(this);
  32372. }
  32373. var engine = scene.getEngine();
  32374. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32375. // Material
  32376. var material = subMesh.getMaterial();
  32377. if (!material) {
  32378. return this;
  32379. }
  32380. this._effectiveMaterial = material;
  32381. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32382. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32383. return this;
  32384. }
  32385. }
  32386. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32387. return this;
  32388. }
  32389. // Alpha mode
  32390. if (enableAlphaMode) {
  32391. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32392. }
  32393. // Outline - step 1
  32394. var savedDepthWrite = engine.getDepthWrite();
  32395. if (this.renderOutline) {
  32396. engine.setDepthWrite(false);
  32397. scene.getOutlineRenderer().render(subMesh, batch);
  32398. engine.setDepthWrite(savedDepthWrite);
  32399. }
  32400. var effect;
  32401. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32402. effect = subMesh.effect;
  32403. }
  32404. else {
  32405. effect = this._effectiveMaterial.getEffect();
  32406. }
  32407. if (!effect) {
  32408. return this;
  32409. }
  32410. var sideOrientation = this.overrideMaterialSideOrientation;
  32411. if (sideOrientation == null) {
  32412. sideOrientation = this._effectiveMaterial.sideOrientation;
  32413. if (this._getWorldMatrixDeterminant() < 0) {
  32414. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32415. }
  32416. }
  32417. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32418. if (this._effectiveMaterial.forceDepthWrite) {
  32419. engine.setDepthWrite(true);
  32420. }
  32421. // Bind
  32422. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32423. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32424. this._bind(subMesh, effect, fillMode);
  32425. }
  32426. var world = this.getWorldMatrix();
  32427. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32428. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32429. }
  32430. else {
  32431. this._effectiveMaterial.bind(world, this);
  32432. }
  32433. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32434. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32435. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32436. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32437. }
  32438. // Draw
  32439. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32440. // Unbind
  32441. this._effectiveMaterial.unbind();
  32442. // Outline - step 2
  32443. if (this.renderOutline && savedDepthWrite) {
  32444. engine.setDepthWrite(true);
  32445. engine.setColorWrite(false);
  32446. scene.getOutlineRenderer().render(subMesh, batch);
  32447. engine.setColorWrite(true);
  32448. }
  32449. // Overlay
  32450. if (this.renderOverlay) {
  32451. var currentMode = engine.getAlphaMode();
  32452. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32453. scene.getOutlineRenderer().render(subMesh, batch, true);
  32454. engine.setAlphaMode(currentMode);
  32455. }
  32456. if (this._onAfterRenderObservable) {
  32457. this._onAfterRenderObservable.notifyObservers(this);
  32458. }
  32459. return this;
  32460. };
  32461. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32462. if (isInstance && effectiveMaterial) {
  32463. effectiveMaterial.bindOnlyWorldMatrix(world);
  32464. }
  32465. };
  32466. /**
  32467. * Returns an array populated with IParticleSystem objects whose the mesh is the emitter.
  32468. */
  32469. Mesh.prototype.getEmittedParticleSystems = function () {
  32470. var results = new Array();
  32471. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32472. var particleSystem = this.getScene().particleSystems[index];
  32473. if (particleSystem.emitter === this) {
  32474. results.push(particleSystem);
  32475. }
  32476. }
  32477. return results;
  32478. };
  32479. /**
  32480. * Returns an array populated with IParticleSystem objects whose the mesh or its children are the emitter.
  32481. */
  32482. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32483. var results = new Array();
  32484. var descendants = this.getDescendants();
  32485. descendants.push(this);
  32486. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32487. var particleSystem = this.getScene().particleSystems[index];
  32488. var emitter = particleSystem.emitter;
  32489. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32490. results.push(particleSystem);
  32491. }
  32492. }
  32493. return results;
  32494. };
  32495. /**
  32496. * Normalize matrix weights so that all vertices have a total weight set to 1
  32497. */
  32498. Mesh.prototype.cleanMatrixWeights = function () {
  32499. var epsilon = 1e-3;
  32500. var noInfluenceBoneIndex = 0.0;
  32501. if (this.skeleton) {
  32502. noInfluenceBoneIndex = this.skeleton.bones.length;
  32503. }
  32504. else {
  32505. return;
  32506. }
  32507. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32508. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32509. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32510. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32511. var influencers = this.numBoneInfluencers;
  32512. var size = matricesWeights.length;
  32513. for (var i = 0; i < size; i += 4) {
  32514. var weight = 0.0;
  32515. var firstZeroWeight = -1;
  32516. for (var j = 0; j < 4; j++) {
  32517. var w = matricesWeights[i + j];
  32518. weight += w;
  32519. if (w < epsilon && firstZeroWeight < 0) {
  32520. firstZeroWeight = j;
  32521. }
  32522. }
  32523. if (matricesWeightsExtra) {
  32524. for (var j = 0; j < 4; j++) {
  32525. var w = matricesWeightsExtra[i + j];
  32526. weight += w;
  32527. if (w < epsilon && firstZeroWeight < 0) {
  32528. firstZeroWeight = j + 4;
  32529. }
  32530. }
  32531. }
  32532. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32533. firstZeroWeight = influencers - 1;
  32534. }
  32535. if (weight > epsilon) {
  32536. var mweight = 1.0 / weight;
  32537. for (var j = 0; j < 4; j++) {
  32538. matricesWeights[i + j] *= mweight;
  32539. }
  32540. if (matricesWeightsExtra) {
  32541. for (var j = 0; j < 4; j++) {
  32542. matricesWeightsExtra[i + j] *= mweight;
  32543. }
  32544. }
  32545. }
  32546. else {
  32547. if (firstZeroWeight >= 4) {
  32548. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32549. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32550. }
  32551. else {
  32552. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32553. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32554. }
  32555. }
  32556. }
  32557. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32558. if (matricesIndicesExtra) {
  32559. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32560. }
  32561. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32562. if (matricesWeightsExtra) {
  32563. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32564. }
  32565. };
  32566. /** @hidden */
  32567. Mesh.prototype._checkDelayState = function () {
  32568. var scene = this.getScene();
  32569. if (this._geometry) {
  32570. this._geometry.load(scene);
  32571. }
  32572. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32573. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32574. this._queueLoad(scene);
  32575. }
  32576. return this;
  32577. };
  32578. Mesh.prototype._queueLoad = function (scene) {
  32579. var _this = this;
  32580. scene._addPendingData(this);
  32581. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32582. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32583. if (data instanceof ArrayBuffer) {
  32584. _this._delayLoadingFunction(data, _this);
  32585. }
  32586. else {
  32587. _this._delayLoadingFunction(JSON.parse(data), _this);
  32588. }
  32589. _this.instances.forEach(function (instance) {
  32590. instance._syncSubMeshes();
  32591. });
  32592. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32593. scene._removePendingData(_this);
  32594. }, function () { }, scene.database, getBinaryData);
  32595. return this;
  32596. };
  32597. /**
  32598. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  32599. * A mesh is in the frustum if its bounding box intersects the frustum
  32600. * @param frustumPlanes defines the frustum to test
  32601. * @returns true if the mesh is in the frustum planes
  32602. */
  32603. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32604. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32605. return false;
  32606. }
  32607. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32608. return false;
  32609. }
  32610. this._checkDelayState();
  32611. return true;
  32612. };
  32613. /**
  32614. * Sets the mesh material by the material or multiMaterial `id` property.
  32615. * The material `id` is a string identifying the material or the multiMaterial.
  32616. * This method returns the Mesh.
  32617. */
  32618. Mesh.prototype.setMaterialByID = function (id) {
  32619. var materials = this.getScene().materials;
  32620. var index;
  32621. for (index = materials.length - 1; index > -1; index--) {
  32622. if (materials[index].id === id) {
  32623. this.material = materials[index];
  32624. return this;
  32625. }
  32626. }
  32627. // Multi
  32628. var multiMaterials = this.getScene().multiMaterials;
  32629. for (index = multiMaterials.length - 1; index > -1; index--) {
  32630. if (multiMaterials[index].id === id) {
  32631. this.material = multiMaterials[index];
  32632. return this;
  32633. }
  32634. }
  32635. return this;
  32636. };
  32637. /**
  32638. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32639. */
  32640. Mesh.prototype.getAnimatables = function () {
  32641. var results = new Array();
  32642. if (this.material) {
  32643. results.push(this.material);
  32644. }
  32645. if (this.skeleton) {
  32646. results.push(this.skeleton);
  32647. }
  32648. return results;
  32649. };
  32650. /**
  32651. * Modifies the mesh geometry according to the passed transformation matrix.
  32652. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32653. * The mesh normals are modified using the same transformation.
  32654. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32655. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32656. * Returns the Mesh.
  32657. */
  32658. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32659. // Position
  32660. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32661. return this;
  32662. }
  32663. var submeshes = this.subMeshes.splice(0);
  32664. this._resetPointsArrayCache();
  32665. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32666. var temp = new Array();
  32667. var index;
  32668. for (index = 0; index < data.length; index += 3) {
  32669. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32670. }
  32671. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32672. // Normals
  32673. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32674. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32675. temp = [];
  32676. for (index = 0; index < data.length; index += 3) {
  32677. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32678. }
  32679. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32680. }
  32681. // flip faces?
  32682. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32683. this.flipFaces();
  32684. }
  32685. // Restore submeshes
  32686. this.releaseSubMeshes();
  32687. this.subMeshes = submeshes;
  32688. return this;
  32689. };
  32690. /**
  32691. * Modifies the mesh geometry according to its own current World Matrix.
  32692. * The mesh World Matrix is then reset.
  32693. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32694. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32695. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32696. * Returns the Mesh.
  32697. */
  32698. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32699. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32700. this.scaling.copyFromFloats(1, 1, 1);
  32701. this.position.copyFromFloats(0, 0, 0);
  32702. this.rotation.copyFromFloats(0, 0, 0);
  32703. //only if quaternion is already set
  32704. if (this.rotationQuaternion) {
  32705. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32706. }
  32707. this._worldMatrix = BABYLON.Matrix.Identity();
  32708. return this;
  32709. };
  32710. Object.defineProperty(Mesh.prototype, "_positions", {
  32711. // Cache
  32712. get: function () {
  32713. if (this._geometry) {
  32714. return this._geometry._positions;
  32715. }
  32716. return null;
  32717. },
  32718. enumerable: true,
  32719. configurable: true
  32720. });
  32721. /** @hidden */
  32722. Mesh.prototype._resetPointsArrayCache = function () {
  32723. if (this._geometry) {
  32724. this._geometry._resetPointsArrayCache();
  32725. }
  32726. return this;
  32727. };
  32728. /** @hidden */
  32729. Mesh.prototype._generatePointsArray = function () {
  32730. if (this._geometry) {
  32731. return this._geometry._generatePointsArray();
  32732. }
  32733. return false;
  32734. };
  32735. /**
  32736. * Returns a new Mesh object generated from the current mesh properties.
  32737. * This method must not get confused with createInstance().
  32738. * The parameter `name` is a string, the name given to the new mesh.
  32739. * The optional parameter `newParent` can be any Node object (default `null`).
  32740. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32741. * 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.
  32742. */
  32743. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32744. if (name === void 0) { name = ""; }
  32745. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32746. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32747. };
  32748. /**
  32749. * Releases resources associated with this mesh.
  32750. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32751. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32752. */
  32753. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32754. var _this = this;
  32755. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32756. this.morphTargetManager = null;
  32757. if (this._geometry) {
  32758. this._geometry.releaseForMesh(this, true);
  32759. }
  32760. if (this._onBeforeDrawObservable) {
  32761. this._onBeforeDrawObservable.clear();
  32762. }
  32763. if (this._onBeforeRenderObservable) {
  32764. this._onBeforeRenderObservable.clear();
  32765. }
  32766. if (this._onAfterRenderObservable) {
  32767. this._onAfterRenderObservable.clear();
  32768. }
  32769. // Sources
  32770. var meshes = this.getScene().meshes;
  32771. meshes.forEach(function (abstractMesh) {
  32772. var mesh = abstractMesh;
  32773. if (mesh._source && mesh._source === _this) {
  32774. mesh._source = null;
  32775. }
  32776. });
  32777. this._source = null;
  32778. // Instances
  32779. if (this._instancesBuffer) {
  32780. this._instancesBuffer.dispose();
  32781. this._instancesBuffer = null;
  32782. }
  32783. while (this.instances.length) {
  32784. this.instances[0].dispose();
  32785. }
  32786. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32787. };
  32788. /**
  32789. * Modifies the mesh geometry according to a displacement map.
  32790. * 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.
  32791. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32792. * This method returns nothing.
  32793. * @param url is a string, the URL from the image file is to be downloaded.
  32794. * @param minHeight is the lower limit of the displacement.
  32795. * @param maxHeight is the upper limit of the displacement.
  32796. * @param onSuccess is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing.
  32797. * @param uvOffset is an optional vector2 used to offset UV.
  32798. * @param uvScale is an optional vector2 used to scale UV.
  32799. * @param forceUpdate defines whether or not to force an update of the generated buffers. This is usefull to apply on a deserialized model for instance.
  32800. * @returns the Mesh.
  32801. */
  32802. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate) {
  32803. var _this = this;
  32804. if (forceUpdate === void 0) { forceUpdate = false; }
  32805. var scene = this.getScene();
  32806. var onload = function (img) {
  32807. // Getting height map data
  32808. var canvas = document.createElement("canvas");
  32809. var context = canvas.getContext("2d");
  32810. var heightMapWidth = img.width;
  32811. var heightMapHeight = img.height;
  32812. canvas.width = heightMapWidth;
  32813. canvas.height = heightMapHeight;
  32814. context.drawImage(img, 0, 0);
  32815. // Create VertexData from map data
  32816. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32817. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32818. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
  32819. //execute success callback, if set
  32820. if (onSuccess) {
  32821. onSuccess(_this);
  32822. }
  32823. };
  32824. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32825. return this;
  32826. };
  32827. /**
  32828. * Modifies the mesh geometry according to a displacementMap buffer.
  32829. * 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.
  32830. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32831. * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  32832. * @param heightMapWidth is the width of the buffer image.
  32833. * @param heightMapHeight is the height of the buffer image.
  32834. * @param minHeight is the lower limit of the displacement.
  32835. * @param maxHeight is the upper limit of the displacement.
  32836. * @param onSuccess is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing.
  32837. * @param uvOffset is an optional vector2 used to offset UV.
  32838. * @param uvScale is an optional vector2 used to scale UV.
  32839. * @param forceUpdate defines whether or not to force an update of the generated buffers. This is usefull to apply on a deserialized model for instance.
  32840. * @returns the Mesh.
  32841. */
  32842. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate) {
  32843. if (forceUpdate === void 0) { forceUpdate = false; }
  32844. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32845. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32846. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32847. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32848. return this;
  32849. }
  32850. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, true, true);
  32851. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32852. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32853. var position = BABYLON.Vector3.Zero();
  32854. var normal = BABYLON.Vector3.Zero();
  32855. var uv = BABYLON.Vector2.Zero();
  32856. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32857. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32858. for (var index = 0; index < positions.length; index += 3) {
  32859. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32860. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32861. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32862. // Compute height
  32863. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32864. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32865. var pos = (u + v * heightMapWidth) * 4;
  32866. var r = buffer[pos] / 255.0;
  32867. var g = buffer[pos + 1] / 255.0;
  32868. var b = buffer[pos + 2] / 255.0;
  32869. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32870. normal.normalize();
  32871. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32872. position = position.add(normal);
  32873. position.toArray(positions, index);
  32874. }
  32875. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32876. if (forceUpdate) {
  32877. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32878. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32879. }
  32880. else {
  32881. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32882. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32883. }
  32884. return this;
  32885. };
  32886. /**
  32887. * Modify the mesh to get a flat shading rendering.
  32888. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32889. * This method returns the Mesh.
  32890. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32891. */
  32892. Mesh.prototype.convertToFlatShadedMesh = function () {
  32893. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32894. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32895. var kinds = this.getVerticesDataKinds();
  32896. var vbs = {};
  32897. var data = {};
  32898. var newdata = {};
  32899. var updatableNormals = false;
  32900. var kindIndex;
  32901. var kind;
  32902. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32903. kind = kinds[kindIndex];
  32904. var vertexBuffer = this.getVertexBuffer(kind);
  32905. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32906. updatableNormals = vertexBuffer.isUpdatable();
  32907. kinds.splice(kindIndex, 1);
  32908. kindIndex--;
  32909. continue;
  32910. }
  32911. vbs[kind] = vertexBuffer;
  32912. data[kind] = vbs[kind].getData();
  32913. newdata[kind] = [];
  32914. }
  32915. // Save previous submeshes
  32916. var previousSubmeshes = this.subMeshes.slice(0);
  32917. var indices = this.getIndices();
  32918. var totalIndices = this.getTotalIndices();
  32919. // Generating unique vertices per face
  32920. var index;
  32921. for (index = 0; index < totalIndices; index++) {
  32922. var vertexIndex = indices[index];
  32923. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32924. kind = kinds[kindIndex];
  32925. var stride = vbs[kind].getStrideSize();
  32926. for (var offset = 0; offset < stride; offset++) {
  32927. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32928. }
  32929. }
  32930. }
  32931. // Updating faces & normal
  32932. var normals = [];
  32933. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32934. for (index = 0; index < totalIndices; index += 3) {
  32935. indices[index] = index;
  32936. indices[index + 1] = index + 1;
  32937. indices[index + 2] = index + 2;
  32938. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32939. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32940. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32941. var p1p2 = p1.subtract(p2);
  32942. var p3p2 = p3.subtract(p2);
  32943. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32944. // Store same normals for every vertex
  32945. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32946. normals.push(normal.x);
  32947. normals.push(normal.y);
  32948. normals.push(normal.z);
  32949. }
  32950. }
  32951. this.setIndices(indices);
  32952. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32953. // Updating vertex buffers
  32954. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32955. kind = kinds[kindIndex];
  32956. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32957. }
  32958. // Updating submeshes
  32959. this.releaseSubMeshes();
  32960. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32961. var previousOne = previousSubmeshes[submeshIndex];
  32962. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32963. }
  32964. this.synchronizeInstances();
  32965. return this;
  32966. };
  32967. /**
  32968. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32969. * In other words, more vertices, no more indices and a single bigger VBO.
  32970. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32971. * Returns the Mesh.
  32972. */
  32973. Mesh.prototype.convertToUnIndexedMesh = function () {
  32974. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32975. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32976. var kinds = this.getVerticesDataKinds();
  32977. var vbs = {};
  32978. var data = {};
  32979. var newdata = {};
  32980. var kindIndex;
  32981. var kind;
  32982. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32983. kind = kinds[kindIndex];
  32984. var vertexBuffer = this.getVertexBuffer(kind);
  32985. vbs[kind] = vertexBuffer;
  32986. data[kind] = vbs[kind].getData();
  32987. newdata[kind] = [];
  32988. }
  32989. // Save previous submeshes
  32990. var previousSubmeshes = this.subMeshes.slice(0);
  32991. var indices = this.getIndices();
  32992. var totalIndices = this.getTotalIndices();
  32993. // Generating unique vertices per face
  32994. var index;
  32995. for (index = 0; index < totalIndices; index++) {
  32996. var vertexIndex = indices[index];
  32997. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32998. kind = kinds[kindIndex];
  32999. var stride = vbs[kind].getStrideSize();
  33000. for (var offset = 0; offset < stride; offset++) {
  33001. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33002. }
  33003. }
  33004. }
  33005. // Updating indices
  33006. for (index = 0; index < totalIndices; index += 3) {
  33007. indices[index] = index;
  33008. indices[index + 1] = index + 1;
  33009. indices[index + 2] = index + 2;
  33010. }
  33011. this.setIndices(indices);
  33012. // Updating vertex buffers
  33013. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33014. kind = kinds[kindIndex];
  33015. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33016. }
  33017. // Updating submeshes
  33018. this.releaseSubMeshes();
  33019. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33020. var previousOne = previousSubmeshes[submeshIndex];
  33021. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33022. }
  33023. this._unIndexed = true;
  33024. this.synchronizeInstances();
  33025. return this;
  33026. };
  33027. /**
  33028. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  33029. * This method returns the Mesh.
  33030. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  33031. */
  33032. Mesh.prototype.flipFaces = function (flipNormals) {
  33033. if (flipNormals === void 0) { flipNormals = false; }
  33034. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  33035. var i;
  33036. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  33037. for (i = 0; i < vertex_data.normals.length; i++) {
  33038. vertex_data.normals[i] *= -1;
  33039. }
  33040. }
  33041. if (vertex_data.indices) {
  33042. var temp;
  33043. for (i = 0; i < vertex_data.indices.length; i += 3) {
  33044. // reassign indices
  33045. temp = vertex_data.indices[i + 1];
  33046. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  33047. vertex_data.indices[i + 2] = temp;
  33048. }
  33049. }
  33050. vertex_data.applyToMesh(this);
  33051. return this;
  33052. };
  33053. // Instances
  33054. /**
  33055. * Creates a new InstancedMesh object from the mesh model.
  33056. * An instance shares the same properties and the same material than its model.
  33057. * Please make sure to call mesh.makeGeometryUnique() if you are calling createInstance on a previously cloned mesh.
  33058. * Only these properties of each instance can then be set individually :
  33059. * - position
  33060. * - rotation
  33061. * - rotationQuaternion
  33062. * - setPivotMatrix
  33063. * - scaling
  33064. *
  33065. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  33066. * Warning : this method is not supported for Line mesh and LineSystem
  33067. */
  33068. Mesh.prototype.createInstance = function (name) {
  33069. return new BABYLON.InstancedMesh(name, this);
  33070. };
  33071. /**
  33072. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  33073. * After this call, all the mesh instances have the same submeshes than the current mesh.
  33074. * This method returns the Mesh.
  33075. */
  33076. Mesh.prototype.synchronizeInstances = function () {
  33077. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  33078. var instance = this.instances[instanceIndex];
  33079. instance._syncSubMeshes();
  33080. }
  33081. return this;
  33082. };
  33083. /**
  33084. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  33085. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  33086. * This should be used together with the simplification to avoid disappearing triangles.
  33087. * Returns the Mesh.
  33088. * @param successCallback an optional success callback to be called after the optimization finished.
  33089. */
  33090. Mesh.prototype.optimizeIndices = function (successCallback) {
  33091. var _this = this;
  33092. var indices = this.getIndices();
  33093. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33094. if (!positions || !indices) {
  33095. return this;
  33096. }
  33097. var vectorPositions = new Array();
  33098. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  33099. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  33100. }
  33101. var dupes = new Array();
  33102. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  33103. var realPos = vectorPositions.length - 1 - iteration;
  33104. var testedPosition = vectorPositions[realPos];
  33105. for (var j = 0; j < realPos; ++j) {
  33106. var againstPosition = vectorPositions[j];
  33107. if (testedPosition.equals(againstPosition)) {
  33108. dupes[realPos] = j;
  33109. break;
  33110. }
  33111. }
  33112. }, function () {
  33113. for (var i = 0; i < indices.length; ++i) {
  33114. indices[i] = dupes[indices[i]] || indices[i];
  33115. }
  33116. //indices are now reordered
  33117. var originalSubMeshes = _this.subMeshes.slice(0);
  33118. _this.setIndices(indices);
  33119. _this.subMeshes = originalSubMeshes;
  33120. if (successCallback) {
  33121. successCallback(_this);
  33122. }
  33123. });
  33124. return this;
  33125. };
  33126. Mesh.prototype.serialize = function (serializationObject) {
  33127. serializationObject.name = this.name;
  33128. serializationObject.id = this.id;
  33129. serializationObject.type = this.getClassName();
  33130. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33131. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33132. }
  33133. serializationObject.position = this.position.asArray();
  33134. if (this.rotationQuaternion) {
  33135. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  33136. }
  33137. else if (this.rotation) {
  33138. serializationObject.rotation = this.rotation.asArray();
  33139. }
  33140. serializationObject.scaling = this.scaling.asArray();
  33141. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33142. serializationObject.isEnabled = this.isEnabled(false);
  33143. serializationObject.isVisible = this.isVisible;
  33144. serializationObject.infiniteDistance = this.infiniteDistance;
  33145. serializationObject.pickable = this.isPickable;
  33146. serializationObject.receiveShadows = this.receiveShadows;
  33147. serializationObject.billboardMode = this.billboardMode;
  33148. serializationObject.visibility = this.visibility;
  33149. serializationObject.checkCollisions = this.checkCollisions;
  33150. serializationObject.isBlocker = this.isBlocker;
  33151. // Parent
  33152. if (this.parent) {
  33153. serializationObject.parentId = this.parent.id;
  33154. }
  33155. // Geometry
  33156. serializationObject.isUnIndexed = this.isUnIndexed;
  33157. var geometry = this._geometry;
  33158. if (geometry) {
  33159. var geometryId = geometry.id;
  33160. serializationObject.geometryId = geometryId;
  33161. // SubMeshes
  33162. serializationObject.subMeshes = [];
  33163. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33164. var subMesh = this.subMeshes[subIndex];
  33165. serializationObject.subMeshes.push({
  33166. materialIndex: subMesh.materialIndex,
  33167. verticesStart: subMesh.verticesStart,
  33168. verticesCount: subMesh.verticesCount,
  33169. indexStart: subMesh.indexStart,
  33170. indexCount: subMesh.indexCount
  33171. });
  33172. }
  33173. }
  33174. // Material
  33175. if (this.material) {
  33176. serializationObject.materialId = this.material.id;
  33177. }
  33178. else {
  33179. this.material = null;
  33180. }
  33181. // Morph targets
  33182. if (this.morphTargetManager) {
  33183. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33184. }
  33185. // Skeleton
  33186. if (this.skeleton) {
  33187. serializationObject.skeletonId = this.skeleton.id;
  33188. }
  33189. // Physics
  33190. //TODO implement correct serialization for physics impostors.
  33191. var impostor = this.getPhysicsImpostor();
  33192. if (impostor) {
  33193. serializationObject.physicsMass = impostor.getParam("mass");
  33194. serializationObject.physicsFriction = impostor.getParam("friction");
  33195. serializationObject.physicsRestitution = impostor.getParam("mass");
  33196. serializationObject.physicsImpostor = impostor.type;
  33197. }
  33198. // Metadata
  33199. if (this.metadata) {
  33200. serializationObject.metadata = this.metadata;
  33201. }
  33202. // Instances
  33203. serializationObject.instances = [];
  33204. for (var index = 0; index < this.instances.length; index++) {
  33205. var instance = this.instances[index];
  33206. if (instance.doNotSerialize) {
  33207. continue;
  33208. }
  33209. var serializationInstance = {
  33210. name: instance.name,
  33211. id: instance.id,
  33212. position: instance.position.asArray(),
  33213. scaling: instance.scaling.asArray()
  33214. };
  33215. if (instance.parent) {
  33216. serializationInstance.parentId = instance.parent.id;
  33217. }
  33218. if (instance.rotationQuaternion) {
  33219. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33220. }
  33221. else if (instance.rotation) {
  33222. serializationInstance.rotation = instance.rotation.asArray();
  33223. }
  33224. serializationObject.instances.push(serializationInstance);
  33225. // Animations
  33226. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33227. serializationInstance.ranges = instance.serializeAnimationRanges();
  33228. }
  33229. //
  33230. // Animations
  33231. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33232. serializationObject.ranges = this.serializeAnimationRanges();
  33233. // Layer mask
  33234. serializationObject.layerMask = this.layerMask;
  33235. // Alpha
  33236. serializationObject.alphaIndex = this.alphaIndex;
  33237. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33238. // Overlay
  33239. serializationObject.overlayAlpha = this.overlayAlpha;
  33240. serializationObject.overlayColor = this.overlayColor.asArray();
  33241. serializationObject.renderOverlay = this.renderOverlay;
  33242. // Fog
  33243. serializationObject.applyFog = this.applyFog;
  33244. // Action Manager
  33245. if (this.actionManager) {
  33246. serializationObject.actions = this.actionManager.serialize(this.name);
  33247. }
  33248. };
  33249. /** @hidden */
  33250. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33251. if (!this.geometry) {
  33252. return;
  33253. }
  33254. this._markSubMeshesAsAttributesDirty();
  33255. var morphTargetManager = this._morphTargetManager;
  33256. if (morphTargetManager && morphTargetManager.vertexCount) {
  33257. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33258. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33259. this.morphTargetManager = null;
  33260. return;
  33261. }
  33262. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33263. var morphTarget = morphTargetManager.getActiveTarget(index);
  33264. var positions = morphTarget.getPositions();
  33265. if (!positions) {
  33266. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33267. return;
  33268. }
  33269. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33270. var normals = morphTarget.getNormals();
  33271. if (normals) {
  33272. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33273. }
  33274. var tangents = morphTarget.getTangents();
  33275. if (tangents) {
  33276. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33277. }
  33278. }
  33279. }
  33280. else {
  33281. var index = 0;
  33282. // Positions
  33283. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33284. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33285. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33286. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33287. }
  33288. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33289. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33290. }
  33291. index++;
  33292. }
  33293. }
  33294. };
  33295. // Statics
  33296. /**
  33297. * Returns a new Mesh object parsed from the source provided.
  33298. * The parameter `parsedMesh` is the source.
  33299. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33300. */
  33301. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33302. var mesh;
  33303. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33304. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33305. }
  33306. else {
  33307. mesh = new Mesh(parsedMesh.name, scene);
  33308. }
  33309. mesh.id = parsedMesh.id;
  33310. if (BABYLON.Tags) {
  33311. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33312. }
  33313. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33314. if (parsedMesh.metadata !== undefined) {
  33315. mesh.metadata = parsedMesh.metadata;
  33316. }
  33317. if (parsedMesh.rotationQuaternion) {
  33318. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33319. }
  33320. else if (parsedMesh.rotation) {
  33321. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33322. }
  33323. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33324. if (parsedMesh.localMatrix) {
  33325. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33326. }
  33327. else if (parsedMesh.pivotMatrix) {
  33328. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33329. }
  33330. mesh.setEnabled(parsedMesh.isEnabled);
  33331. mesh.isVisible = parsedMesh.isVisible;
  33332. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33333. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33334. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33335. if (parsedMesh.applyFog !== undefined) {
  33336. mesh.applyFog = parsedMesh.applyFog;
  33337. }
  33338. if (parsedMesh.pickable !== undefined) {
  33339. mesh.isPickable = parsedMesh.pickable;
  33340. }
  33341. if (parsedMesh.alphaIndex !== undefined) {
  33342. mesh.alphaIndex = parsedMesh.alphaIndex;
  33343. }
  33344. mesh.receiveShadows = parsedMesh.receiveShadows;
  33345. mesh.billboardMode = parsedMesh.billboardMode;
  33346. if (parsedMesh.visibility !== undefined) {
  33347. mesh.visibility = parsedMesh.visibility;
  33348. }
  33349. mesh.checkCollisions = parsedMesh.checkCollisions;
  33350. if (parsedMesh.isBlocker !== undefined) {
  33351. mesh.isBlocker = parsedMesh.isBlocker;
  33352. }
  33353. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33354. // freezeWorldMatrix
  33355. if (parsedMesh.freezeWorldMatrix) {
  33356. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33357. }
  33358. // Parent
  33359. if (parsedMesh.parentId) {
  33360. mesh._waitingParentId = parsedMesh.parentId;
  33361. }
  33362. // Actions
  33363. if (parsedMesh.actions !== undefined) {
  33364. mesh._waitingActions = parsedMesh.actions;
  33365. }
  33366. // Overlay
  33367. if (parsedMesh.overlayAlpha !== undefined) {
  33368. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33369. }
  33370. if (parsedMesh.overlayColor !== undefined) {
  33371. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33372. }
  33373. if (parsedMesh.renderOverlay !== undefined) {
  33374. mesh.renderOverlay = parsedMesh.renderOverlay;
  33375. }
  33376. // Geometry
  33377. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33378. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33379. if (parsedMesh.delayLoadingFile) {
  33380. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33381. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33382. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33383. if (parsedMesh._binaryInfo) {
  33384. mesh._binaryInfo = parsedMesh._binaryInfo;
  33385. }
  33386. mesh._delayInfo = [];
  33387. if (parsedMesh.hasUVs) {
  33388. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33389. }
  33390. if (parsedMesh.hasUVs2) {
  33391. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33392. }
  33393. if (parsedMesh.hasUVs3) {
  33394. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33395. }
  33396. if (parsedMesh.hasUVs4) {
  33397. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33398. }
  33399. if (parsedMesh.hasUVs5) {
  33400. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33401. }
  33402. if (parsedMesh.hasUVs6) {
  33403. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33404. }
  33405. if (parsedMesh.hasColors) {
  33406. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33407. }
  33408. if (parsedMesh.hasMatricesIndices) {
  33409. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33410. }
  33411. if (parsedMesh.hasMatricesWeights) {
  33412. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33413. }
  33414. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33415. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33416. mesh._checkDelayState();
  33417. }
  33418. }
  33419. else {
  33420. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33421. }
  33422. // Material
  33423. if (parsedMesh.materialId) {
  33424. mesh.setMaterialByID(parsedMesh.materialId);
  33425. }
  33426. else {
  33427. mesh.material = null;
  33428. }
  33429. // Morph targets
  33430. if (parsedMesh.morphTargetManagerId > -1) {
  33431. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33432. }
  33433. // Skeleton
  33434. if (parsedMesh.skeletonId > -1) {
  33435. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33436. if (parsedMesh.numBoneInfluencers) {
  33437. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33438. }
  33439. }
  33440. // Animations
  33441. if (parsedMesh.animations) {
  33442. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33443. var parsedAnimation = parsedMesh.animations[animationIndex];
  33444. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33445. }
  33446. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33447. }
  33448. if (parsedMesh.autoAnimate) {
  33449. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33450. }
  33451. // Layer Mask
  33452. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33453. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33454. }
  33455. else {
  33456. mesh.layerMask = 0x0FFFFFFF;
  33457. }
  33458. // Physics
  33459. if (parsedMesh.physicsImpostor) {
  33460. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33461. mass: parsedMesh.physicsMass,
  33462. friction: parsedMesh.physicsFriction,
  33463. restitution: parsedMesh.physicsRestitution
  33464. }, scene);
  33465. }
  33466. // Instances
  33467. if (parsedMesh.instances) {
  33468. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33469. var parsedInstance = parsedMesh.instances[index];
  33470. var instance = mesh.createInstance(parsedInstance.name);
  33471. if (parsedInstance.id) {
  33472. instance.id = parsedInstance.id;
  33473. }
  33474. if (BABYLON.Tags) {
  33475. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33476. }
  33477. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33478. if (parsedInstance.parentId) {
  33479. instance._waitingParentId = parsedInstance.parentId;
  33480. }
  33481. if (parsedInstance.rotationQuaternion) {
  33482. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33483. }
  33484. else if (parsedInstance.rotation) {
  33485. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33486. }
  33487. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33488. instance.checkCollisions = mesh.checkCollisions;
  33489. if (parsedMesh.animations) {
  33490. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33491. parsedAnimation = parsedMesh.animations[animationIndex];
  33492. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33493. }
  33494. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33495. if (parsedMesh.autoAnimate) {
  33496. scene.beginAnimation(instance, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33497. }
  33498. }
  33499. }
  33500. }
  33501. return mesh;
  33502. };
  33503. /**
  33504. * Creates a ribbon mesh.
  33505. * Please consider using the same method from the MeshBuilder class instead.
  33506. * The ribbon is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33507. *
  33508. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33509. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33510. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33511. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33512. * 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.
  33513. * 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.
  33514. * 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
  33515. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33516. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33517. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33518. */
  33519. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33520. if (closeArray === void 0) { closeArray = false; }
  33521. if (updatable === void 0) { updatable = false; }
  33522. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33523. pathArray: pathArray,
  33524. closeArray: closeArray,
  33525. closePath: closePath,
  33526. offset: offset,
  33527. updatable: updatable,
  33528. sideOrientation: sideOrientation,
  33529. instance: instance
  33530. }, scene);
  33531. };
  33532. /**
  33533. * Creates a plane polygonal mesh. By default, this is a disc.
  33534. * Please consider using the same method from the MeshBuilder class instead.
  33535. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33536. * 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.
  33537. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33538. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33539. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33540. */
  33541. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33542. if (scene === void 0) { scene = null; }
  33543. var options = {
  33544. radius: radius,
  33545. tessellation: tessellation,
  33546. sideOrientation: sideOrientation,
  33547. updatable: updatable
  33548. };
  33549. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33550. };
  33551. /**
  33552. * Creates a box mesh.
  33553. * Please consider using the same method from the MeshBuilder class instead.
  33554. * The parameter `size` sets the size (float) of each box side (default 1).
  33555. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33556. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33557. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33558. */
  33559. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33560. if (scene === void 0) { scene = null; }
  33561. var options = {
  33562. size: size,
  33563. sideOrientation: sideOrientation,
  33564. updatable: updatable
  33565. };
  33566. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33567. };
  33568. /**
  33569. * Creates a sphere mesh.
  33570. * Please consider using the same method from the MeshBuilder class instead.
  33571. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33572. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33573. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33574. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33575. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33576. */
  33577. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33578. var options = {
  33579. segments: segments,
  33580. diameterX: diameter,
  33581. diameterY: diameter,
  33582. diameterZ: diameter,
  33583. sideOrientation: sideOrientation,
  33584. updatable: updatable
  33585. };
  33586. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33587. };
  33588. /**
  33589. * Creates a cylinder or a cone mesh.
  33590. * Please consider using the same method from the MeshBuilder class instead.
  33591. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33592. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33593. * 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.
  33594. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33595. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33596. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33597. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33598. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33599. */
  33600. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33601. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33602. if (scene !== undefined) {
  33603. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33604. updatable = scene;
  33605. }
  33606. scene = subdivisions;
  33607. subdivisions = 1;
  33608. }
  33609. var options = {
  33610. height: height,
  33611. diameterTop: diameterTop,
  33612. diameterBottom: diameterBottom,
  33613. tessellation: tessellation,
  33614. subdivisions: subdivisions,
  33615. sideOrientation: sideOrientation,
  33616. updatable: updatable
  33617. };
  33618. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33619. };
  33620. // Torus (Code from SharpDX.org)
  33621. /**
  33622. * Creates a torus mesh.
  33623. * Please consider using the same method from the MeshBuilder class instead.
  33624. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33625. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33626. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33627. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33628. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33629. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33630. */
  33631. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33632. var options = {
  33633. diameter: diameter,
  33634. thickness: thickness,
  33635. tessellation: tessellation,
  33636. sideOrientation: sideOrientation,
  33637. updatable: updatable
  33638. };
  33639. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33640. };
  33641. /**
  33642. * Creates a torus knot mesh.
  33643. * Please consider using the same method from the MeshBuilder class instead.
  33644. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33645. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33646. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33647. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33648. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33649. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33650. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33651. */
  33652. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33653. var options = {
  33654. radius: radius,
  33655. tube: tube,
  33656. radialSegments: radialSegments,
  33657. tubularSegments: tubularSegments,
  33658. p: p,
  33659. q: q,
  33660. sideOrientation: sideOrientation,
  33661. updatable: updatable
  33662. };
  33663. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33664. };
  33665. /**
  33666. * Creates a line mesh.
  33667. * Please consider using the same method from the MeshBuilder class instead.
  33668. * 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.
  33669. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33670. * The parameter `points` is an array successive Vector3.
  33671. * 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
  33672. * When updating an instance, remember that only point positions can change, not the number of points.
  33673. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33674. */
  33675. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33676. if (scene === void 0) { scene = null; }
  33677. if (updatable === void 0) { updatable = false; }
  33678. if (instance === void 0) { instance = null; }
  33679. var options = {
  33680. points: points,
  33681. updatable: updatable,
  33682. instance: instance
  33683. };
  33684. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33685. };
  33686. /**
  33687. * Creates a dashed line mesh.
  33688. * Please consider using the same method from the MeshBuilder class instead.
  33689. * 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.
  33690. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33691. * The parameter `points` is an array successive Vector3.
  33692. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33693. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33694. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33695. * 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
  33696. * When updating an instance, remember that only point positions can change, not the number of points.
  33697. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33698. */
  33699. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33700. if (scene === void 0) { scene = null; }
  33701. var options = {
  33702. points: points,
  33703. dashSize: dashSize,
  33704. gapSize: gapSize,
  33705. dashNb: dashNb,
  33706. updatable: updatable,
  33707. instance: instance
  33708. };
  33709. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33710. };
  33711. /**
  33712. * Creates a polygon mesh.
  33713. * Please consider using the same method from the MeshBuilder class instead.
  33714. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33715. * 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.
  33716. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33717. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33718. * Remember you can only change the shape positions, not their number when updating a polygon.
  33719. */
  33720. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33721. var options = {
  33722. shape: shape,
  33723. holes: holes,
  33724. updatable: updatable,
  33725. sideOrientation: sideOrientation
  33726. };
  33727. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33728. };
  33729. /**
  33730. * Creates an extruded polygon mesh, with depth in the Y direction.
  33731. * Please consider using the same method from the MeshBuilder class instead.
  33732. */
  33733. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33734. var options = {
  33735. shape: shape,
  33736. holes: holes,
  33737. depth: depth,
  33738. updatable: updatable,
  33739. sideOrientation: sideOrientation
  33740. };
  33741. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33742. };
  33743. /**
  33744. * Creates an extruded shape mesh.
  33745. * The extrusion is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33746. * Please consider using the same method from the MeshBuilder class instead.
  33747. *
  33748. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33749. * 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
  33750. * extruded along the Z axis.
  33751. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33752. * 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.
  33753. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33754. * 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
  33755. * 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
  33756. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33757. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33758. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33759. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33760. */
  33761. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33762. if (scene === void 0) { scene = null; }
  33763. var options = {
  33764. shape: shape,
  33765. path: path,
  33766. scale: scale,
  33767. rotation: rotation,
  33768. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33769. sideOrientation: sideOrientation,
  33770. instance: instance,
  33771. updatable: updatable
  33772. };
  33773. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33774. };
  33775. /**
  33776. * Creates an custom extruded shape mesh.
  33777. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33778. * Please consider using the same method from the MeshBuilder class instead.
  33779. *
  33780. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33781. * 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
  33782. * extruded along the Z axis.
  33783. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33784. * 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
  33785. * and the distance of this point from the begining of the path :
  33786. * ```javascript
  33787. * var rotationFunction = function(i, distance) {
  33788. * // do things
  33789. * return rotationValue; }
  33790. * ```
  33791. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33792. * 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
  33793. * and the distance of this point from the begining of the path :
  33794. * ```javascript
  33795. * var scaleFunction = function(i, distance) {
  33796. * // do things
  33797. * return scaleValue;}
  33798. * ```
  33799. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33800. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33801. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33802. * 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
  33803. * 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
  33804. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33805. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33806. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33807. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33808. */
  33809. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33810. var options = {
  33811. shape: shape,
  33812. path: path,
  33813. scaleFunction: scaleFunction,
  33814. rotationFunction: rotationFunction,
  33815. ribbonCloseArray: ribbonCloseArray,
  33816. ribbonClosePath: ribbonClosePath,
  33817. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33818. sideOrientation: sideOrientation,
  33819. instance: instance,
  33820. updatable: updatable
  33821. };
  33822. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33823. };
  33824. /**
  33825. * Creates lathe mesh.
  33826. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33827. * Please consider using the same method from the MeshBuilder class instead.
  33828. * 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
  33829. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33830. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33831. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33832. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33833. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33834. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33835. */
  33836. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33837. var options = {
  33838. shape: shape,
  33839. radius: radius,
  33840. tessellation: tessellation,
  33841. sideOrientation: sideOrientation,
  33842. updatable: updatable
  33843. };
  33844. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33845. };
  33846. /**
  33847. * Creates a plane mesh.
  33848. * Please consider using the same method from the MeshBuilder class instead.
  33849. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33850. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33851. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  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. */
  33854. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33855. var options = {
  33856. size: size,
  33857. width: size,
  33858. height: size,
  33859. sideOrientation: sideOrientation,
  33860. updatable: updatable
  33861. };
  33862. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33863. };
  33864. /**
  33865. * Creates a ground mesh.
  33866. * Please consider using the same method from the MeshBuilder class instead.
  33867. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33868. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33869. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33870. */
  33871. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33872. var options = {
  33873. width: width,
  33874. height: height,
  33875. subdivisions: subdivisions,
  33876. updatable: updatable
  33877. };
  33878. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33879. };
  33880. /**
  33881. * Creates a tiled ground mesh.
  33882. * Please consider using the same method from the MeshBuilder class instead.
  33883. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33884. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33885. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33886. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33887. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33888. * numbers of subdivisions on the ground width and height of each tile.
  33889. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33890. */
  33891. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33892. var options = {
  33893. xmin: xmin,
  33894. zmin: zmin,
  33895. xmax: xmax,
  33896. zmax: zmax,
  33897. subdivisions: subdivisions,
  33898. precision: precision,
  33899. updatable: updatable
  33900. };
  33901. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33902. };
  33903. /**
  33904. * Creates a ground mesh from a height map.
  33905. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33906. * Please consider using the same method from the MeshBuilder class instead.
  33907. * The parameter `url` sets the URL of the height map image resource.
  33908. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33909. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33910. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33911. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33912. * 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).
  33913. * This function is passed the newly built mesh :
  33914. * ```javascript
  33915. * function(mesh) { // do things
  33916. * return; }
  33917. * ```
  33918. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33919. */
  33920. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33921. var options = {
  33922. width: width,
  33923. height: height,
  33924. subdivisions: subdivisions,
  33925. minHeight: minHeight,
  33926. maxHeight: maxHeight,
  33927. updatable: updatable,
  33928. onReady: onReady
  33929. };
  33930. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33931. };
  33932. /**
  33933. * Creates a tube mesh.
  33934. * The tube is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33935. * Please consider using the same method from the MeshBuilder class instead.
  33936. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33937. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33938. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33939. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33940. * 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.
  33941. * It must return a radius value (positive float) :
  33942. * ```javascript
  33943. * var radiusFunction = function(i, distance) {
  33944. * // do things
  33945. * return radius; }
  33946. * ```
  33947. * 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
  33948. * 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
  33949. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33950. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33951. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33952. */
  33953. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33954. var options = {
  33955. path: path,
  33956. radius: radius,
  33957. tessellation: tessellation,
  33958. radiusFunction: radiusFunction,
  33959. arc: 1,
  33960. cap: cap,
  33961. updatable: updatable,
  33962. sideOrientation: sideOrientation,
  33963. instance: instance
  33964. };
  33965. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33966. };
  33967. /**
  33968. * Creates a polyhedron mesh.
  33969. * Please consider using the same method from the MeshBuilder class instead.
  33970. * 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
  33971. * to choose the wanted type.
  33972. * The parameter `size` (positive float, default 1) sets the polygon size.
  33973. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33974. * 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`.
  33975. * 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
  33976. * 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)`).
  33977. * 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
  33978. * 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.
  33979. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33980. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33981. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33982. */
  33983. Mesh.CreatePolyhedron = function (name, options, scene) {
  33984. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33985. };
  33986. /**
  33987. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33988. * Please consider using the same method from the MeshBuilder class instead.
  33989. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33990. * 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`).
  33991. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33992. * 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.
  33993. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33994. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33995. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33996. */
  33997. Mesh.CreateIcoSphere = function (name, options, scene) {
  33998. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33999. };
  34000. /**
  34001. * Creates a decal mesh.
  34002. * Please consider using the same method from the MeshBuilder class instead.
  34003. * 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.
  34004. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  34005. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  34006. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  34007. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  34008. */
  34009. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  34010. var options = {
  34011. position: position,
  34012. normal: normal,
  34013. size: size,
  34014. angle: angle
  34015. };
  34016. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  34017. };
  34018. // Skeletons
  34019. /**
  34020. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34021. */
  34022. Mesh.prototype.setPositionsForCPUSkinning = function () {
  34023. if (!this._sourcePositions) {
  34024. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34025. if (!source) {
  34026. return this._sourcePositions;
  34027. }
  34028. this._sourcePositions = new Float32Array(source);
  34029. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34030. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  34031. }
  34032. }
  34033. return this._sourcePositions;
  34034. };
  34035. /**
  34036. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34037. */
  34038. Mesh.prototype.setNormalsForCPUSkinning = function () {
  34039. if (!this._sourceNormals) {
  34040. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34041. if (!source) {
  34042. return this._sourceNormals;
  34043. }
  34044. this._sourceNormals = new Float32Array(source);
  34045. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34046. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  34047. }
  34048. }
  34049. return this._sourceNormals;
  34050. };
  34051. /**
  34052. * Updates the vertex buffer by applying transformation from the bones.
  34053. * Returns the Mesh.
  34054. *
  34055. * @param {skeleton} skeleton to apply
  34056. */
  34057. Mesh.prototype.applySkeleton = function (skeleton) {
  34058. if (!this.geometry) {
  34059. return this;
  34060. }
  34061. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  34062. return this;
  34063. }
  34064. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  34065. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34066. return this;
  34067. }
  34068. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34069. return this;
  34070. }
  34071. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34072. return this;
  34073. }
  34074. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34075. return this;
  34076. }
  34077. if (!this._sourcePositions) {
  34078. var submeshes = this.subMeshes.slice();
  34079. this.setPositionsForCPUSkinning();
  34080. this.subMeshes = submeshes;
  34081. }
  34082. if (!this._sourceNormals) {
  34083. this.setNormalsForCPUSkinning();
  34084. }
  34085. // positionsData checks for not being Float32Array will only pass at most once
  34086. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34087. if (!positionsData) {
  34088. return this;
  34089. }
  34090. if (!(positionsData instanceof Float32Array)) {
  34091. positionsData = new Float32Array(positionsData);
  34092. }
  34093. // normalsData checks for not being Float32Array will only pass at most once
  34094. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34095. if (!normalsData) {
  34096. return this;
  34097. }
  34098. if (!(normalsData instanceof Float32Array)) {
  34099. normalsData = new Float32Array(normalsData);
  34100. }
  34101. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34102. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34103. if (!matricesWeightsData || !matricesIndicesData) {
  34104. return this;
  34105. }
  34106. var needExtras = this.numBoneInfluencers > 4;
  34107. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  34108. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  34109. var skeletonMatrices = skeleton.getTransformMatrices(this);
  34110. var tempVector3 = BABYLON.Vector3.Zero();
  34111. var finalMatrix = new BABYLON.Matrix();
  34112. var tempMatrix = new BABYLON.Matrix();
  34113. var matWeightIdx = 0;
  34114. var inf;
  34115. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  34116. var weight;
  34117. for (inf = 0; inf < 4; inf++) {
  34118. weight = matricesWeightsData[matWeightIdx + inf];
  34119. if (weight > 0) {
  34120. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34121. finalMatrix.addToSelf(tempMatrix);
  34122. }
  34123. }
  34124. if (needExtras) {
  34125. for (inf = 0; inf < 4; inf++) {
  34126. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34127. if (weight > 0) {
  34128. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34129. finalMatrix.addToSelf(tempMatrix);
  34130. }
  34131. }
  34132. }
  34133. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34134. tempVector3.toArray(positionsData, index);
  34135. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34136. tempVector3.toArray(normalsData, index);
  34137. finalMatrix.reset();
  34138. }
  34139. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34140. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34141. return this;
  34142. };
  34143. // Tools
  34144. /**
  34145. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  34146. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  34147. */
  34148. Mesh.MinMax = function (meshes) {
  34149. var minVector = null;
  34150. var maxVector = null;
  34151. meshes.forEach(function (mesh, index, array) {
  34152. var boundingInfo = mesh.getBoundingInfo();
  34153. var boundingBox = boundingInfo.boundingBox;
  34154. if (!minVector || !maxVector) {
  34155. minVector = boundingBox.minimumWorld;
  34156. maxVector = boundingBox.maximumWorld;
  34157. }
  34158. else {
  34159. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34160. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34161. }
  34162. });
  34163. if (!minVector || !maxVector) {
  34164. return {
  34165. min: BABYLON.Vector3.Zero(),
  34166. max: BABYLON.Vector3.Zero()
  34167. };
  34168. }
  34169. return {
  34170. min: minVector,
  34171. max: maxVector
  34172. };
  34173. };
  34174. /**
  34175. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  34176. */
  34177. Mesh.Center = function (meshesOrMinMaxVector) {
  34178. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34179. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34180. };
  34181. /**
  34182. * Merge the array of meshes into a single mesh for performance reasons.
  34183. * @param meshes - The vertices source. They should all be of the same material. Entries can empty
  34184. * @param disposeSource - When true (default), dispose of the vertices from the source meshes
  34185. * @param allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  34186. * @param meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34187. * @param subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  34188. */
  34189. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34190. if (disposeSource === void 0) { disposeSource = true; }
  34191. var index;
  34192. if (!allow32BitsIndices) {
  34193. var totalVertices = 0;
  34194. // Counting vertices
  34195. for (index = 0; index < meshes.length; index++) {
  34196. if (meshes[index]) {
  34197. totalVertices += meshes[index].getTotalVertices();
  34198. if (totalVertices > 65536) {
  34199. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34200. return null;
  34201. }
  34202. }
  34203. }
  34204. }
  34205. // Merge
  34206. var vertexData = null;
  34207. var otherVertexData;
  34208. var indiceArray = new Array();
  34209. var source = null;
  34210. for (index = 0; index < meshes.length; index++) {
  34211. if (meshes[index]) {
  34212. var wm = meshes[index].computeWorldMatrix(true);
  34213. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  34214. otherVertexData.transform(wm);
  34215. if (vertexData) {
  34216. vertexData.merge(otherVertexData, allow32BitsIndices);
  34217. }
  34218. else {
  34219. vertexData = otherVertexData;
  34220. source = meshes[index];
  34221. }
  34222. if (subdivideWithSubMeshes) {
  34223. indiceArray.push(meshes[index].getTotalIndices());
  34224. }
  34225. }
  34226. }
  34227. source = source;
  34228. if (!meshSubclass) {
  34229. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34230. }
  34231. vertexData.applyToMesh(meshSubclass);
  34232. // Setting properties
  34233. meshSubclass.material = source.material;
  34234. meshSubclass.checkCollisions = source.checkCollisions;
  34235. // Cleaning
  34236. if (disposeSource) {
  34237. for (index = 0; index < meshes.length; index++) {
  34238. if (meshes[index]) {
  34239. meshes[index].dispose();
  34240. }
  34241. }
  34242. }
  34243. // Subdivide
  34244. if (subdivideWithSubMeshes) {
  34245. //-- removal of global submesh
  34246. meshSubclass.releaseSubMeshes();
  34247. index = 0;
  34248. var offset = 0;
  34249. //-- apply subdivision according to index table
  34250. while (index < indiceArray.length) {
  34251. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34252. offset += indiceArray[index];
  34253. index++;
  34254. }
  34255. }
  34256. return meshSubclass;
  34257. };
  34258. // Consts
  34259. Mesh._FRONTSIDE = 0;
  34260. Mesh._BACKSIDE = 1;
  34261. Mesh._DOUBLESIDE = 2;
  34262. Mesh._DEFAULTSIDE = 0;
  34263. Mesh._NO_CAP = 0;
  34264. Mesh._CAP_START = 1;
  34265. Mesh._CAP_END = 2;
  34266. Mesh._CAP_ALL = 3;
  34267. return Mesh;
  34268. }(BABYLON.AbstractMesh));
  34269. BABYLON.Mesh = Mesh;
  34270. })(BABYLON || (BABYLON = {}));
  34271. //# sourceMappingURL=babylon.mesh.js.map
  34272. var BABYLON;
  34273. (function (BABYLON) {
  34274. var BaseSubMesh = /** @class */ (function () {
  34275. function BaseSubMesh() {
  34276. }
  34277. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34278. get: function () {
  34279. return this._materialEffect;
  34280. },
  34281. enumerable: true,
  34282. configurable: true
  34283. });
  34284. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34285. if (defines === void 0) { defines = null; }
  34286. if (this._materialEffect === effect) {
  34287. if (!effect) {
  34288. this._materialDefines = null;
  34289. }
  34290. return;
  34291. }
  34292. this._materialDefines = defines;
  34293. this._materialEffect = effect;
  34294. };
  34295. return BaseSubMesh;
  34296. }());
  34297. BABYLON.BaseSubMesh = BaseSubMesh;
  34298. var SubMesh = /** @class */ (function (_super) {
  34299. __extends(SubMesh, _super);
  34300. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34301. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34302. var _this = _super.call(this) || this;
  34303. _this.materialIndex = materialIndex;
  34304. _this.verticesStart = verticesStart;
  34305. _this.verticesCount = verticesCount;
  34306. _this.indexStart = indexStart;
  34307. _this.indexCount = indexCount;
  34308. /** @hidden */
  34309. _this._renderId = 0;
  34310. _this._mesh = mesh;
  34311. _this._renderingMesh = renderingMesh || mesh;
  34312. mesh.subMeshes.push(_this);
  34313. _this._trianglePlanes = [];
  34314. _this._id = mesh.subMeshes.length - 1;
  34315. if (createBoundingBox) {
  34316. _this.refreshBoundingInfo();
  34317. mesh.computeWorldMatrix(true);
  34318. }
  34319. return _this;
  34320. }
  34321. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34322. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34323. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34324. };
  34325. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34326. get: function () {
  34327. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34328. },
  34329. enumerable: true,
  34330. configurable: true
  34331. });
  34332. /**
  34333. * Returns the submesh BoudingInfo object.
  34334. */
  34335. SubMesh.prototype.getBoundingInfo = function () {
  34336. if (this.IsGlobal) {
  34337. return this._mesh.getBoundingInfo();
  34338. }
  34339. return this._boundingInfo;
  34340. };
  34341. /**
  34342. * Sets the submesh BoundingInfo.
  34343. * Return the SubMesh.
  34344. */
  34345. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34346. this._boundingInfo = boundingInfo;
  34347. return this;
  34348. };
  34349. /**
  34350. * Returns the mesh of the current submesh.
  34351. */
  34352. SubMesh.prototype.getMesh = function () {
  34353. return this._mesh;
  34354. };
  34355. /**
  34356. * Returns the rendering mesh of the submesh.
  34357. */
  34358. SubMesh.prototype.getRenderingMesh = function () {
  34359. return this._renderingMesh;
  34360. };
  34361. /**
  34362. * Returns the submesh material.
  34363. */
  34364. SubMesh.prototype.getMaterial = function () {
  34365. var rootMaterial = this._renderingMesh.material;
  34366. if (rootMaterial === null || rootMaterial === undefined) {
  34367. return this._mesh.getScene().defaultMaterial;
  34368. }
  34369. else if (rootMaterial.getSubMaterial) {
  34370. var multiMaterial = rootMaterial;
  34371. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34372. if (this._currentMaterial !== effectiveMaterial) {
  34373. this._currentMaterial = effectiveMaterial;
  34374. this._materialDefines = null;
  34375. }
  34376. return effectiveMaterial;
  34377. }
  34378. return rootMaterial;
  34379. };
  34380. // Methods
  34381. /**
  34382. * Sets a new updated BoundingInfo object to the submesh.
  34383. * Returns the SubMesh.
  34384. */
  34385. SubMesh.prototype.refreshBoundingInfo = function () {
  34386. this._lastColliderWorldVertices = null;
  34387. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34388. return this;
  34389. }
  34390. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34391. if (!data) {
  34392. this._boundingInfo = this._mesh.getBoundingInfo();
  34393. return this;
  34394. }
  34395. var indices = this._renderingMesh.getIndices();
  34396. var extend;
  34397. //is this the only submesh?
  34398. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34399. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34400. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34401. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34402. }
  34403. else {
  34404. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34405. }
  34406. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34407. return this;
  34408. };
  34409. /** @hidden */
  34410. SubMesh.prototype._checkCollision = function (collider) {
  34411. var boundingInfo = this.getBoundingInfo();
  34412. return boundingInfo._checkCollision(collider);
  34413. };
  34414. /**
  34415. * Updates the submesh BoundingInfo.
  34416. * Returns the Submesh.
  34417. */
  34418. SubMesh.prototype.updateBoundingInfo = function (world) {
  34419. var boundingInfo = this.getBoundingInfo();
  34420. if (!boundingInfo) {
  34421. this.refreshBoundingInfo();
  34422. boundingInfo = this.getBoundingInfo();
  34423. }
  34424. boundingInfo.update(world);
  34425. return this;
  34426. };
  34427. /**
  34428. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34429. * Boolean returned.
  34430. */
  34431. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34432. var boundingInfo = this.getBoundingInfo();
  34433. if (!boundingInfo) {
  34434. return false;
  34435. }
  34436. return boundingInfo.isInFrustum(frustumPlanes);
  34437. };
  34438. /**
  34439. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34440. * Boolean returned.
  34441. */
  34442. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34443. var boundingInfo = this.getBoundingInfo();
  34444. if (!boundingInfo) {
  34445. return false;
  34446. }
  34447. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34448. };
  34449. /**
  34450. * Renders the submesh.
  34451. * Returns it.
  34452. */
  34453. SubMesh.prototype.render = function (enableAlphaMode) {
  34454. this._renderingMesh.render(this, enableAlphaMode);
  34455. return this;
  34456. };
  34457. /**
  34458. * Returns a new Index Buffer.
  34459. * Type returned : WebGLBuffer.
  34460. */
  34461. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34462. if (!this._linesIndexBuffer) {
  34463. var linesIndices = [];
  34464. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34465. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34466. }
  34467. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34468. this.linesIndexCount = linesIndices.length;
  34469. }
  34470. return this._linesIndexBuffer;
  34471. };
  34472. /**
  34473. * True is the passed Ray intersects the submesh bounding box.
  34474. * Boolean returned.
  34475. */
  34476. SubMesh.prototype.canIntersects = function (ray) {
  34477. var boundingInfo = this.getBoundingInfo();
  34478. if (!boundingInfo) {
  34479. return false;
  34480. }
  34481. return ray.intersectsBox(boundingInfo.boundingBox);
  34482. };
  34483. /**
  34484. * Returns an object IntersectionInfo.
  34485. */
  34486. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34487. var intersectInfo = null;
  34488. var material = this.getMaterial();
  34489. if (!material) {
  34490. return null;
  34491. }
  34492. switch (material.fillMode) {
  34493. case BABYLON.Material.PointListDrawMode:
  34494. case BABYLON.Material.LineListDrawMode:
  34495. case BABYLON.Material.LineLoopDrawMode:
  34496. case BABYLON.Material.LineStripDrawMode:
  34497. case BABYLON.Material.TriangleFanDrawMode:
  34498. case BABYLON.Material.TriangleStripDrawMode:
  34499. return null;
  34500. }
  34501. // LineMesh first as it's also a Mesh...
  34502. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34503. var lineMesh = this._mesh;
  34504. // Line test
  34505. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34506. var p0 = positions[indices[index]];
  34507. var p1 = positions[indices[index + 1]];
  34508. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34509. if (length < 0) {
  34510. continue;
  34511. }
  34512. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34513. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34514. if (fastCheck) {
  34515. break;
  34516. }
  34517. }
  34518. }
  34519. }
  34520. else {
  34521. // Triangles test
  34522. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34523. var p0 = positions[indices[index]];
  34524. var p1 = positions[indices[index + 1]];
  34525. var p2 = positions[indices[index + 2]];
  34526. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34527. if (currentIntersectInfo) {
  34528. if (currentIntersectInfo.distance < 0) {
  34529. continue;
  34530. }
  34531. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34532. intersectInfo = currentIntersectInfo;
  34533. intersectInfo.faceId = index / 3;
  34534. if (fastCheck) {
  34535. break;
  34536. }
  34537. }
  34538. }
  34539. }
  34540. }
  34541. return intersectInfo;
  34542. };
  34543. /** @hidden */
  34544. SubMesh.prototype._rebuild = function () {
  34545. if (this._linesIndexBuffer) {
  34546. this._linesIndexBuffer = null;
  34547. }
  34548. };
  34549. // Clone
  34550. /**
  34551. * Creates a new Submesh from the passed Mesh.
  34552. */
  34553. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34554. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34555. if (!this.IsGlobal) {
  34556. var boundingInfo = this.getBoundingInfo();
  34557. if (!boundingInfo) {
  34558. return result;
  34559. }
  34560. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34561. }
  34562. return result;
  34563. };
  34564. // Dispose
  34565. /**
  34566. * Disposes the Submesh.
  34567. * Returns nothing.
  34568. */
  34569. SubMesh.prototype.dispose = function () {
  34570. if (this._linesIndexBuffer) {
  34571. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34572. this._linesIndexBuffer = null;
  34573. }
  34574. // Remove from mesh
  34575. var index = this._mesh.subMeshes.indexOf(this);
  34576. this._mesh.subMeshes.splice(index, 1);
  34577. };
  34578. // Statics
  34579. /**
  34580. * Creates a new Submesh from the passed parameters :
  34581. * - materialIndex (integer) : the index of the main mesh material.
  34582. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34583. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34584. * - mesh (Mesh) : the main mesh to create the submesh from.
  34585. * - renderingMesh (optional Mesh) : rendering mesh.
  34586. */
  34587. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34588. var minVertexIndex = Number.MAX_VALUE;
  34589. var maxVertexIndex = -Number.MAX_VALUE;
  34590. renderingMesh = (renderingMesh || mesh);
  34591. var indices = renderingMesh.getIndices();
  34592. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34593. var vertexIndex = indices[index];
  34594. if (vertexIndex < minVertexIndex)
  34595. minVertexIndex = vertexIndex;
  34596. if (vertexIndex > maxVertexIndex)
  34597. maxVertexIndex = vertexIndex;
  34598. }
  34599. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34600. };
  34601. return SubMesh;
  34602. }(BaseSubMesh));
  34603. BABYLON.SubMesh = SubMesh;
  34604. })(BABYLON || (BABYLON = {}));
  34605. //# sourceMappingURL=babylon.subMesh.js.map
  34606. var __assign = (this && this.__assign) || function () {
  34607. __assign = Object.assign || function(t) {
  34608. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34609. s = arguments[i];
  34610. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34611. t[p] = s[p];
  34612. }
  34613. return t;
  34614. };
  34615. return __assign.apply(this, arguments);
  34616. };
  34617. var BABYLON;
  34618. (function (BABYLON) {
  34619. /**
  34620. * Manages the defines for the Material
  34621. */
  34622. var MaterialDefines = /** @class */ (function () {
  34623. function MaterialDefines() {
  34624. this._isDirty = true;
  34625. /** @hidden */
  34626. this._areLightsDirty = true;
  34627. /** @hidden */
  34628. this._areAttributesDirty = true;
  34629. /** @hidden */
  34630. this._areTexturesDirty = true;
  34631. /** @hidden */
  34632. this._areFresnelDirty = true;
  34633. /** @hidden */
  34634. this._areMiscDirty = true;
  34635. /** @hidden */
  34636. this._areImageProcessingDirty = true;
  34637. /** @hidden */
  34638. this._normals = false;
  34639. /** @hidden */
  34640. this._uvs = false;
  34641. /** @hidden */
  34642. this._needNormals = false;
  34643. /** @hidden */
  34644. this._needUVs = false;
  34645. }
  34646. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34647. /**
  34648. * Specifies if the material needs to be re-calculated
  34649. */
  34650. get: function () {
  34651. return this._isDirty;
  34652. },
  34653. enumerable: true,
  34654. configurable: true
  34655. });
  34656. /**
  34657. * Marks the material to indicate that it has been re-calculated
  34658. */
  34659. MaterialDefines.prototype.markAsProcessed = function () {
  34660. this._isDirty = false;
  34661. this._areAttributesDirty = false;
  34662. this._areTexturesDirty = false;
  34663. this._areFresnelDirty = false;
  34664. this._areLightsDirty = false;
  34665. this._areMiscDirty = false;
  34666. this._areImageProcessingDirty = false;
  34667. };
  34668. /**
  34669. * Marks the material to indicate that it needs to be re-calculated
  34670. */
  34671. MaterialDefines.prototype.markAsUnprocessed = function () {
  34672. this._isDirty = true;
  34673. };
  34674. /**
  34675. * Marks the material to indicate all of its defines need to be re-calculated
  34676. */
  34677. MaterialDefines.prototype.markAllAsDirty = function () {
  34678. this._areTexturesDirty = true;
  34679. this._areAttributesDirty = true;
  34680. this._areLightsDirty = true;
  34681. this._areFresnelDirty = true;
  34682. this._areMiscDirty = true;
  34683. this._areImageProcessingDirty = true;
  34684. this._isDirty = true;
  34685. };
  34686. /**
  34687. * Marks the material to indicate that image processing needs to be re-calculated
  34688. */
  34689. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34690. this._areImageProcessingDirty = true;
  34691. this._isDirty = true;
  34692. };
  34693. /**
  34694. * Marks the material to indicate the lights need to be re-calculated
  34695. */
  34696. MaterialDefines.prototype.markAsLightDirty = function () {
  34697. this._areLightsDirty = true;
  34698. this._isDirty = true;
  34699. };
  34700. /**
  34701. * Marks the attribute state as changed
  34702. */
  34703. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34704. this._areAttributesDirty = true;
  34705. this._isDirty = true;
  34706. };
  34707. /**
  34708. * Marks the texture state as changed
  34709. */
  34710. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34711. this._areTexturesDirty = true;
  34712. this._isDirty = true;
  34713. };
  34714. /**
  34715. * Marks the fresnel state as changed
  34716. */
  34717. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34718. this._areFresnelDirty = true;
  34719. this._isDirty = true;
  34720. };
  34721. /**
  34722. * Marks the misc state as changed
  34723. */
  34724. MaterialDefines.prototype.markAsMiscDirty = function () {
  34725. this._areMiscDirty = true;
  34726. this._isDirty = true;
  34727. };
  34728. /**
  34729. * Rebuilds the material defines
  34730. */
  34731. MaterialDefines.prototype.rebuild = function () {
  34732. if (this._keys) {
  34733. delete this._keys;
  34734. }
  34735. this._keys = [];
  34736. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34737. var key = _a[_i];
  34738. if (key[0] === "_") {
  34739. continue;
  34740. }
  34741. this._keys.push(key);
  34742. }
  34743. };
  34744. /**
  34745. * Specifies if two material defines are equal
  34746. * @param other - A material define instance to compare to
  34747. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34748. */
  34749. MaterialDefines.prototype.isEqual = function (other) {
  34750. if (this._keys.length !== other._keys.length) {
  34751. return false;
  34752. }
  34753. for (var index = 0; index < this._keys.length; index++) {
  34754. var prop = this._keys[index];
  34755. if (this[prop] !== other[prop]) {
  34756. return false;
  34757. }
  34758. }
  34759. return true;
  34760. };
  34761. /**
  34762. * Clones this instance's defines to another instance
  34763. * @param other - material defines to clone values to
  34764. */
  34765. MaterialDefines.prototype.cloneTo = function (other) {
  34766. if (this._keys.length !== other._keys.length) {
  34767. other._keys = this._keys.slice(0);
  34768. }
  34769. for (var index = 0; index < this._keys.length; index++) {
  34770. var prop = this._keys[index];
  34771. other[prop] = this[prop];
  34772. }
  34773. };
  34774. /**
  34775. * Resets the material define values
  34776. */
  34777. MaterialDefines.prototype.reset = function () {
  34778. for (var index = 0; index < this._keys.length; index++) {
  34779. var prop = this._keys[index];
  34780. var type = typeof this[prop];
  34781. switch (type) {
  34782. case "number":
  34783. this[prop] = 0;
  34784. break;
  34785. case "string":
  34786. this[prop] = "";
  34787. break;
  34788. default:
  34789. this[prop] = false;
  34790. break;
  34791. }
  34792. }
  34793. };
  34794. /**
  34795. * Converts the material define values to a string
  34796. * @returns - String of material define information
  34797. */
  34798. MaterialDefines.prototype.toString = function () {
  34799. var result = "";
  34800. for (var index = 0; index < this._keys.length; index++) {
  34801. var prop = this._keys[index];
  34802. var value = this[prop];
  34803. var type = typeof value;
  34804. switch (type) {
  34805. case "number":
  34806. case "string":
  34807. result += "#define " + prop + " " + value + "\n";
  34808. break;
  34809. default:
  34810. if (value) {
  34811. result += "#define " + prop + "\n";
  34812. }
  34813. break;
  34814. }
  34815. }
  34816. return result;
  34817. };
  34818. return MaterialDefines;
  34819. }());
  34820. BABYLON.MaterialDefines = MaterialDefines;
  34821. /**
  34822. * Base class for the main features of a material in Babylon.js
  34823. */
  34824. var Material = /** @class */ (function () {
  34825. /**
  34826. * Creates a material instance
  34827. * @param name defines the name of the material
  34828. * @param scene defines the scene to reference
  34829. * @param doNotAdd specifies if the material should be added to the scene
  34830. */
  34831. function Material(name, scene, doNotAdd) {
  34832. /**
  34833. * Specifies if the ready state should be checked on each call
  34834. */
  34835. this.checkReadyOnEveryCall = false;
  34836. /**
  34837. * Specifies if the ready state should be checked once
  34838. */
  34839. this.checkReadyOnlyOnce = false;
  34840. /**
  34841. * The state of the material
  34842. */
  34843. this.state = "";
  34844. /**
  34845. * The alpha value of the material
  34846. */
  34847. this._alpha = 1.0;
  34848. /**
  34849. * Specifies if back face culling is enabled
  34850. */
  34851. this._backFaceCulling = true;
  34852. /**
  34853. * Specifies if the material should be serialized
  34854. */
  34855. this.doNotSerialize = false;
  34856. /**
  34857. * Specifies if the effect should be stored on sub meshes
  34858. */
  34859. this.storeEffectOnSubMeshes = false;
  34860. /**
  34861. * An event triggered when the material is disposed
  34862. */
  34863. this.onDisposeObservable = new BABYLON.Observable();
  34864. /**
  34865. * Stores the value of the alpha mode
  34866. */
  34867. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34868. /**
  34869. * Stores the state of the need depth pre-pass value
  34870. */
  34871. this._needDepthPrePass = false;
  34872. /**
  34873. * Specifies if depth writing should be disabled
  34874. */
  34875. this.disableDepthWrite = false;
  34876. /**
  34877. * Specifies if depth writing should be forced
  34878. */
  34879. this.forceDepthWrite = false;
  34880. /**
  34881. * Specifies if there should be a separate pass for culling
  34882. */
  34883. this.separateCullingPass = false;
  34884. /**
  34885. * Stores the state specifing if fog should be enabled
  34886. */
  34887. this._fogEnabled = true;
  34888. /**
  34889. * Stores the size of points
  34890. */
  34891. this.pointSize = 1.0;
  34892. /**
  34893. * Stores the z offset value
  34894. */
  34895. this.zOffset = 0;
  34896. /**
  34897. * @hidden
  34898. * Specifies if the material was previously ready
  34899. */
  34900. this._wasPreviouslyReady = false;
  34901. /**
  34902. * Stores the fill mode state
  34903. */
  34904. this._fillMode = Material.TriangleFillMode;
  34905. this.name = name;
  34906. this.id = name || BABYLON.Tools.RandomId();
  34907. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34908. this.uniqueId = this._scene.getUniqueId();
  34909. if (this._scene.useRightHandedSystem) {
  34910. this.sideOrientation = Material.ClockWiseSideOrientation;
  34911. }
  34912. else {
  34913. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34914. }
  34915. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34916. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34917. if (!doNotAdd) {
  34918. this._scene.materials.push(this);
  34919. }
  34920. }
  34921. Object.defineProperty(Material, "TriangleFillMode", {
  34922. /**
  34923. * Returns the triangle fill mode
  34924. */
  34925. get: function () {
  34926. return Material._TriangleFillMode;
  34927. },
  34928. enumerable: true,
  34929. configurable: true
  34930. });
  34931. Object.defineProperty(Material, "WireFrameFillMode", {
  34932. /**
  34933. * Returns the wireframe mode
  34934. */
  34935. get: function () {
  34936. return Material._WireFrameFillMode;
  34937. },
  34938. enumerable: true,
  34939. configurable: true
  34940. });
  34941. Object.defineProperty(Material, "PointFillMode", {
  34942. /**
  34943. * Returns the point fill mode
  34944. */
  34945. get: function () {
  34946. return Material._PointFillMode;
  34947. },
  34948. enumerable: true,
  34949. configurable: true
  34950. });
  34951. Object.defineProperty(Material, "PointListDrawMode", {
  34952. /**
  34953. * Returns the point list draw mode
  34954. */
  34955. get: function () {
  34956. return Material._PointListDrawMode;
  34957. },
  34958. enumerable: true,
  34959. configurable: true
  34960. });
  34961. Object.defineProperty(Material, "LineListDrawMode", {
  34962. /**
  34963. * Returns the line list draw mode
  34964. */
  34965. get: function () {
  34966. return Material._LineListDrawMode;
  34967. },
  34968. enumerable: true,
  34969. configurable: true
  34970. });
  34971. Object.defineProperty(Material, "LineLoopDrawMode", {
  34972. /**
  34973. * Returns the line loop draw mode
  34974. */
  34975. get: function () {
  34976. return Material._LineLoopDrawMode;
  34977. },
  34978. enumerable: true,
  34979. configurable: true
  34980. });
  34981. Object.defineProperty(Material, "LineStripDrawMode", {
  34982. /**
  34983. * Returns the line strip draw mode
  34984. */
  34985. get: function () {
  34986. return Material._LineStripDrawMode;
  34987. },
  34988. enumerable: true,
  34989. configurable: true
  34990. });
  34991. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34992. /**
  34993. * Returns the triangle strip draw mode
  34994. */
  34995. get: function () {
  34996. return Material._TriangleStripDrawMode;
  34997. },
  34998. enumerable: true,
  34999. configurable: true
  35000. });
  35001. Object.defineProperty(Material, "TriangleFanDrawMode", {
  35002. /**
  35003. * Returns the triangle fan draw mode
  35004. */
  35005. get: function () {
  35006. return Material._TriangleFanDrawMode;
  35007. },
  35008. enumerable: true,
  35009. configurable: true
  35010. });
  35011. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  35012. /**
  35013. * Returns the clock-wise side orientation
  35014. */
  35015. get: function () {
  35016. return Material._ClockWiseSideOrientation;
  35017. },
  35018. enumerable: true,
  35019. configurable: true
  35020. });
  35021. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  35022. /**
  35023. * Returns the counter clock-wise side orientation
  35024. */
  35025. get: function () {
  35026. return Material._CounterClockWiseSideOrientation;
  35027. },
  35028. enumerable: true,
  35029. configurable: true
  35030. });
  35031. Object.defineProperty(Material, "TextureDirtyFlag", {
  35032. /**
  35033. * Returns the dirty texture flag value
  35034. */
  35035. get: function () {
  35036. return Material._TextureDirtyFlag;
  35037. },
  35038. enumerable: true,
  35039. configurable: true
  35040. });
  35041. Object.defineProperty(Material, "LightDirtyFlag", {
  35042. /**
  35043. * Returns the dirty light flag value
  35044. */
  35045. get: function () {
  35046. return Material._LightDirtyFlag;
  35047. },
  35048. enumerable: true,
  35049. configurable: true
  35050. });
  35051. Object.defineProperty(Material, "FresnelDirtyFlag", {
  35052. /**
  35053. * Returns the dirty fresnel flag value
  35054. */
  35055. get: function () {
  35056. return Material._FresnelDirtyFlag;
  35057. },
  35058. enumerable: true,
  35059. configurable: true
  35060. });
  35061. Object.defineProperty(Material, "AttributesDirtyFlag", {
  35062. /**
  35063. * Returns the dirty attributes flag value
  35064. */
  35065. get: function () {
  35066. return Material._AttributesDirtyFlag;
  35067. },
  35068. enumerable: true,
  35069. configurable: true
  35070. });
  35071. Object.defineProperty(Material, "MiscDirtyFlag", {
  35072. /**
  35073. * Returns the dirty misc flag value
  35074. */
  35075. get: function () {
  35076. return Material._MiscDirtyFlag;
  35077. },
  35078. enumerable: true,
  35079. configurable: true
  35080. });
  35081. Object.defineProperty(Material.prototype, "alpha", {
  35082. /**
  35083. * Gets the alpha value of the material
  35084. */
  35085. get: function () {
  35086. return this._alpha;
  35087. },
  35088. /**
  35089. * Sets the alpha value of the material
  35090. */
  35091. set: function (value) {
  35092. if (this._alpha === value) {
  35093. return;
  35094. }
  35095. this._alpha = value;
  35096. this.markAsDirty(Material.MiscDirtyFlag);
  35097. },
  35098. enumerable: true,
  35099. configurable: true
  35100. });
  35101. Object.defineProperty(Material.prototype, "backFaceCulling", {
  35102. /**
  35103. * Gets the back-face culling state
  35104. */
  35105. get: function () {
  35106. return this._backFaceCulling;
  35107. },
  35108. /**
  35109. * Sets the back-face culling state
  35110. */
  35111. set: function (value) {
  35112. if (this._backFaceCulling === value) {
  35113. return;
  35114. }
  35115. this._backFaceCulling = value;
  35116. this.markAsDirty(Material.TextureDirtyFlag);
  35117. },
  35118. enumerable: true,
  35119. configurable: true
  35120. });
  35121. Object.defineProperty(Material.prototype, "onDispose", {
  35122. /**
  35123. * Called during a dispose event
  35124. */
  35125. set: function (callback) {
  35126. if (this._onDisposeObserver) {
  35127. this.onDisposeObservable.remove(this._onDisposeObserver);
  35128. }
  35129. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35130. },
  35131. enumerable: true,
  35132. configurable: true
  35133. });
  35134. Object.defineProperty(Material.prototype, "onBindObservable", {
  35135. /**
  35136. * An event triggered when the material is bound
  35137. */
  35138. get: function () {
  35139. if (!this._onBindObservable) {
  35140. this._onBindObservable = new BABYLON.Observable();
  35141. }
  35142. return this._onBindObservable;
  35143. },
  35144. enumerable: true,
  35145. configurable: true
  35146. });
  35147. Object.defineProperty(Material.prototype, "onBind", {
  35148. /**
  35149. * Called during a bind event
  35150. */
  35151. set: function (callback) {
  35152. if (this._onBindObserver) {
  35153. this.onBindObservable.remove(this._onBindObserver);
  35154. }
  35155. this._onBindObserver = this.onBindObservable.add(callback);
  35156. },
  35157. enumerable: true,
  35158. configurable: true
  35159. });
  35160. Object.defineProperty(Material.prototype, "onUnBindObservable", {
  35161. /**
  35162. * An event triggered when the material is unbound
  35163. */
  35164. get: function () {
  35165. if (!this._onUnBindObservable) {
  35166. this._onUnBindObservable = new BABYLON.Observable();
  35167. }
  35168. return this._onUnBindObservable;
  35169. },
  35170. enumerable: true,
  35171. configurable: true
  35172. });
  35173. Object.defineProperty(Material.prototype, "alphaMode", {
  35174. /**
  35175. * Gets the value of the alpha mode
  35176. */
  35177. get: function () {
  35178. return this._alphaMode;
  35179. },
  35180. /**
  35181. * Sets the value of the alpha mode.
  35182. *
  35183. * | Value | Type | Description |
  35184. * | --- | --- | --- |
  35185. * | 0 | ALPHA_DISABLE | |
  35186. * | 1 | ALPHA_ADD | |
  35187. * | 2 | ALPHA_COMBINE | |
  35188. * | 3 | ALPHA_SUBTRACT | |
  35189. * | 4 | ALPHA_MULTIPLY | |
  35190. * | 5 | ALPHA_MAXIMIZED | |
  35191. * | 6 | ALPHA_ONEONE | |
  35192. * | 7 | ALPHA_PREMULTIPLIED | |
  35193. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35194. * | 9 | ALPHA_INTERPOLATE | |
  35195. * | 10 | ALPHA_SCREENMODE | |
  35196. *
  35197. */
  35198. set: function (value) {
  35199. if (this._alphaMode === value) {
  35200. return;
  35201. }
  35202. this._alphaMode = value;
  35203. this.markAsDirty(Material.TextureDirtyFlag);
  35204. },
  35205. enumerable: true,
  35206. configurable: true
  35207. });
  35208. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35209. /**
  35210. * Gets the depth pre-pass value
  35211. */
  35212. get: function () {
  35213. return this._needDepthPrePass;
  35214. },
  35215. /**
  35216. * Sets the need depth pre-pass value
  35217. */
  35218. set: function (value) {
  35219. if (this._needDepthPrePass === value) {
  35220. return;
  35221. }
  35222. this._needDepthPrePass = value;
  35223. if (this._needDepthPrePass) {
  35224. this.checkReadyOnEveryCall = true;
  35225. }
  35226. },
  35227. enumerable: true,
  35228. configurable: true
  35229. });
  35230. Object.defineProperty(Material.prototype, "fogEnabled", {
  35231. /**
  35232. * Gets the value of the fog enabled state
  35233. */
  35234. get: function () {
  35235. return this._fogEnabled;
  35236. },
  35237. /**
  35238. * Sets the state for enabling fog
  35239. */
  35240. set: function (value) {
  35241. if (this._fogEnabled === value) {
  35242. return;
  35243. }
  35244. this._fogEnabled = value;
  35245. this.markAsDirty(Material.MiscDirtyFlag);
  35246. },
  35247. enumerable: true,
  35248. configurable: true
  35249. });
  35250. Object.defineProperty(Material.prototype, "wireframe", {
  35251. /**
  35252. * Gets a value specifying if wireframe mode is enabled
  35253. */
  35254. get: function () {
  35255. switch (this._fillMode) {
  35256. case Material.WireFrameFillMode:
  35257. case Material.LineListDrawMode:
  35258. case Material.LineLoopDrawMode:
  35259. case Material.LineStripDrawMode:
  35260. return true;
  35261. }
  35262. return this._scene.forceWireframe;
  35263. },
  35264. /**
  35265. * Sets the state of wireframe mode
  35266. */
  35267. set: function (value) {
  35268. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35269. },
  35270. enumerable: true,
  35271. configurable: true
  35272. });
  35273. Object.defineProperty(Material.prototype, "pointsCloud", {
  35274. /**
  35275. * Gets the value specifying if point clouds are enabled
  35276. */
  35277. get: function () {
  35278. switch (this._fillMode) {
  35279. case Material.PointFillMode:
  35280. case Material.PointListDrawMode:
  35281. return true;
  35282. }
  35283. return this._scene.forcePointsCloud;
  35284. },
  35285. /**
  35286. * Sets the state of point cloud mode
  35287. */
  35288. set: function (value) {
  35289. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35290. },
  35291. enumerable: true,
  35292. configurable: true
  35293. });
  35294. Object.defineProperty(Material.prototype, "fillMode", {
  35295. /**
  35296. * Gets the material fill mode
  35297. */
  35298. get: function () {
  35299. return this._fillMode;
  35300. },
  35301. /**
  35302. * Sets the material fill mode
  35303. */
  35304. set: function (value) {
  35305. if (this._fillMode === value) {
  35306. return;
  35307. }
  35308. this._fillMode = value;
  35309. this.markAsDirty(Material.MiscDirtyFlag);
  35310. },
  35311. enumerable: true,
  35312. configurable: true
  35313. });
  35314. /**
  35315. * Returns a string representation of the current material
  35316. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35317. * @returns a string with material information
  35318. */
  35319. Material.prototype.toString = function (fullDetails) {
  35320. var ret = "Name: " + this.name;
  35321. if (fullDetails) {
  35322. }
  35323. return ret;
  35324. };
  35325. /**
  35326. * Gets the class name of the material
  35327. * @returns a string with the class name of the material
  35328. */
  35329. Material.prototype.getClassName = function () {
  35330. return "Material";
  35331. };
  35332. Object.defineProperty(Material.prototype, "isFrozen", {
  35333. /**
  35334. * Specifies if updates for the material been locked
  35335. */
  35336. get: function () {
  35337. return this.checkReadyOnlyOnce;
  35338. },
  35339. enumerable: true,
  35340. configurable: true
  35341. });
  35342. /**
  35343. * Locks updates for the material
  35344. */
  35345. Material.prototype.freeze = function () {
  35346. this.checkReadyOnlyOnce = true;
  35347. };
  35348. /**
  35349. * Unlocks updates for the material
  35350. */
  35351. Material.prototype.unfreeze = function () {
  35352. this.checkReadyOnlyOnce = false;
  35353. };
  35354. /**
  35355. * Specifies if the material is ready to be used
  35356. * @param mesh defines the mesh to check
  35357. * @param useInstances specifies if instances should be used
  35358. * @returns a boolean indicating if the material is ready to be used
  35359. */
  35360. Material.prototype.isReady = function (mesh, useInstances) {
  35361. return true;
  35362. };
  35363. /**
  35364. * Specifies that the submesh is ready to be used
  35365. * @param mesh defines the mesh to check
  35366. * @param subMesh defines which submesh to check
  35367. * @param useInstances specifies that instances should be used
  35368. * @returns a boolean indicating that the submesh is ready or not
  35369. */
  35370. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35371. return false;
  35372. };
  35373. /**
  35374. * Returns the material effect
  35375. * @returns the effect associated with the material
  35376. */
  35377. Material.prototype.getEffect = function () {
  35378. return this._effect;
  35379. };
  35380. /**
  35381. * Returns the current scene
  35382. * @returns a Scene
  35383. */
  35384. Material.prototype.getScene = function () {
  35385. return this._scene;
  35386. };
  35387. /**
  35388. * Specifies if the material will require alpha blending
  35389. * @returns a boolean specifying if alpha blending is needed
  35390. */
  35391. Material.prototype.needAlphaBlending = function () {
  35392. return (this.alpha < 1.0);
  35393. };
  35394. /**
  35395. * Specifies if the mesh will require alpha blending
  35396. * @param mesh defines the mesh to check
  35397. * @returns a boolean specifying if alpha blending is needed for the mesh
  35398. */
  35399. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35400. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35401. };
  35402. /**
  35403. * Specifies if this material should be rendered in alpha test mode
  35404. * @returns a boolean specifying if an alpha test is needed.
  35405. */
  35406. Material.prototype.needAlphaTesting = function () {
  35407. return false;
  35408. };
  35409. /**
  35410. * Gets the texture used for the alpha test
  35411. * @returns the texture to use for alpha testing
  35412. */
  35413. Material.prototype.getAlphaTestTexture = function () {
  35414. return null;
  35415. };
  35416. /**
  35417. * Marks the material to indicate that it needs to be re-calculated
  35418. */
  35419. Material.prototype.markDirty = function () {
  35420. this._wasPreviouslyReady = false;
  35421. };
  35422. /** @hidden */
  35423. Material.prototype._preBind = function (effect, overrideOrientation) {
  35424. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35425. var engine = this._scene.getEngine();
  35426. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35427. var reverse = orientation === Material.ClockWiseSideOrientation;
  35428. engine.enableEffect(effect ? effect : this._effect);
  35429. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35430. return reverse;
  35431. };
  35432. /**
  35433. * Binds the material to the mesh
  35434. * @param world defines the world transformation matrix
  35435. * @param mesh defines the mesh to bind the material to
  35436. */
  35437. Material.prototype.bind = function (world, mesh) {
  35438. };
  35439. /**
  35440. * Binds the submesh to the material
  35441. * @param world defines the world transformation matrix
  35442. * @param mesh defines the mesh containing the submesh
  35443. * @param subMesh defines the submesh to bind the material to
  35444. */
  35445. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35446. };
  35447. /**
  35448. * Binds the world matrix to the material
  35449. * @param world defines the world transformation matrix
  35450. */
  35451. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35452. };
  35453. /**
  35454. * Binds the scene's uniform buffer to the effect.
  35455. * @param effect defines the effect to bind to the scene uniform buffer
  35456. * @param sceneUbo defines the uniform buffer storing scene data
  35457. */
  35458. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35459. sceneUbo.bindToEffect(effect, "Scene");
  35460. };
  35461. /**
  35462. * Binds the view matrix to the effect
  35463. * @param effect defines the effect to bind the view matrix to
  35464. */
  35465. Material.prototype.bindView = function (effect) {
  35466. if (!this._useUBO) {
  35467. effect.setMatrix("view", this.getScene().getViewMatrix());
  35468. }
  35469. else {
  35470. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35471. }
  35472. };
  35473. /**
  35474. * Binds the view projection matrix to the effect
  35475. * @param effect defines the effect to bind the view projection matrix to
  35476. */
  35477. Material.prototype.bindViewProjection = function (effect) {
  35478. if (!this._useUBO) {
  35479. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35480. }
  35481. else {
  35482. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35483. }
  35484. };
  35485. /**
  35486. * Specifies if material alpha testing should be turned on for the mesh
  35487. * @param mesh defines the mesh to check
  35488. */
  35489. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35490. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35491. };
  35492. /**
  35493. * Processes to execute after binding the material to a mesh
  35494. * @param mesh defines the rendered mesh
  35495. */
  35496. Material.prototype._afterBind = function (mesh) {
  35497. this._scene._cachedMaterial = this;
  35498. if (mesh) {
  35499. this._scene._cachedVisibility = mesh.visibility;
  35500. }
  35501. else {
  35502. this._scene._cachedVisibility = 1;
  35503. }
  35504. if (this._onBindObservable && mesh) {
  35505. this._onBindObservable.notifyObservers(mesh);
  35506. }
  35507. if (this.disableDepthWrite) {
  35508. var engine = this._scene.getEngine();
  35509. this._cachedDepthWriteState = engine.getDepthWrite();
  35510. engine.setDepthWrite(false);
  35511. }
  35512. };
  35513. /**
  35514. * Unbinds the material from the mesh
  35515. */
  35516. Material.prototype.unbind = function () {
  35517. if (this._onUnBindObservable) {
  35518. this._onUnBindObservable.notifyObservers(this);
  35519. }
  35520. if (this.disableDepthWrite) {
  35521. var engine = this._scene.getEngine();
  35522. engine.setDepthWrite(this._cachedDepthWriteState);
  35523. }
  35524. };
  35525. /**
  35526. * Gets the active textures from the material
  35527. * @returns an array of textures
  35528. */
  35529. Material.prototype.getActiveTextures = function () {
  35530. return [];
  35531. };
  35532. /**
  35533. * Specifies if the material uses a texture
  35534. * @param texture defines the texture to check against the material
  35535. * @returns a boolean specifying if the material uses the texture
  35536. */
  35537. Material.prototype.hasTexture = function (texture) {
  35538. return false;
  35539. };
  35540. /**
  35541. * Makes a duplicate of the material, and gives it a new name
  35542. * @param name defines the new name for the duplicated material
  35543. * @returns the cloned material
  35544. */
  35545. Material.prototype.clone = function (name) {
  35546. return null;
  35547. };
  35548. /**
  35549. * Gets the meshes bound to the material
  35550. * @returns an array of meshes bound to the material
  35551. */
  35552. Material.prototype.getBindedMeshes = function () {
  35553. var result = new Array();
  35554. for (var index = 0; index < this._scene.meshes.length; index++) {
  35555. var mesh = this._scene.meshes[index];
  35556. if (mesh.material === this) {
  35557. result.push(mesh);
  35558. }
  35559. }
  35560. return result;
  35561. };
  35562. /**
  35563. * Force shader compilation
  35564. * @param mesh defines the mesh associated with this material
  35565. * @param onCompiled defines a function to execute once the material is compiled
  35566. * @param options defines the options to configure the compilation
  35567. */
  35568. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35569. var _this = this;
  35570. var localOptions = __assign({ clipPlane: false }, options);
  35571. var subMesh = new BABYLON.BaseSubMesh();
  35572. var scene = this.getScene();
  35573. var checkReady = function () {
  35574. if (!_this._scene || !_this._scene.getEngine()) {
  35575. return;
  35576. }
  35577. if (subMesh._materialDefines) {
  35578. subMesh._materialDefines._renderId = -1;
  35579. }
  35580. var clipPlaneState = scene.clipPlane;
  35581. if (localOptions.clipPlane) {
  35582. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35583. }
  35584. if (_this.storeEffectOnSubMeshes) {
  35585. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35586. if (onCompiled) {
  35587. onCompiled(_this);
  35588. }
  35589. }
  35590. else {
  35591. setTimeout(checkReady, 16);
  35592. }
  35593. }
  35594. else {
  35595. if (_this.isReady(mesh)) {
  35596. if (onCompiled) {
  35597. onCompiled(_this);
  35598. }
  35599. }
  35600. else {
  35601. setTimeout(checkReady, 16);
  35602. }
  35603. }
  35604. if (localOptions.clipPlane) {
  35605. scene.clipPlane = clipPlaneState;
  35606. }
  35607. };
  35608. checkReady();
  35609. };
  35610. /**
  35611. * Force shader compilation
  35612. * @param mesh defines the mesh that will use this material
  35613. * @param options defines additional options for compiling the shaders
  35614. * @returns a promise that resolves when the compilation completes
  35615. */
  35616. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35617. var _this = this;
  35618. return new Promise(function (resolve) {
  35619. _this.forceCompilation(mesh, function () {
  35620. resolve();
  35621. }, options);
  35622. });
  35623. };
  35624. /**
  35625. * Marks a define in the material to indicate that it needs to be re-computed
  35626. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35627. */
  35628. Material.prototype.markAsDirty = function (flag) {
  35629. if (flag & Material.TextureDirtyFlag) {
  35630. this._markAllSubMeshesAsTexturesDirty();
  35631. }
  35632. if (flag & Material.LightDirtyFlag) {
  35633. this._markAllSubMeshesAsLightsDirty();
  35634. }
  35635. if (flag & Material.FresnelDirtyFlag) {
  35636. this._markAllSubMeshesAsFresnelDirty();
  35637. }
  35638. if (flag & Material.AttributesDirtyFlag) {
  35639. this._markAllSubMeshesAsAttributesDirty();
  35640. }
  35641. if (flag & Material.MiscDirtyFlag) {
  35642. this._markAllSubMeshesAsMiscDirty();
  35643. }
  35644. this.getScene().resetCachedMaterial();
  35645. };
  35646. /**
  35647. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35648. * @param func defines a function which checks material defines against the submeshes
  35649. */
  35650. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35651. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35652. var mesh = _a[_i];
  35653. if (!mesh.subMeshes) {
  35654. continue;
  35655. }
  35656. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35657. var subMesh = _c[_b];
  35658. if (subMesh.getMaterial() !== this) {
  35659. continue;
  35660. }
  35661. if (!subMesh._materialDefines) {
  35662. continue;
  35663. }
  35664. func(subMesh._materialDefines);
  35665. }
  35666. }
  35667. };
  35668. /**
  35669. * Indicates that image processing needs to be re-calculated for all submeshes
  35670. */
  35671. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35672. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35673. };
  35674. /**
  35675. * Indicates that textures need to be re-calculated for all submeshes
  35676. */
  35677. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35678. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35679. };
  35680. /**
  35681. * Indicates that fresnel needs to be re-calculated for all submeshes
  35682. */
  35683. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35684. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35685. };
  35686. /**
  35687. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35688. */
  35689. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35690. this._markAllSubMeshesAsDirty(function (defines) {
  35691. defines.markAsFresnelDirty();
  35692. defines.markAsMiscDirty();
  35693. });
  35694. };
  35695. /**
  35696. * Indicates that lights need to be re-calculated for all submeshes
  35697. */
  35698. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35699. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35700. };
  35701. /**
  35702. * Indicates that attributes need to be re-calculated for all submeshes
  35703. */
  35704. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35705. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35706. };
  35707. /**
  35708. * Indicates that misc needs to be re-calculated for all submeshes
  35709. */
  35710. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35711. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35712. };
  35713. /**
  35714. * Indicates that textures and misc need to be re-calculated for all submeshes
  35715. */
  35716. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35717. this._markAllSubMeshesAsDirty(function (defines) {
  35718. defines.markAsTexturesDirty();
  35719. defines.markAsMiscDirty();
  35720. });
  35721. };
  35722. /**
  35723. * Disposes the material
  35724. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35725. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35726. */
  35727. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35728. // Animations
  35729. this.getScene().stopAnimation(this);
  35730. this.getScene().freeProcessedMaterials();
  35731. // Remove from scene
  35732. var index = this._scene.materials.indexOf(this);
  35733. if (index >= 0) {
  35734. this._scene.materials.splice(index, 1);
  35735. }
  35736. // Remove from meshes
  35737. for (index = 0; index < this._scene.meshes.length; index++) {
  35738. var mesh = this._scene.meshes[index];
  35739. if (mesh.material === this) {
  35740. mesh.material = null;
  35741. if (mesh.geometry) {
  35742. var geometry = (mesh.geometry);
  35743. if (this.storeEffectOnSubMeshes) {
  35744. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35745. var subMesh = _a[_i];
  35746. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35747. if (forceDisposeEffect && subMesh._materialEffect) {
  35748. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35749. }
  35750. }
  35751. }
  35752. else {
  35753. geometry._releaseVertexArrayObject(this._effect);
  35754. }
  35755. }
  35756. }
  35757. }
  35758. this._uniformBuffer.dispose();
  35759. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35760. if (forceDisposeEffect && this._effect) {
  35761. if (!this.storeEffectOnSubMeshes) {
  35762. this._scene.getEngine()._releaseEffect(this._effect);
  35763. }
  35764. this._effect = null;
  35765. }
  35766. // Callback
  35767. this.onDisposeObservable.notifyObservers(this);
  35768. this.onDisposeObservable.clear();
  35769. if (this._onBindObservable) {
  35770. this._onBindObservable.clear();
  35771. }
  35772. if (this._onUnBindObservable) {
  35773. this._onUnBindObservable.clear();
  35774. }
  35775. };
  35776. /**
  35777. * Serializes this material
  35778. * @returns the serialized material object
  35779. */
  35780. Material.prototype.serialize = function () {
  35781. return BABYLON.SerializationHelper.Serialize(this);
  35782. };
  35783. /**
  35784. * Creates a MultiMaterial from parsed MultiMaterial data.
  35785. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35786. * @param scene defines the hosting scene
  35787. * @returns a new MultiMaterial
  35788. */
  35789. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35790. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35791. multiMaterial.id = parsedMultiMaterial.id;
  35792. if (BABYLON.Tags) {
  35793. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35794. }
  35795. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35796. var subMatId = parsedMultiMaterial.materials[matIndex];
  35797. if (subMatId) {
  35798. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35799. }
  35800. else {
  35801. multiMaterial.subMaterials.push(null);
  35802. }
  35803. }
  35804. return multiMaterial;
  35805. };
  35806. /**
  35807. * Creates a material from parsed material data
  35808. * @param parsedMaterial defines parsed material data
  35809. * @param scene defines the hosting scene
  35810. * @param rootUrl defines the root URL to use to load textures
  35811. * @returns a new material
  35812. */
  35813. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35814. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35815. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35816. }
  35817. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35818. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35819. if (!BABYLON.LegacyPBRMaterial) {
  35820. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35821. return;
  35822. }
  35823. }
  35824. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35825. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35826. };
  35827. // Triangle views
  35828. Material._TriangleFillMode = 0;
  35829. Material._WireFrameFillMode = 1;
  35830. Material._PointFillMode = 2;
  35831. // Draw modes
  35832. Material._PointListDrawMode = 3;
  35833. Material._LineListDrawMode = 4;
  35834. Material._LineLoopDrawMode = 5;
  35835. Material._LineStripDrawMode = 6;
  35836. Material._TriangleStripDrawMode = 7;
  35837. Material._TriangleFanDrawMode = 8;
  35838. /**
  35839. * Stores the clock-wise side orientation
  35840. */
  35841. Material._ClockWiseSideOrientation = 0;
  35842. /**
  35843. * Stores the counter clock-wise side orientation
  35844. */
  35845. Material._CounterClockWiseSideOrientation = 1;
  35846. /**
  35847. * The dirty texture flag value
  35848. */
  35849. Material._TextureDirtyFlag = 1;
  35850. /**
  35851. * The dirty light flag value
  35852. */
  35853. Material._LightDirtyFlag = 2;
  35854. /**
  35855. * The dirty fresnel flag value
  35856. */
  35857. Material._FresnelDirtyFlag = 4;
  35858. /**
  35859. * The dirty attribute flag value
  35860. */
  35861. Material._AttributesDirtyFlag = 8;
  35862. /**
  35863. * The dirty misc flag value
  35864. */
  35865. Material._MiscDirtyFlag = 16;
  35866. __decorate([
  35867. BABYLON.serialize()
  35868. ], Material.prototype, "id", void 0);
  35869. __decorate([
  35870. BABYLON.serialize()
  35871. ], Material.prototype, "uniqueId", void 0);
  35872. __decorate([
  35873. BABYLON.serialize()
  35874. ], Material.prototype, "name", void 0);
  35875. __decorate([
  35876. BABYLON.serialize()
  35877. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35878. __decorate([
  35879. BABYLON.serialize()
  35880. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35881. __decorate([
  35882. BABYLON.serialize()
  35883. ], Material.prototype, "state", void 0);
  35884. __decorate([
  35885. BABYLON.serialize("alpha")
  35886. ], Material.prototype, "_alpha", void 0);
  35887. __decorate([
  35888. BABYLON.serialize("backFaceCulling")
  35889. ], Material.prototype, "_backFaceCulling", void 0);
  35890. __decorate([
  35891. BABYLON.serialize()
  35892. ], Material.prototype, "sideOrientation", void 0);
  35893. __decorate([
  35894. BABYLON.serialize("alphaMode")
  35895. ], Material.prototype, "_alphaMode", void 0);
  35896. __decorate([
  35897. BABYLON.serialize()
  35898. ], Material.prototype, "_needDepthPrePass", void 0);
  35899. __decorate([
  35900. BABYLON.serialize()
  35901. ], Material.prototype, "disableDepthWrite", void 0);
  35902. __decorate([
  35903. BABYLON.serialize()
  35904. ], Material.prototype, "forceDepthWrite", void 0);
  35905. __decorate([
  35906. BABYLON.serialize()
  35907. ], Material.prototype, "separateCullingPass", void 0);
  35908. __decorate([
  35909. BABYLON.serialize("fogEnabled")
  35910. ], Material.prototype, "_fogEnabled", void 0);
  35911. __decorate([
  35912. BABYLON.serialize()
  35913. ], Material.prototype, "pointSize", void 0);
  35914. __decorate([
  35915. BABYLON.serialize()
  35916. ], Material.prototype, "zOffset", void 0);
  35917. __decorate([
  35918. BABYLON.serialize()
  35919. ], Material.prototype, "wireframe", null);
  35920. __decorate([
  35921. BABYLON.serialize()
  35922. ], Material.prototype, "pointsCloud", null);
  35923. __decorate([
  35924. BABYLON.serialize()
  35925. ], Material.prototype, "fillMode", null);
  35926. return Material;
  35927. }());
  35928. BABYLON.Material = Material;
  35929. })(BABYLON || (BABYLON = {}));
  35930. //# sourceMappingURL=babylon.material.js.map
  35931. var BABYLON;
  35932. (function (BABYLON) {
  35933. var UniformBuffer = /** @class */ (function () {
  35934. /**
  35935. * Uniform buffer objects.
  35936. *
  35937. * Handles blocks of uniform on the GPU.
  35938. *
  35939. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35940. *
  35941. * For more information, please refer to :
  35942. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35943. */
  35944. function UniformBuffer(engine, data, dynamic) {
  35945. this._engine = engine;
  35946. this._noUBO = !engine.supportsUniformBuffers;
  35947. this._dynamic = dynamic;
  35948. this._data = data || [];
  35949. this._uniformLocations = {};
  35950. this._uniformSizes = {};
  35951. this._uniformLocationPointer = 0;
  35952. this._needSync = false;
  35953. if (this._noUBO) {
  35954. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35955. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35956. this.updateFloat = this._updateFloatForEffect;
  35957. this.updateFloat2 = this._updateFloat2ForEffect;
  35958. this.updateFloat3 = this._updateFloat3ForEffect;
  35959. this.updateFloat4 = this._updateFloat4ForEffect;
  35960. this.updateMatrix = this._updateMatrixForEffect;
  35961. this.updateVector3 = this._updateVector3ForEffect;
  35962. this.updateVector4 = this._updateVector4ForEffect;
  35963. this.updateColor3 = this._updateColor3ForEffect;
  35964. this.updateColor4 = this._updateColor4ForEffect;
  35965. }
  35966. else {
  35967. this._engine._uniformBuffers.push(this);
  35968. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35969. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35970. this.updateFloat = this._updateFloatForUniform;
  35971. this.updateFloat2 = this._updateFloat2ForUniform;
  35972. this.updateFloat3 = this._updateFloat3ForUniform;
  35973. this.updateFloat4 = this._updateFloat4ForUniform;
  35974. this.updateMatrix = this._updateMatrixForUniform;
  35975. this.updateVector3 = this._updateVector3ForUniform;
  35976. this.updateVector4 = this._updateVector4ForUniform;
  35977. this.updateColor3 = this._updateColor3ForUniform;
  35978. this.updateColor4 = this._updateColor4ForUniform;
  35979. }
  35980. }
  35981. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35982. // Properties
  35983. /**
  35984. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35985. * or just falling back on setUniformXXX calls.
  35986. */
  35987. get: function () {
  35988. return !this._noUBO;
  35989. },
  35990. enumerable: true,
  35991. configurable: true
  35992. });
  35993. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35994. /**
  35995. * Indicates if the WebGL underlying uniform buffer is in sync
  35996. * with the javascript cache data.
  35997. */
  35998. get: function () {
  35999. return !this._needSync;
  36000. },
  36001. enumerable: true,
  36002. configurable: true
  36003. });
  36004. /**
  36005. * Indicates if the WebGL underlying uniform buffer is dynamic.
  36006. * Also, a dynamic UniformBuffer will disable cache verification and always
  36007. * update the underlying WebGL uniform buffer to the GPU.
  36008. */
  36009. UniformBuffer.prototype.isDynamic = function () {
  36010. return this._dynamic !== undefined;
  36011. };
  36012. /**
  36013. * The data cache on JS side.
  36014. */
  36015. UniformBuffer.prototype.getData = function () {
  36016. return this._bufferData;
  36017. };
  36018. /**
  36019. * The underlying WebGL Uniform buffer.
  36020. */
  36021. UniformBuffer.prototype.getBuffer = function () {
  36022. return this._buffer;
  36023. };
  36024. /**
  36025. * std140 layout specifies how to align data within an UBO structure.
  36026. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  36027. * for specs.
  36028. */
  36029. UniformBuffer.prototype._fillAlignment = function (size) {
  36030. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  36031. // and 4x4 matrices
  36032. // TODO : change if other types are used
  36033. var alignment;
  36034. if (size <= 2) {
  36035. alignment = size;
  36036. }
  36037. else {
  36038. alignment = 4;
  36039. }
  36040. if ((this._uniformLocationPointer % alignment) !== 0) {
  36041. var oldPointer = this._uniformLocationPointer;
  36042. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  36043. var diff = this._uniformLocationPointer - oldPointer;
  36044. for (var i = 0; i < diff; i++) {
  36045. this._data.push(0);
  36046. }
  36047. }
  36048. };
  36049. /**
  36050. * Adds an uniform in the buffer.
  36051. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  36052. * for the layout to be correct !
  36053. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36054. * @param {number|number[]} size Data size, or data directly.
  36055. */
  36056. UniformBuffer.prototype.addUniform = function (name, size) {
  36057. if (this._noUBO) {
  36058. return;
  36059. }
  36060. if (this._uniformLocations[name] !== undefined) {
  36061. // Already existing uniform
  36062. return;
  36063. }
  36064. // This function must be called in the order of the shader layout !
  36065. // size can be the size of the uniform, or data directly
  36066. var data;
  36067. if (size instanceof Array) {
  36068. data = size;
  36069. size = data.length;
  36070. }
  36071. else {
  36072. size = size;
  36073. data = [];
  36074. // Fill with zeros
  36075. for (var i = 0; i < size; i++) {
  36076. data.push(0);
  36077. }
  36078. }
  36079. this._fillAlignment(size);
  36080. this._uniformSizes[name] = size;
  36081. this._uniformLocations[name] = this._uniformLocationPointer;
  36082. this._uniformLocationPointer += size;
  36083. for (var i = 0; i < size; i++) {
  36084. this._data.push(data[i]);
  36085. }
  36086. this._needSync = true;
  36087. };
  36088. /**
  36089. * Wrapper for addUniform.
  36090. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36091. * @param {Matrix} mat A 4x4 matrix.
  36092. */
  36093. UniformBuffer.prototype.addMatrix = function (name, mat) {
  36094. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  36095. };
  36096. /**
  36097. * Wrapper for addUniform.
  36098. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36099. * @param {number} x
  36100. * @param {number} y
  36101. */
  36102. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  36103. var temp = [x, y];
  36104. this.addUniform(name, temp);
  36105. };
  36106. /**
  36107. * Wrapper for addUniform.
  36108. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36109. * @param {number} x
  36110. * @param {number} y
  36111. * @param {number} z
  36112. */
  36113. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  36114. var temp = [x, y, z];
  36115. this.addUniform(name, temp);
  36116. };
  36117. /**
  36118. * Wrapper for addUniform.
  36119. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36120. * @param {Color3} color
  36121. */
  36122. UniformBuffer.prototype.addColor3 = function (name, color) {
  36123. var temp = new Array();
  36124. color.toArray(temp);
  36125. this.addUniform(name, temp);
  36126. };
  36127. /**
  36128. * Wrapper for addUniform.
  36129. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36130. * @param {Color3} color
  36131. * @param {number} alpha
  36132. */
  36133. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36134. var temp = new Array();
  36135. color.toArray(temp);
  36136. temp.push(alpha);
  36137. this.addUniform(name, temp);
  36138. };
  36139. /**
  36140. * Wrapper for addUniform.
  36141. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36142. * @param {Vector3} vector
  36143. */
  36144. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36145. var temp = new Array();
  36146. vector.toArray(temp);
  36147. this.addUniform(name, temp);
  36148. };
  36149. /**
  36150. * Wrapper for addUniform.
  36151. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36152. */
  36153. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36154. this.addUniform(name, 12);
  36155. };
  36156. /**
  36157. * Wrapper for addUniform.
  36158. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36159. */
  36160. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36161. this.addUniform(name, 8);
  36162. };
  36163. /**
  36164. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36165. */
  36166. UniformBuffer.prototype.create = function () {
  36167. if (this._noUBO) {
  36168. return;
  36169. }
  36170. if (this._buffer) {
  36171. return; // nothing to do
  36172. }
  36173. // See spec, alignment must be filled as a vec4
  36174. this._fillAlignment(4);
  36175. this._bufferData = new Float32Array(this._data);
  36176. this._rebuild();
  36177. this._needSync = true;
  36178. };
  36179. /** @hidden */
  36180. UniformBuffer.prototype._rebuild = function () {
  36181. if (this._noUBO) {
  36182. return;
  36183. }
  36184. if (this._dynamic) {
  36185. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36186. }
  36187. else {
  36188. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36189. }
  36190. };
  36191. /**
  36192. * Updates the WebGL Uniform Buffer on the GPU.
  36193. * If the `dynamic` flag is set to true, no cache comparison is done.
  36194. * Otherwise, the buffer will be updated only if the cache differs.
  36195. */
  36196. UniformBuffer.prototype.update = function () {
  36197. if (!this._buffer) {
  36198. this.create();
  36199. return;
  36200. }
  36201. if (!this._dynamic && !this._needSync) {
  36202. return;
  36203. }
  36204. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36205. this._needSync = false;
  36206. };
  36207. /**
  36208. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36209. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36210. * @param {number[]|Float32Array} data Flattened data
  36211. * @param {number} size Size of the data.
  36212. */
  36213. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36214. var location = this._uniformLocations[uniformName];
  36215. if (location === undefined) {
  36216. if (this._buffer) {
  36217. // Cannot add an uniform if the buffer is already created
  36218. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36219. return;
  36220. }
  36221. this.addUniform(uniformName, size);
  36222. location = this._uniformLocations[uniformName];
  36223. }
  36224. if (!this._buffer) {
  36225. this.create();
  36226. }
  36227. if (!this._dynamic) {
  36228. // Cache for static uniform buffers
  36229. var changed = false;
  36230. for (var i = 0; i < size; i++) {
  36231. if (this._bufferData[location + i] !== data[i]) {
  36232. changed = true;
  36233. this._bufferData[location + i] = data[i];
  36234. }
  36235. }
  36236. this._needSync = this._needSync || changed;
  36237. }
  36238. else {
  36239. // No cache for dynamic
  36240. for (var i = 0; i < size; i++) {
  36241. this._bufferData[location + i] = data[i];
  36242. }
  36243. }
  36244. };
  36245. // Update methods
  36246. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36247. // To match std140, matrix must be realigned
  36248. for (var i = 0; i < 3; i++) {
  36249. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36250. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36251. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36252. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36253. }
  36254. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36255. };
  36256. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36257. this._currentEffect.setMatrix3x3(name, matrix);
  36258. };
  36259. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36260. this._currentEffect.setMatrix2x2(name, matrix);
  36261. };
  36262. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36263. // To match std140, matrix must be realigned
  36264. for (var i = 0; i < 2; i++) {
  36265. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36266. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36267. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36268. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36269. }
  36270. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36271. };
  36272. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36273. this._currentEffect.setFloat(name, x);
  36274. };
  36275. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36276. UniformBuffer._tempBuffer[0] = x;
  36277. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36278. };
  36279. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36280. if (suffix === void 0) { suffix = ""; }
  36281. this._currentEffect.setFloat2(name + suffix, x, y);
  36282. };
  36283. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36284. if (suffix === void 0) { suffix = ""; }
  36285. UniformBuffer._tempBuffer[0] = x;
  36286. UniformBuffer._tempBuffer[1] = y;
  36287. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36288. };
  36289. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36290. if (suffix === void 0) { suffix = ""; }
  36291. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36292. };
  36293. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36294. if (suffix === void 0) { suffix = ""; }
  36295. UniformBuffer._tempBuffer[0] = x;
  36296. UniformBuffer._tempBuffer[1] = y;
  36297. UniformBuffer._tempBuffer[2] = z;
  36298. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36299. };
  36300. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36301. if (suffix === void 0) { suffix = ""; }
  36302. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36303. };
  36304. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36305. if (suffix === void 0) { suffix = ""; }
  36306. UniformBuffer._tempBuffer[0] = x;
  36307. UniformBuffer._tempBuffer[1] = y;
  36308. UniformBuffer._tempBuffer[2] = z;
  36309. UniformBuffer._tempBuffer[3] = w;
  36310. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36311. };
  36312. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36313. this._currentEffect.setMatrix(name, mat);
  36314. };
  36315. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36316. this.updateUniform(name, mat.toArray(), 16);
  36317. };
  36318. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36319. this._currentEffect.setVector3(name, vector);
  36320. };
  36321. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36322. vector.toArray(UniformBuffer._tempBuffer);
  36323. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36324. };
  36325. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36326. this._currentEffect.setVector4(name, vector);
  36327. };
  36328. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36329. vector.toArray(UniformBuffer._tempBuffer);
  36330. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36331. };
  36332. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36333. if (suffix === void 0) { suffix = ""; }
  36334. this._currentEffect.setColor3(name + suffix, color);
  36335. };
  36336. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36337. if (suffix === void 0) { suffix = ""; }
  36338. color.toArray(UniformBuffer._tempBuffer);
  36339. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36340. };
  36341. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36342. if (suffix === void 0) { suffix = ""; }
  36343. this._currentEffect.setColor4(name + suffix, color, alpha);
  36344. };
  36345. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36346. if (suffix === void 0) { suffix = ""; }
  36347. color.toArray(UniformBuffer._tempBuffer);
  36348. UniformBuffer._tempBuffer[3] = alpha;
  36349. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36350. };
  36351. /**
  36352. * Sets a sampler uniform on the effect.
  36353. * @param {string} name Name of the sampler.
  36354. * @param {Texture} texture
  36355. */
  36356. UniformBuffer.prototype.setTexture = function (name, texture) {
  36357. this._currentEffect.setTexture(name, texture);
  36358. };
  36359. /**
  36360. * Directly updates the value of the uniform in the cache AND on the GPU.
  36361. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36362. * @param {number[]|Float32Array} data Flattened data
  36363. */
  36364. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36365. this.updateUniform(uniformName, data, data.length);
  36366. this.update();
  36367. };
  36368. /**
  36369. * Binds this uniform buffer to an effect.
  36370. * @param {Effect} effect
  36371. * @param {string} name Name of the uniform block in the shader.
  36372. */
  36373. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36374. this._currentEffect = effect;
  36375. if (this._noUBO || !this._buffer) {
  36376. return;
  36377. }
  36378. effect.bindUniformBuffer(this._buffer, name);
  36379. };
  36380. /**
  36381. * Disposes the uniform buffer.
  36382. */
  36383. UniformBuffer.prototype.dispose = function () {
  36384. if (this._noUBO) {
  36385. return;
  36386. }
  36387. var index = this._engine._uniformBuffers.indexOf(this);
  36388. if (index !== -1) {
  36389. this._engine._uniformBuffers.splice(index, 1);
  36390. }
  36391. if (!this._buffer) {
  36392. return;
  36393. }
  36394. if (this._engine._releaseBuffer(this._buffer)) {
  36395. this._buffer = null;
  36396. }
  36397. };
  36398. // Pool for avoiding memory leaks
  36399. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36400. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36401. return UniformBuffer;
  36402. }());
  36403. BABYLON.UniformBuffer = UniformBuffer;
  36404. })(BABYLON || (BABYLON = {}));
  36405. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36406. var BABYLON;
  36407. (function (BABYLON) {
  36408. /**
  36409. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36410. */
  36411. var VertexData = /** @class */ (function () {
  36412. function VertexData() {
  36413. }
  36414. /**
  36415. * Uses the passed data array to set the set the values for the specified kind of data
  36416. * @param data a linear array of floating numbers
  36417. * @param kind the type of data that is being set, eg positions, colors etc
  36418. */
  36419. VertexData.prototype.set = function (data, kind) {
  36420. switch (kind) {
  36421. case BABYLON.VertexBuffer.PositionKind:
  36422. this.positions = data;
  36423. break;
  36424. case BABYLON.VertexBuffer.NormalKind:
  36425. this.normals = data;
  36426. break;
  36427. case BABYLON.VertexBuffer.TangentKind:
  36428. this.tangents = data;
  36429. break;
  36430. case BABYLON.VertexBuffer.UVKind:
  36431. this.uvs = data;
  36432. break;
  36433. case BABYLON.VertexBuffer.UV2Kind:
  36434. this.uvs2 = data;
  36435. break;
  36436. case BABYLON.VertexBuffer.UV3Kind:
  36437. this.uvs3 = data;
  36438. break;
  36439. case BABYLON.VertexBuffer.UV4Kind:
  36440. this.uvs4 = data;
  36441. break;
  36442. case BABYLON.VertexBuffer.UV5Kind:
  36443. this.uvs5 = data;
  36444. break;
  36445. case BABYLON.VertexBuffer.UV6Kind:
  36446. this.uvs6 = data;
  36447. break;
  36448. case BABYLON.VertexBuffer.ColorKind:
  36449. this.colors = data;
  36450. break;
  36451. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36452. this.matricesIndices = data;
  36453. break;
  36454. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36455. this.matricesWeights = data;
  36456. break;
  36457. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36458. this.matricesIndicesExtra = data;
  36459. break;
  36460. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36461. this.matricesWeightsExtra = data;
  36462. break;
  36463. }
  36464. };
  36465. /**
  36466. * Associates the vertexData to the passed Mesh.
  36467. * Sets it as updatable or not (default `false`)
  36468. * @param mesh the mesh the vertexData is applied to
  36469. * @param updatable when used and having the value true allows new data to update the vertexData
  36470. * @returns the VertexData
  36471. */
  36472. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36473. this._applyTo(mesh, updatable);
  36474. return this;
  36475. };
  36476. /**
  36477. * Associates the vertexData to the passed Geometry.
  36478. * Sets it as updatable or not (default `false`)
  36479. * @param geometry the geometry the vertexData is applied to
  36480. * @param updatable when used and having the value true allows new data to update the vertexData
  36481. * @returns VertexData
  36482. */
  36483. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36484. this._applyTo(geometry, updatable);
  36485. return this;
  36486. };
  36487. /**
  36488. * Updates the associated mesh
  36489. * @param mesh the mesh to be updated
  36490. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36491. * @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
  36492. * @returns VertexData
  36493. */
  36494. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36495. this._update(mesh);
  36496. return this;
  36497. };
  36498. /**
  36499. * Updates the associated geometry
  36500. * @param geometry the geometry to be updated
  36501. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36502. * @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
  36503. * @returns VertexData.
  36504. */
  36505. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36506. this._update(geometry);
  36507. return this;
  36508. };
  36509. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36510. if (updatable === void 0) { updatable = false; }
  36511. if (this.positions) {
  36512. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36513. }
  36514. if (this.normals) {
  36515. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36516. }
  36517. if (this.tangents) {
  36518. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36519. }
  36520. if (this.uvs) {
  36521. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36522. }
  36523. if (this.uvs2) {
  36524. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36525. }
  36526. if (this.uvs3) {
  36527. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36528. }
  36529. if (this.uvs4) {
  36530. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36531. }
  36532. if (this.uvs5) {
  36533. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36534. }
  36535. if (this.uvs6) {
  36536. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36537. }
  36538. if (this.colors) {
  36539. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36540. }
  36541. if (this.matricesIndices) {
  36542. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36543. }
  36544. if (this.matricesWeights) {
  36545. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36546. }
  36547. if (this.matricesIndicesExtra) {
  36548. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36549. }
  36550. if (this.matricesWeightsExtra) {
  36551. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36552. }
  36553. if (this.indices) {
  36554. meshOrGeometry.setIndices(this.indices, null, updatable);
  36555. }
  36556. else {
  36557. meshOrGeometry.setIndices([], null);
  36558. }
  36559. return this;
  36560. };
  36561. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36562. if (this.positions) {
  36563. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36564. }
  36565. if (this.normals) {
  36566. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36567. }
  36568. if (this.tangents) {
  36569. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36570. }
  36571. if (this.uvs) {
  36572. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36573. }
  36574. if (this.uvs2) {
  36575. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36576. }
  36577. if (this.uvs3) {
  36578. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36579. }
  36580. if (this.uvs4) {
  36581. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36582. }
  36583. if (this.uvs5) {
  36584. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36585. }
  36586. if (this.uvs6) {
  36587. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36588. }
  36589. if (this.colors) {
  36590. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36591. }
  36592. if (this.matricesIndices) {
  36593. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36594. }
  36595. if (this.matricesWeights) {
  36596. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36597. }
  36598. if (this.matricesIndicesExtra) {
  36599. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36600. }
  36601. if (this.matricesWeightsExtra) {
  36602. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36603. }
  36604. if (this.indices) {
  36605. meshOrGeometry.setIndices(this.indices, null);
  36606. }
  36607. return this;
  36608. };
  36609. /**
  36610. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36611. * @param matrix the transforming matrix
  36612. * @returns the VertexData
  36613. */
  36614. VertexData.prototype.transform = function (matrix) {
  36615. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  36616. var transformed = BABYLON.Vector3.Zero();
  36617. var index;
  36618. if (this.positions) {
  36619. var position = BABYLON.Vector3.Zero();
  36620. for (index = 0; index < this.positions.length; index += 3) {
  36621. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36622. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36623. this.positions[index] = transformed.x;
  36624. this.positions[index + 1] = transformed.y;
  36625. this.positions[index + 2] = transformed.z;
  36626. }
  36627. }
  36628. if (this.normals) {
  36629. var normal = BABYLON.Vector3.Zero();
  36630. for (index = 0; index < this.normals.length; index += 3) {
  36631. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36632. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36633. this.normals[index] = transformed.x;
  36634. this.normals[index + 1] = transformed.y;
  36635. this.normals[index + 2] = transformed.z;
  36636. }
  36637. }
  36638. if (this.tangents) {
  36639. var tangent = BABYLON.Vector4.Zero();
  36640. var tangentTransformed = BABYLON.Vector4.Zero();
  36641. for (index = 0; index < this.tangents.length; index += 4) {
  36642. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36643. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36644. this.tangents[index] = tangentTransformed.x;
  36645. this.tangents[index + 1] = tangentTransformed.y;
  36646. this.tangents[index + 2] = tangentTransformed.z;
  36647. this.tangents[index + 3] = tangentTransformed.w;
  36648. }
  36649. }
  36650. if (flip && this.indices) {
  36651. for (index = 0; index < this.indices.length; index += 3) {
  36652. var tmp = this.indices[index + 1];
  36653. this.indices[index + 1] = this.indices[index + 2];
  36654. this.indices[index + 2] = tmp;
  36655. }
  36656. }
  36657. return this;
  36658. };
  36659. /**
  36660. * Merges the passed VertexData into the current one
  36661. * @param other the VertexData to be merged into the current one
  36662. * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array
  36663. * @returns the modified VertexData
  36664. */
  36665. VertexData.prototype.merge = function (other, use32BitsIndices) {
  36666. if (use32BitsIndices === void 0) { use32BitsIndices = false; }
  36667. this._validate();
  36668. other._validate();
  36669. if (!this.normals !== !other.normals ||
  36670. !this.tangents !== !other.tangents ||
  36671. !this.uvs !== !other.uvs ||
  36672. !this.uvs2 !== !other.uvs2 ||
  36673. !this.uvs3 !== !other.uvs3 ||
  36674. !this.uvs4 !== !other.uvs4 ||
  36675. !this.uvs5 !== !other.uvs5 ||
  36676. !this.uvs6 !== !other.uvs6 ||
  36677. !this.colors !== !other.colors ||
  36678. !this.matricesIndices !== !other.matricesIndices ||
  36679. !this.matricesWeights !== !other.matricesWeights ||
  36680. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36681. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36682. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36683. }
  36684. if (other.indices) {
  36685. if (!this.indices) {
  36686. this.indices = [];
  36687. }
  36688. var offset = this.positions ? this.positions.length / 3 : 0;
  36689. var isSrcTypedArray = this.indices.BYTES_PER_ELEMENT !== undefined;
  36690. if (isSrcTypedArray) {
  36691. var len = this.indices.length + other.indices.length;
  36692. var temp = use32BitsIndices || this.indices instanceof Uint32Array ? new Uint32Array(len) : new Uint16Array(len);
  36693. temp.set(this.indices);
  36694. var decal = this.indices.length;
  36695. for (var index = 0; index < other.indices.length; index++) {
  36696. temp[decal + index] = other.indices[index] + offset;
  36697. }
  36698. this.indices = temp;
  36699. }
  36700. else {
  36701. for (var index = 0; index < other.indices.length; index++) {
  36702. this.indices.push(other.indices[index] + offset);
  36703. }
  36704. }
  36705. }
  36706. this.positions = this._mergeElement(this.positions, other.positions);
  36707. this.normals = this._mergeElement(this.normals, other.normals);
  36708. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36709. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36710. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36711. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36712. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36713. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36714. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36715. this.colors = this._mergeElement(this.colors, other.colors);
  36716. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36717. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36718. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36719. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36720. return this;
  36721. };
  36722. VertexData.prototype._mergeElement = function (source, other) {
  36723. if (!source) {
  36724. return other;
  36725. }
  36726. if (!other) {
  36727. return source;
  36728. }
  36729. var len = other.length + source.length;
  36730. var isSrcTypedArray = source instanceof Float32Array;
  36731. var isOthTypedArray = other instanceof Float32Array;
  36732. // use non-loop method when the source is Float32Array
  36733. if (isSrcTypedArray) {
  36734. var ret32 = new Float32Array(len);
  36735. ret32.set(source);
  36736. ret32.set(other, source.length);
  36737. return ret32;
  36738. // source is number[], when other is also use concat
  36739. }
  36740. else if (!isOthTypedArray) {
  36741. return source.concat(other);
  36742. // source is a number[], but other is a Float32Array, loop required
  36743. }
  36744. else {
  36745. var ret = source.slice(0); // copy source to a separate array
  36746. for (var i = 0, len = other.length; i < len; i++) {
  36747. ret.push(other[i]);
  36748. }
  36749. return ret;
  36750. }
  36751. };
  36752. VertexData.prototype._validate = function () {
  36753. if (!this.positions) {
  36754. throw new Error("Positions are required");
  36755. }
  36756. var getElementCount = function (kind, values) {
  36757. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36758. if ((values.length % stride) !== 0) {
  36759. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36760. }
  36761. return values.length / stride;
  36762. };
  36763. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36764. var validateElementCount = function (kind, values) {
  36765. var elementCount = getElementCount(kind, values);
  36766. if (elementCount !== positionsElementCount) {
  36767. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36768. }
  36769. };
  36770. if (this.normals)
  36771. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36772. if (this.tangents)
  36773. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36774. if (this.uvs)
  36775. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36776. if (this.uvs2)
  36777. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36778. if (this.uvs3)
  36779. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36780. if (this.uvs4)
  36781. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36782. if (this.uvs5)
  36783. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36784. if (this.uvs6)
  36785. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36786. if (this.colors)
  36787. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36788. if (this.matricesIndices)
  36789. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36790. if (this.matricesWeights)
  36791. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36792. if (this.matricesIndicesExtra)
  36793. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36794. if (this.matricesWeightsExtra)
  36795. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36796. };
  36797. /**
  36798. * Serializes the VertexData
  36799. * @returns a serialized object
  36800. */
  36801. VertexData.prototype.serialize = function () {
  36802. var serializationObject = this.serialize();
  36803. if (this.positions) {
  36804. serializationObject.positions = this.positions;
  36805. }
  36806. if (this.normals) {
  36807. serializationObject.normals = this.normals;
  36808. }
  36809. if (this.tangents) {
  36810. serializationObject.tangents = this.tangents;
  36811. }
  36812. if (this.uvs) {
  36813. serializationObject.uvs = this.uvs;
  36814. }
  36815. if (this.uvs2) {
  36816. serializationObject.uvs2 = this.uvs2;
  36817. }
  36818. if (this.uvs3) {
  36819. serializationObject.uvs3 = this.uvs3;
  36820. }
  36821. if (this.uvs4) {
  36822. serializationObject.uvs4 = this.uvs4;
  36823. }
  36824. if (this.uvs5) {
  36825. serializationObject.uvs5 = this.uvs5;
  36826. }
  36827. if (this.uvs6) {
  36828. serializationObject.uvs6 = this.uvs6;
  36829. }
  36830. if (this.colors) {
  36831. serializationObject.colors = this.colors;
  36832. }
  36833. if (this.matricesIndices) {
  36834. serializationObject.matricesIndices = this.matricesIndices;
  36835. serializationObject.matricesIndices._isExpanded = true;
  36836. }
  36837. if (this.matricesWeights) {
  36838. serializationObject.matricesWeights = this.matricesWeights;
  36839. }
  36840. if (this.matricesIndicesExtra) {
  36841. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36842. serializationObject.matricesIndicesExtra._isExpanded = true;
  36843. }
  36844. if (this.matricesWeightsExtra) {
  36845. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36846. }
  36847. serializationObject.indices = this.indices;
  36848. return serializationObject;
  36849. };
  36850. // Statics
  36851. /**
  36852. * Extracts the vertexData from a mesh
  36853. * @param mesh the mesh from which to extract the VertexData
  36854. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36855. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36856. * @returns the object VertexData associated to the passed mesh
  36857. */
  36858. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36859. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36860. };
  36861. /**
  36862. * Extracts the vertexData from the geometry
  36863. * @param geometry the geometry from which to extract the VertexData
  36864. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36865. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36866. * @returns the object VertexData associated to the passed mesh
  36867. */
  36868. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36869. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36870. };
  36871. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36872. var result = new VertexData();
  36873. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36874. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36875. }
  36876. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36877. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36878. }
  36879. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36880. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36881. }
  36882. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36883. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36884. }
  36885. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36886. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36887. }
  36888. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36889. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36890. }
  36891. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36892. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36893. }
  36894. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36895. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36896. }
  36897. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36898. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36899. }
  36900. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36901. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36902. }
  36903. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36904. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36905. }
  36906. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36907. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36908. }
  36909. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36910. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36911. }
  36912. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36913. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36914. }
  36915. result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);
  36916. return result;
  36917. };
  36918. /**
  36919. * Creates the VertexData for a Ribbon
  36920. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36921. * * pathArray array of paths, each of which an array of successive Vector3
  36922. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36923. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36924. * * 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
  36925. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36926. * * 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)
  36927. * * 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)
  36928. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36929. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36930. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36931. * @returns the VertexData of the ribbon
  36932. */
  36933. VertexData.CreateRibbon = function (options) {
  36934. var pathArray = options.pathArray;
  36935. var closeArray = options.closeArray || false;
  36936. var closePath = options.closePath || false;
  36937. var invertUV = options.invertUV || false;
  36938. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36939. var offset = options.offset || defaultOffset;
  36940. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36941. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36942. var customUV = options.uvs;
  36943. var customColors = options.colors;
  36944. var positions = [];
  36945. var indices = [];
  36946. var normals = [];
  36947. var uvs = [];
  36948. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36949. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36950. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36951. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36952. var minlg; // minimal length among all paths from pathArray
  36953. var lg = []; // array of path lengths : nb of vertex per path
  36954. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36955. var p; // path iterator
  36956. var i; // point iterator
  36957. var j; // point iterator
  36958. // if single path in pathArray
  36959. if (pathArray.length < 2) {
  36960. var ar1 = [];
  36961. var ar2 = [];
  36962. for (i = 0; i < pathArray[0].length - offset; i++) {
  36963. ar1.push(pathArray[0][i]);
  36964. ar2.push(pathArray[0][i + offset]);
  36965. }
  36966. pathArray = [ar1, ar2];
  36967. }
  36968. // positions and horizontal distances (u)
  36969. var idc = 0;
  36970. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36971. var path;
  36972. var l;
  36973. minlg = pathArray[0].length;
  36974. var vectlg;
  36975. var dist;
  36976. for (p = 0; p < pathArray.length; p++) {
  36977. uTotalDistance[p] = 0;
  36978. us[p] = [0];
  36979. path = pathArray[p];
  36980. l = path.length;
  36981. minlg = (minlg < l) ? minlg : l;
  36982. j = 0;
  36983. while (j < l) {
  36984. positions.push(path[j].x, path[j].y, path[j].z);
  36985. if (j > 0) {
  36986. vectlg = path[j].subtract(path[j - 1]).length();
  36987. dist = vectlg + uTotalDistance[p];
  36988. us[p].push(dist);
  36989. uTotalDistance[p] = dist;
  36990. }
  36991. j++;
  36992. }
  36993. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36994. j--;
  36995. positions.push(path[0].x, path[0].y, path[0].z);
  36996. vectlg = path[j].subtract(path[0]).length();
  36997. dist = vectlg + uTotalDistance[p];
  36998. us[p].push(dist);
  36999. uTotalDistance[p] = dist;
  37000. }
  37001. lg[p] = l + closePathCorr;
  37002. idx[p] = idc;
  37003. idc += (l + closePathCorr);
  37004. }
  37005. // vertical distances (v)
  37006. var path1;
  37007. var path2;
  37008. var vertex1 = null;
  37009. var vertex2 = null;
  37010. for (i = 0; i < minlg + closePathCorr; i++) {
  37011. vTotalDistance[i] = 0;
  37012. vs[i] = [0];
  37013. for (p = 0; p < pathArray.length - 1; p++) {
  37014. path1 = pathArray[p];
  37015. path2 = pathArray[p + 1];
  37016. if (i === minlg) { // closePath
  37017. vertex1 = path1[0];
  37018. vertex2 = path2[0];
  37019. }
  37020. else {
  37021. vertex1 = path1[i];
  37022. vertex2 = path2[i];
  37023. }
  37024. vectlg = vertex2.subtract(vertex1).length();
  37025. dist = vectlg + vTotalDistance[i];
  37026. vs[i].push(dist);
  37027. vTotalDistance[i] = dist;
  37028. }
  37029. if (closeArray && vertex2 && vertex1) {
  37030. path1 = pathArray[p];
  37031. path2 = pathArray[0];
  37032. if (i === minlg) { // closePath
  37033. vertex2 = path2[0];
  37034. }
  37035. vectlg = vertex2.subtract(vertex1).length();
  37036. dist = vectlg + vTotalDistance[i];
  37037. vTotalDistance[i] = dist;
  37038. }
  37039. }
  37040. // uvs
  37041. var u;
  37042. var v;
  37043. if (customUV) {
  37044. for (p = 0; p < customUV.length; p++) {
  37045. uvs.push(customUV[p].x, customUV[p].y);
  37046. }
  37047. }
  37048. else {
  37049. for (p = 0; p < pathArray.length; p++) {
  37050. for (i = 0; i < minlg + closePathCorr; i++) {
  37051. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  37052. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  37053. if (invertUV) {
  37054. uvs.push(v, u);
  37055. }
  37056. else {
  37057. uvs.push(u, v);
  37058. }
  37059. }
  37060. }
  37061. }
  37062. // indices
  37063. p = 0; // path index
  37064. var pi = 0; // positions array index
  37065. var l1 = lg[p] - 1; // path1 length
  37066. var l2 = lg[p + 1] - 1; // path2 length
  37067. var min = (l1 < l2) ? l1 : l2; // current path stop index
  37068. var shft = idx[1] - idx[0]; // shift
  37069. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  37070. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  37071. // 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
  37072. indices.push(pi, pi + shft, pi + 1);
  37073. indices.push(pi + shft + 1, pi + 1, pi + shft);
  37074. pi += 1;
  37075. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  37076. p++;
  37077. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  37078. shft = idx[0] - idx[p];
  37079. l1 = lg[p] - 1;
  37080. l2 = lg[0] - 1;
  37081. }
  37082. else {
  37083. shft = idx[p + 1] - idx[p];
  37084. l1 = lg[p] - 1;
  37085. l2 = lg[p + 1] - 1;
  37086. }
  37087. pi = idx[p];
  37088. min = (l1 < l2) ? l1 + pi : l2 + pi;
  37089. }
  37090. }
  37091. // normals
  37092. VertexData.ComputeNormals(positions, indices, normals);
  37093. if (closePath) { // update both the first and last vertex normals to their average value
  37094. var indexFirst = 0;
  37095. var indexLast = 0;
  37096. for (p = 0; p < pathArray.length; p++) {
  37097. indexFirst = idx[p] * 3;
  37098. if (p + 1 < pathArray.length) {
  37099. indexLast = (idx[p + 1] - 1) * 3;
  37100. }
  37101. else {
  37102. indexLast = normals.length - 3;
  37103. }
  37104. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37105. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37106. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37107. normals[indexLast] = normals[indexFirst];
  37108. normals[indexLast + 1] = normals[indexFirst + 1];
  37109. normals[indexLast + 2] = normals[indexFirst + 2];
  37110. }
  37111. }
  37112. // sides
  37113. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37114. // Colors
  37115. var colors = null;
  37116. if (customColors) {
  37117. colors = new Float32Array(customColors.length * 4);
  37118. for (var c = 0; c < customColors.length; c++) {
  37119. colors[c * 4] = customColors[c].r;
  37120. colors[c * 4 + 1] = customColors[c].g;
  37121. colors[c * 4 + 2] = customColors[c].b;
  37122. colors[c * 4 + 3] = customColors[c].a;
  37123. }
  37124. }
  37125. // Result
  37126. var vertexData = new VertexData();
  37127. var positions32 = new Float32Array(positions);
  37128. var normals32 = new Float32Array(normals);
  37129. var uvs32 = new Float32Array(uvs);
  37130. vertexData.indices = indices;
  37131. vertexData.positions = positions32;
  37132. vertexData.normals = normals32;
  37133. vertexData.uvs = uvs32;
  37134. if (colors) {
  37135. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37136. }
  37137. if (closePath) {
  37138. vertexData._idx = idx;
  37139. }
  37140. return vertexData;
  37141. };
  37142. /**
  37143. * Creates the VertexData for a box
  37144. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37145. * * size sets the width, height and depth of the box to the value of size, optional default 1
  37146. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  37147. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  37148. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  37149. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  37150. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  37151. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37152. * * 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)
  37153. * * 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)
  37154. * @returns the VertexData of the box
  37155. */
  37156. VertexData.CreateBox = function (options) {
  37157. var normalsSource = [
  37158. new BABYLON.Vector3(0, 0, 1),
  37159. new BABYLON.Vector3(0, 0, -1),
  37160. new BABYLON.Vector3(1, 0, 0),
  37161. new BABYLON.Vector3(-1, 0, 0),
  37162. new BABYLON.Vector3(0, 1, 0),
  37163. new BABYLON.Vector3(0, -1, 0)
  37164. ];
  37165. var indices = [];
  37166. var positions = [];
  37167. var normals = [];
  37168. var uvs = [];
  37169. var width = options.width || options.size || 1;
  37170. var height = options.height || options.size || 1;
  37171. var depth = options.depth || options.size || 1;
  37172. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37173. var faceUV = options.faceUV || new Array(6);
  37174. var faceColors = options.faceColors;
  37175. var colors = [];
  37176. // default face colors and UV if undefined
  37177. for (var f = 0; f < 6; f++) {
  37178. if (faceUV[f] === undefined) {
  37179. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37180. }
  37181. if (faceColors && faceColors[f] === undefined) {
  37182. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37183. }
  37184. }
  37185. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37186. // Create each face in turn.
  37187. for (var index = 0; index < normalsSource.length; index++) {
  37188. var normal = normalsSource[index];
  37189. // Get two vectors perpendicular to the face normal and to each other.
  37190. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37191. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37192. // Six indices (two triangles) per face.
  37193. var verticesLength = positions.length / 3;
  37194. indices.push(verticesLength);
  37195. indices.push(verticesLength + 1);
  37196. indices.push(verticesLength + 2);
  37197. indices.push(verticesLength);
  37198. indices.push(verticesLength + 2);
  37199. indices.push(verticesLength + 3);
  37200. // Four vertices per face.
  37201. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37202. positions.push(vertex.x, vertex.y, vertex.z);
  37203. normals.push(normal.x, normal.y, normal.z);
  37204. uvs.push(faceUV[index].z, faceUV[index].w);
  37205. if (faceColors) {
  37206. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37207. }
  37208. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37209. positions.push(vertex.x, vertex.y, vertex.z);
  37210. normals.push(normal.x, normal.y, normal.z);
  37211. uvs.push(faceUV[index].x, faceUV[index].w);
  37212. if (faceColors) {
  37213. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37214. }
  37215. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37216. positions.push(vertex.x, vertex.y, vertex.z);
  37217. normals.push(normal.x, normal.y, normal.z);
  37218. uvs.push(faceUV[index].x, faceUV[index].y);
  37219. if (faceColors) {
  37220. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37221. }
  37222. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37223. positions.push(vertex.x, vertex.y, vertex.z);
  37224. normals.push(normal.x, normal.y, normal.z);
  37225. uvs.push(faceUV[index].z, faceUV[index].y);
  37226. if (faceColors) {
  37227. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37228. }
  37229. }
  37230. // sides
  37231. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37232. // Result
  37233. var vertexData = new VertexData();
  37234. vertexData.indices = indices;
  37235. vertexData.positions = positions;
  37236. vertexData.normals = normals;
  37237. vertexData.uvs = uvs;
  37238. if (faceColors) {
  37239. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37240. vertexData.colors = totalColors;
  37241. }
  37242. return vertexData;
  37243. };
  37244. /**
  37245. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37246. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37247. * * segments sets the number of horizontal strips optional, default 32
  37248. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37249. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37250. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37251. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37252. * * 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
  37253. * * 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
  37254. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37255. * * 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)
  37256. * * 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)
  37257. * @returns the VertexData of the ellipsoid
  37258. */
  37259. VertexData.CreateSphere = function (options) {
  37260. var segments = options.segments || 32;
  37261. var diameterX = options.diameterX || options.diameter || 1;
  37262. var diameterY = options.diameterY || options.diameter || 1;
  37263. var diameterZ = options.diameterZ || options.diameter || 1;
  37264. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37265. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37266. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37267. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37268. var totalZRotationSteps = 2 + segments;
  37269. var totalYRotationSteps = 2 * totalZRotationSteps;
  37270. var indices = [];
  37271. var positions = [];
  37272. var normals = [];
  37273. var uvs = [];
  37274. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37275. var normalizedZ = zRotationStep / totalZRotationSteps;
  37276. var angleZ = normalizedZ * Math.PI * slice;
  37277. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37278. var normalizedY = yRotationStep / totalYRotationSteps;
  37279. var angleY = normalizedY * Math.PI * 2 * arc;
  37280. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37281. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37282. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37283. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37284. var vertex = complete.multiply(radius);
  37285. var normal = complete.divide(radius).normalize();
  37286. positions.push(vertex.x, vertex.y, vertex.z);
  37287. normals.push(normal.x, normal.y, normal.z);
  37288. uvs.push(normalizedY, normalizedZ);
  37289. }
  37290. if (zRotationStep > 0) {
  37291. var verticesCount = positions.length / 3;
  37292. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37293. indices.push((firstIndex));
  37294. indices.push((firstIndex + 1));
  37295. indices.push(firstIndex + totalYRotationSteps + 1);
  37296. indices.push((firstIndex + totalYRotationSteps + 1));
  37297. indices.push((firstIndex + 1));
  37298. indices.push((firstIndex + totalYRotationSteps + 2));
  37299. }
  37300. }
  37301. }
  37302. // Sides
  37303. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37304. // Result
  37305. var vertexData = new VertexData();
  37306. vertexData.indices = indices;
  37307. vertexData.positions = positions;
  37308. vertexData.normals = normals;
  37309. vertexData.uvs = uvs;
  37310. return vertexData;
  37311. };
  37312. /**
  37313. * Creates the VertexData for a cylinder, cone or prism
  37314. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37315. * * height sets the height (y direction) of the cylinder, optional, default 2
  37316. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37317. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37318. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37319. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37320. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37321. * * 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
  37322. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37323. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37324. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37325. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37326. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37327. * * 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)
  37328. * * 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)
  37329. * @returns the VertexData of the cylinder, cone or prism
  37330. */
  37331. VertexData.CreateCylinder = function (options) {
  37332. var height = options.height || 2;
  37333. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37334. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37335. var tessellation = options.tessellation || 24;
  37336. var subdivisions = options.subdivisions || 1;
  37337. var hasRings = options.hasRings ? true : false;
  37338. var enclose = options.enclose ? true : false;
  37339. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37340. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37341. var faceUV = options.faceUV || new Array(3);
  37342. var faceColors = options.faceColors;
  37343. // default face colors and UV if undefined
  37344. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37345. var ringNb = (hasRings) ? subdivisions : 1;
  37346. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37347. var f;
  37348. for (f = 0; f < surfaceNb; f++) {
  37349. if (faceColors && faceColors[f] === undefined) {
  37350. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37351. }
  37352. }
  37353. for (f = 0; f < surfaceNb; f++) {
  37354. if (faceUV && faceUV[f] === undefined) {
  37355. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37356. }
  37357. }
  37358. var indices = new Array();
  37359. var positions = new Array();
  37360. var normals = new Array();
  37361. var uvs = new Array();
  37362. var colors = new Array();
  37363. var angle_step = Math.PI * 2 * arc / tessellation;
  37364. var angle;
  37365. var h;
  37366. var radius;
  37367. var tan = (diameterBottom - diameterTop) / 2 / height;
  37368. var ringVertex = BABYLON.Vector3.Zero();
  37369. var ringNormal = BABYLON.Vector3.Zero();
  37370. var ringFirstVertex = BABYLON.Vector3.Zero();
  37371. var ringFirstNormal = BABYLON.Vector3.Zero();
  37372. var quadNormal = BABYLON.Vector3.Zero();
  37373. var Y = BABYLON.Axis.Y;
  37374. // positions, normals, uvs
  37375. var i;
  37376. var j;
  37377. var r;
  37378. var ringIdx = 1;
  37379. var s = 1; // surface index
  37380. var cs = 0;
  37381. var v = 0;
  37382. for (i = 0; i <= subdivisions; i++) {
  37383. h = i / subdivisions;
  37384. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37385. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37386. for (r = 0; r < ringIdx; r++) {
  37387. if (hasRings) {
  37388. s += r;
  37389. }
  37390. if (enclose) {
  37391. s += 2 * r;
  37392. }
  37393. for (j = 0; j <= tessellation; j++) {
  37394. angle = j * angle_step;
  37395. // position
  37396. ringVertex.x = Math.cos(-angle) * radius;
  37397. ringVertex.y = -height / 2 + h * height;
  37398. ringVertex.z = Math.sin(-angle) * radius;
  37399. // normal
  37400. if (diameterTop === 0 && i === subdivisions) {
  37401. // if no top cap, reuse former normals
  37402. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37403. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37404. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37405. }
  37406. else {
  37407. ringNormal.x = ringVertex.x;
  37408. ringNormal.z = ringVertex.z;
  37409. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37410. ringNormal.normalize();
  37411. }
  37412. // keep first ring vertex values for enclose
  37413. if (j === 0) {
  37414. ringFirstVertex.copyFrom(ringVertex);
  37415. ringFirstNormal.copyFrom(ringNormal);
  37416. }
  37417. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37418. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37419. if (hasRings) {
  37420. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37421. }
  37422. else {
  37423. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37424. }
  37425. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37426. if (faceColors) {
  37427. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37428. }
  37429. }
  37430. // if enclose, add four vertices and their dedicated normals
  37431. if (arc !== 1 && enclose) {
  37432. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37433. positions.push(0, ringVertex.y, 0);
  37434. positions.push(0, ringVertex.y, 0);
  37435. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37436. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37437. quadNormal.normalize();
  37438. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37439. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37440. quadNormal.normalize();
  37441. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37442. if (hasRings) {
  37443. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37444. }
  37445. else {
  37446. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37447. }
  37448. uvs.push(faceUV[s + 1].x, v);
  37449. uvs.push(faceUV[s + 1].z, v);
  37450. if (hasRings) {
  37451. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37452. }
  37453. else {
  37454. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37455. }
  37456. uvs.push(faceUV[s + 2].x, v);
  37457. uvs.push(faceUV[s + 2].z, v);
  37458. if (faceColors) {
  37459. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37460. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37461. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37462. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37463. }
  37464. }
  37465. if (cs !== s) {
  37466. cs = s;
  37467. }
  37468. }
  37469. }
  37470. // indices
  37471. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37472. var s;
  37473. i = 0;
  37474. for (s = 0; s < subdivisions; s++) {
  37475. var i0 = 0;
  37476. var i1 = 0;
  37477. var i2 = 0;
  37478. var i3 = 0;
  37479. for (j = 0; j < tessellation; j++) {
  37480. i0 = i * (e + 1) + j;
  37481. i1 = (i + 1) * (e + 1) + j;
  37482. i2 = i * (e + 1) + (j + 1);
  37483. i3 = (i + 1) * (e + 1) + (j + 1);
  37484. indices.push(i0, i1, i2);
  37485. indices.push(i3, i2, i1);
  37486. }
  37487. if (arc !== 1 && enclose) { // if enclose, add two quads
  37488. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37489. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37490. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37491. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37492. }
  37493. i = (hasRings) ? (i + 2) : (i + 1);
  37494. }
  37495. // Caps
  37496. var createCylinderCap = function (isTop) {
  37497. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37498. if (radius === 0) {
  37499. return;
  37500. }
  37501. // Cap positions, normals & uvs
  37502. var angle;
  37503. var circleVector;
  37504. var i;
  37505. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37506. var c = null;
  37507. if (faceColors) {
  37508. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37509. }
  37510. // cap center
  37511. var vbase = positions.length / 3;
  37512. var offset = isTop ? height / 2 : -height / 2;
  37513. var center = new BABYLON.Vector3(0, offset, 0);
  37514. positions.push(center.x, center.y, center.z);
  37515. normals.push(0, isTop ? 1 : -1, 0);
  37516. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37517. if (c) {
  37518. colors.push(c.r, c.g, c.b, c.a);
  37519. }
  37520. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37521. for (i = 0; i <= tessellation; i++) {
  37522. angle = Math.PI * 2 * i * arc / tessellation;
  37523. var cos = Math.cos(-angle);
  37524. var sin = Math.sin(-angle);
  37525. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37526. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37527. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37528. normals.push(0, isTop ? 1 : -1, 0);
  37529. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37530. if (c) {
  37531. colors.push(c.r, c.g, c.b, c.a);
  37532. }
  37533. }
  37534. // Cap indices
  37535. for (i = 0; i < tessellation; i++) {
  37536. if (!isTop) {
  37537. indices.push(vbase);
  37538. indices.push(vbase + (i + 1));
  37539. indices.push(vbase + (i + 2));
  37540. }
  37541. else {
  37542. indices.push(vbase);
  37543. indices.push(vbase + (i + 2));
  37544. indices.push(vbase + (i + 1));
  37545. }
  37546. }
  37547. };
  37548. // add caps to geometry
  37549. createCylinderCap(false);
  37550. createCylinderCap(true);
  37551. // Sides
  37552. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37553. var vertexData = new VertexData();
  37554. vertexData.indices = indices;
  37555. vertexData.positions = positions;
  37556. vertexData.normals = normals;
  37557. vertexData.uvs = uvs;
  37558. if (faceColors) {
  37559. vertexData.colors = colors;
  37560. }
  37561. return vertexData;
  37562. };
  37563. /**
  37564. * Creates the VertexData for a torus
  37565. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37566. * * diameter the diameter of the torus, optional default 1
  37567. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37568. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37569. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37570. * * 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)
  37571. * * 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)
  37572. * @returns the VertexData of the torus
  37573. */
  37574. VertexData.CreateTorus = function (options) {
  37575. var indices = [];
  37576. var positions = [];
  37577. var normals = [];
  37578. var uvs = [];
  37579. var diameter = options.diameter || 1;
  37580. var thickness = options.thickness || 0.5;
  37581. var tessellation = options.tessellation || 16;
  37582. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37583. var stride = tessellation + 1;
  37584. for (var i = 0; i <= tessellation; i++) {
  37585. var u = i / tessellation;
  37586. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37587. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37588. for (var j = 0; j <= tessellation; j++) {
  37589. var v = 1 - j / tessellation;
  37590. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37591. var dx = Math.cos(innerAngle);
  37592. var dy = Math.sin(innerAngle);
  37593. // Create a vertex.
  37594. var normal = new BABYLON.Vector3(dx, dy, 0);
  37595. var position = normal.scale(thickness / 2);
  37596. var textureCoordinate = new BABYLON.Vector2(u, v);
  37597. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37598. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37599. positions.push(position.x, position.y, position.z);
  37600. normals.push(normal.x, normal.y, normal.z);
  37601. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37602. // And create indices for two triangles.
  37603. var nextI = (i + 1) % stride;
  37604. var nextJ = (j + 1) % stride;
  37605. indices.push(i * stride + j);
  37606. indices.push(i * stride + nextJ);
  37607. indices.push(nextI * stride + j);
  37608. indices.push(i * stride + nextJ);
  37609. indices.push(nextI * stride + nextJ);
  37610. indices.push(nextI * stride + j);
  37611. }
  37612. }
  37613. // Sides
  37614. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37615. // Result
  37616. var vertexData = new VertexData();
  37617. vertexData.indices = indices;
  37618. vertexData.positions = positions;
  37619. vertexData.normals = normals;
  37620. vertexData.uvs = uvs;
  37621. return vertexData;
  37622. };
  37623. /**
  37624. * Creates the VertexData of the LineSystem
  37625. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37626. * - lines an array of lines, each line being an array of successive Vector3
  37627. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37628. * @returns the VertexData of the LineSystem
  37629. */
  37630. VertexData.CreateLineSystem = function (options) {
  37631. var indices = [];
  37632. var positions = [];
  37633. var lines = options.lines;
  37634. var colors = options.colors;
  37635. var vertexColors = [];
  37636. var idx = 0;
  37637. for (var l = 0; l < lines.length; l++) {
  37638. var points = lines[l];
  37639. for (var index = 0; index < points.length; index++) {
  37640. positions.push(points[index].x, points[index].y, points[index].z);
  37641. if (colors) {
  37642. var color = colors[l];
  37643. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37644. }
  37645. if (index > 0) {
  37646. indices.push(idx - 1);
  37647. indices.push(idx);
  37648. }
  37649. idx++;
  37650. }
  37651. }
  37652. var vertexData = new VertexData();
  37653. vertexData.indices = indices;
  37654. vertexData.positions = positions;
  37655. if (colors) {
  37656. vertexData.colors = vertexColors;
  37657. }
  37658. return vertexData;
  37659. };
  37660. /**
  37661. * Create the VertexData for a DashedLines
  37662. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37663. * - points an array successive Vector3
  37664. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37665. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37666. * - dashNb the intended total number of dashes, optional, default 200
  37667. * @returns the VertexData for the DashedLines
  37668. */
  37669. VertexData.CreateDashedLines = function (options) {
  37670. var dashSize = options.dashSize || 3;
  37671. var gapSize = options.gapSize || 1;
  37672. var dashNb = options.dashNb || 200;
  37673. var points = options.points;
  37674. var positions = new Array();
  37675. var indices = new Array();
  37676. var curvect = BABYLON.Vector3.Zero();
  37677. var lg = 0;
  37678. var nb = 0;
  37679. var shft = 0;
  37680. var dashshft = 0;
  37681. var curshft = 0;
  37682. var idx = 0;
  37683. var i = 0;
  37684. for (i = 0; i < points.length - 1; i++) {
  37685. points[i + 1].subtractToRef(points[i], curvect);
  37686. lg += curvect.length();
  37687. }
  37688. shft = lg / dashNb;
  37689. dashshft = dashSize * shft / (dashSize + gapSize);
  37690. for (i = 0; i < points.length - 1; i++) {
  37691. points[i + 1].subtractToRef(points[i], curvect);
  37692. nb = Math.floor(curvect.length() / shft);
  37693. curvect.normalize();
  37694. for (var j = 0; j < nb; j++) {
  37695. curshft = shft * j;
  37696. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37697. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37698. indices.push(idx, idx + 1);
  37699. idx += 2;
  37700. }
  37701. }
  37702. // Result
  37703. var vertexData = new VertexData();
  37704. vertexData.positions = positions;
  37705. vertexData.indices = indices;
  37706. return vertexData;
  37707. };
  37708. /**
  37709. * Creates the VertexData for a Ground
  37710. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37711. * - width the width (x direction) of the ground, optional, default 1
  37712. * - height the height (z direction) of the ground, optional, default 1
  37713. * - subdivisions the number of subdivisions per side, optional, default 1
  37714. * @returns the VertexData of the Ground
  37715. */
  37716. VertexData.CreateGround = function (options) {
  37717. var indices = [];
  37718. var positions = [];
  37719. var normals = [];
  37720. var uvs = [];
  37721. var row, col;
  37722. var width = options.width || 1;
  37723. var height = options.height || 1;
  37724. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37725. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37726. for (row = 0; row <= subdivisionsY; row++) {
  37727. for (col = 0; col <= subdivisionsX; col++) {
  37728. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37729. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37730. positions.push(position.x, position.y, position.z);
  37731. normals.push(normal.x, normal.y, normal.z);
  37732. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37733. }
  37734. }
  37735. for (row = 0; row < subdivisionsY; row++) {
  37736. for (col = 0; col < subdivisionsX; col++) {
  37737. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37738. indices.push(col + 1 + row * (subdivisionsX + 1));
  37739. indices.push(col + row * (subdivisionsX + 1));
  37740. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37741. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37742. indices.push(col + row * (subdivisionsX + 1));
  37743. }
  37744. }
  37745. // Result
  37746. var vertexData = new VertexData();
  37747. vertexData.indices = indices;
  37748. vertexData.positions = positions;
  37749. vertexData.normals = normals;
  37750. vertexData.uvs = uvs;
  37751. return vertexData;
  37752. };
  37753. /**
  37754. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37755. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37756. * * xmin the ground minimum X coordinate, optional, default -1
  37757. * * zmin the ground minimum Z coordinate, optional, default -1
  37758. * * xmax the ground maximum X coordinate, optional, default 1
  37759. * * zmax the ground maximum Z coordinate, optional, default 1
  37760. * * 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}
  37761. * * 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}
  37762. * @returns the VertexData of the TiledGround
  37763. */
  37764. VertexData.CreateTiledGround = function (options) {
  37765. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37766. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37767. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37768. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37769. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37770. var precision = options.precision || { w: 1, h: 1 };
  37771. var indices = new Array();
  37772. var positions = new Array();
  37773. var normals = new Array();
  37774. var uvs = new Array();
  37775. var row, col, tileRow, tileCol;
  37776. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37777. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37778. precision.w = (precision.w < 1) ? 1 : precision.w;
  37779. precision.h = (precision.h < 1) ? 1 : precision.h;
  37780. var tileSize = {
  37781. 'w': (xmax - xmin) / subdivisions.w,
  37782. 'h': (zmax - zmin) / subdivisions.h
  37783. };
  37784. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37785. // Indices
  37786. var base = positions.length / 3;
  37787. var rowLength = precision.w + 1;
  37788. for (row = 0; row < precision.h; row++) {
  37789. for (col = 0; col < precision.w; col++) {
  37790. var square = [
  37791. base + col + row * rowLength,
  37792. base + (col + 1) + row * rowLength,
  37793. base + (col + 1) + (row + 1) * rowLength,
  37794. base + col + (row + 1) * rowLength
  37795. ];
  37796. indices.push(square[1]);
  37797. indices.push(square[2]);
  37798. indices.push(square[3]);
  37799. indices.push(square[0]);
  37800. indices.push(square[1]);
  37801. indices.push(square[3]);
  37802. }
  37803. }
  37804. // Position, normals and uvs
  37805. var position = BABYLON.Vector3.Zero();
  37806. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37807. for (row = 0; row <= precision.h; row++) {
  37808. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37809. for (col = 0; col <= precision.w; col++) {
  37810. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37811. position.y = 0;
  37812. positions.push(position.x, position.y, position.z);
  37813. normals.push(normal.x, normal.y, normal.z);
  37814. uvs.push(col / precision.w, row / precision.h);
  37815. }
  37816. }
  37817. }
  37818. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37819. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37820. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37821. }
  37822. }
  37823. // Result
  37824. var vertexData = new VertexData();
  37825. vertexData.indices = indices;
  37826. vertexData.positions = positions;
  37827. vertexData.normals = normals;
  37828. vertexData.uvs = uvs;
  37829. return vertexData;
  37830. };
  37831. /**
  37832. * Creates the VertexData of the Ground designed from a heightmap
  37833. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37834. * * width the width (x direction) of the ground
  37835. * * height the height (z direction) of the ground
  37836. * * subdivisions the number of subdivisions per side
  37837. * * minHeight the minimum altitude on the ground, optional, default 0
  37838. * * maxHeight the maximum altitude on the ground, optional default 1
  37839. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37840. * * buffer the array holding the image color data
  37841. * * bufferWidth the width of image
  37842. * * bufferHeight the height of image
  37843. * @returns the VertexData of the Ground designed from a heightmap
  37844. */
  37845. VertexData.CreateGroundFromHeightMap = function (options) {
  37846. var indices = [];
  37847. var positions = [];
  37848. var normals = [];
  37849. var uvs = [];
  37850. var row, col;
  37851. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37852. // Vertices
  37853. for (row = 0; row <= options.subdivisions; row++) {
  37854. for (col = 0; col <= options.subdivisions; col++) {
  37855. 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));
  37856. // Compute height
  37857. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37858. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37859. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37860. var r = options.buffer[pos] / 255.0;
  37861. var g = options.buffer[pos + 1] / 255.0;
  37862. var b = options.buffer[pos + 2] / 255.0;
  37863. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37864. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37865. // Add vertex
  37866. positions.push(position.x, position.y, position.z);
  37867. normals.push(0, 0, 0);
  37868. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37869. }
  37870. }
  37871. // Indices
  37872. for (row = 0; row < options.subdivisions; row++) {
  37873. for (col = 0; col < options.subdivisions; col++) {
  37874. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37875. indices.push(col + 1 + row * (options.subdivisions + 1));
  37876. indices.push(col + row * (options.subdivisions + 1));
  37877. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37878. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37879. indices.push(col + row * (options.subdivisions + 1));
  37880. }
  37881. }
  37882. // Normals
  37883. VertexData.ComputeNormals(positions, indices, normals);
  37884. // Result
  37885. var vertexData = new VertexData();
  37886. vertexData.indices = indices;
  37887. vertexData.positions = positions;
  37888. vertexData.normals = normals;
  37889. vertexData.uvs = uvs;
  37890. return vertexData;
  37891. };
  37892. /**
  37893. * Creates the VertexData for a Plane
  37894. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37895. * * size sets the width and height of the plane to the value of size, optional default 1
  37896. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37897. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37898. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37899. * * 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)
  37900. * * 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)
  37901. * @returns the VertexData of the box
  37902. */
  37903. VertexData.CreatePlane = function (options) {
  37904. var indices = [];
  37905. var positions = [];
  37906. var normals = [];
  37907. var uvs = [];
  37908. var width = options.width || options.size || 1;
  37909. var height = options.height || options.size || 1;
  37910. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37911. // Vertices
  37912. var halfWidth = width / 2.0;
  37913. var halfHeight = height / 2.0;
  37914. positions.push(-halfWidth, -halfHeight, 0);
  37915. normals.push(0, 0, -1.0);
  37916. uvs.push(0.0, 0.0);
  37917. positions.push(halfWidth, -halfHeight, 0);
  37918. normals.push(0, 0, -1.0);
  37919. uvs.push(1.0, 0.0);
  37920. positions.push(halfWidth, halfHeight, 0);
  37921. normals.push(0, 0, -1.0);
  37922. uvs.push(1.0, 1.0);
  37923. positions.push(-halfWidth, halfHeight, 0);
  37924. normals.push(0, 0, -1.0);
  37925. uvs.push(0.0, 1.0);
  37926. // Indices
  37927. indices.push(0);
  37928. indices.push(1);
  37929. indices.push(2);
  37930. indices.push(0);
  37931. indices.push(2);
  37932. indices.push(3);
  37933. // Sides
  37934. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37935. // Result
  37936. var vertexData = new VertexData();
  37937. vertexData.indices = indices;
  37938. vertexData.positions = positions;
  37939. vertexData.normals = normals;
  37940. vertexData.uvs = uvs;
  37941. return vertexData;
  37942. };
  37943. /**
  37944. * Creates the VertexData of the Disc or regular Polygon
  37945. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37946. * * radius the radius of the disc, optional default 0.5
  37947. * * tessellation the number of polygon sides, optional, default 64
  37948. * * 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
  37949. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37950. * * 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)
  37951. * * 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)
  37952. * @returns the VertexData of the box
  37953. */
  37954. VertexData.CreateDisc = function (options) {
  37955. var positions = new Array();
  37956. var indices = new Array();
  37957. var normals = new Array();
  37958. var uvs = new Array();
  37959. var radius = options.radius || 0.5;
  37960. var tessellation = options.tessellation || 64;
  37961. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37962. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37963. // positions and uvs
  37964. positions.push(0, 0, 0); // disc center first
  37965. uvs.push(0.5, 0.5);
  37966. var theta = Math.PI * 2 * arc;
  37967. var step = theta / tessellation;
  37968. for (var a = 0; a < theta; a += step) {
  37969. var x = Math.cos(a);
  37970. var y = Math.sin(a);
  37971. var u = (x + 1) / 2;
  37972. var v = (1 - y) / 2;
  37973. positions.push(radius * x, radius * y, 0);
  37974. uvs.push(u, v);
  37975. }
  37976. if (arc === 1) {
  37977. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37978. uvs.push(uvs[2], uvs[3]);
  37979. }
  37980. //indices
  37981. var vertexNb = positions.length / 3;
  37982. for (var i = 1; i < vertexNb - 1; i++) {
  37983. indices.push(i + 1, 0, i);
  37984. }
  37985. // result
  37986. VertexData.ComputeNormals(positions, indices, normals);
  37987. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37988. var vertexData = new VertexData();
  37989. vertexData.indices = indices;
  37990. vertexData.positions = positions;
  37991. vertexData.normals = normals;
  37992. vertexData.uvs = uvs;
  37993. return vertexData;
  37994. };
  37995. /**
  37996. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37997. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37998. * @param polygon a mesh built from polygonTriangulation.build()
  37999. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38000. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38001. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38002. * @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)
  38003. * @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)
  38004. * @returns the VertexData of the Polygon
  38005. */
  38006. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  38007. var faceUV = fUV || new Array(3);
  38008. var faceColors = fColors;
  38009. var colors = [];
  38010. // default face colors and UV if undefined
  38011. for (var f = 0; f < 3; f++) {
  38012. if (faceUV[f] === undefined) {
  38013. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38014. }
  38015. if (faceColors && faceColors[f] === undefined) {
  38016. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38017. }
  38018. }
  38019. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38020. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38021. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38022. var indices = polygon.getIndices();
  38023. // set face colours and textures
  38024. var idx = 0;
  38025. var face = 0;
  38026. for (var index = 0; index < normals.length; index += 3) {
  38027. //Edge Face no. 1
  38028. if (Math.abs(normals[index + 1]) < 0.001) {
  38029. face = 1;
  38030. }
  38031. //Top Face no. 0
  38032. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  38033. face = 0;
  38034. }
  38035. //Bottom Face no. 2
  38036. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  38037. face = 2;
  38038. }
  38039. idx = index / 3;
  38040. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  38041. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  38042. if (faceColors) {
  38043. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  38044. }
  38045. }
  38046. // sides
  38047. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  38048. // Result
  38049. var vertexData = new VertexData();
  38050. vertexData.indices = indices;
  38051. vertexData.positions = positions;
  38052. vertexData.normals = normals;
  38053. vertexData.uvs = uvs;
  38054. if (faceColors) {
  38055. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38056. vertexData.colors = totalColors;
  38057. }
  38058. return vertexData;
  38059. };
  38060. /**
  38061. * Creates the VertexData of the IcoSphere
  38062. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  38063. * * radius the radius of the IcoSphere, optional default 1
  38064. * * radiusX allows stretching in the x direction, optional, default radius
  38065. * * radiusY allows stretching in the y direction, optional, default radius
  38066. * * radiusZ allows stretching in the z direction, optional, default radius
  38067. * * flat when true creates a flat shaded mesh, optional, default true
  38068. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38069. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38070. * * 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)
  38071. * * 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)
  38072. * @returns the VertexData of the IcoSphere
  38073. */
  38074. VertexData.CreateIcoSphere = function (options) {
  38075. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38076. var radius = options.radius || 1;
  38077. var flat = (options.flat === undefined) ? true : options.flat;
  38078. var subdivisions = options.subdivisions || 4;
  38079. var radiusX = options.radiusX || radius;
  38080. var radiusY = options.radiusY || radius;
  38081. var radiusZ = options.radiusZ || radius;
  38082. var t = (1 + Math.sqrt(5)) / 2;
  38083. // 12 vertex x,y,z
  38084. var ico_vertices = [
  38085. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  38086. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  38087. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  38088. ];
  38089. // index of 3 vertex makes a face of icopshere
  38090. var ico_indices = [
  38091. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  38092. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  38093. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  38094. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  38095. ];
  38096. // vertex for uv have aliased position, not for UV
  38097. var vertices_unalias_id = [
  38098. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  38099. // vertex alias
  38100. 0,
  38101. 2,
  38102. 3,
  38103. 3,
  38104. 3,
  38105. 4,
  38106. 7,
  38107. 8,
  38108. 9,
  38109. 9,
  38110. 10,
  38111. 11 // 23: B + 12
  38112. ];
  38113. // uv as integer step (not pixels !)
  38114. var ico_vertexuv = [
  38115. 5, 1, 3, 1, 6, 4, 0, 0,
  38116. 5, 3, 4, 2, 2, 2, 4, 0,
  38117. 2, 0, 1, 1, 6, 0, 6, 2,
  38118. // vertex alias (for same vertex on different faces)
  38119. 0, 4,
  38120. 3, 3,
  38121. 4, 4,
  38122. 3, 1,
  38123. 4, 2,
  38124. 4, 4,
  38125. 0, 2,
  38126. 1, 1,
  38127. 2, 2,
  38128. 3, 3,
  38129. 1, 3,
  38130. 2, 4 // 23: B + 12
  38131. ];
  38132. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38133. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38134. // First island of uv mapping
  38135. // v = 4h 3+ 2
  38136. // v = 3h 9+ 4
  38137. // v = 2h 9+ 5 B
  38138. // v = 1h 9 1 0
  38139. // v = 0h 3 8 7 A
  38140. // u = 0 1 2 3 4 5 6 *a
  38141. // Second island of uv mapping
  38142. // v = 4h 0+ B+ 4+
  38143. // v = 3h A+ 2+
  38144. // v = 2h 7+ 6 3+
  38145. // v = 1h 8+ 3+
  38146. // v = 0h
  38147. // u = 0 1 2 3 4 5 6 *a
  38148. // Face layout on texture UV mapping
  38149. // ============
  38150. // \ 4 /\ 16 / ======
  38151. // \ / \ / /\ 11 /
  38152. // \/ 7 \/ / \ /
  38153. // ======= / 10 \/
  38154. // /\ 17 /\ =======
  38155. // / \ / \ \ 15 /\
  38156. // / 8 \/ 12 \ \ / \
  38157. // ============ \/ 6 \
  38158. // \ 18 /\ ============
  38159. // \ / \ \ 5 /\ 0 /
  38160. // \/ 13 \ \ / \ /
  38161. // ======= \/ 1 \/
  38162. // =============
  38163. // /\ 19 /\ 2 /\
  38164. // / \ / \ / \
  38165. // / 14 \/ 9 \/ 3 \
  38166. // ===================
  38167. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38168. var ustep = 138 / 1024;
  38169. var vstep = 239 / 1024;
  38170. var uoffset = 60 / 1024;
  38171. var voffset = 26 / 1024;
  38172. // Second island should have margin, not to touch the first island
  38173. // avoid any borderline artefact in pixel rounding
  38174. var island_u_offset = -40 / 1024;
  38175. var island_v_offset = +20 / 1024;
  38176. // face is either island 0 or 1 :
  38177. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38178. var island = [
  38179. 0, 0, 0, 0, 1,
  38180. 0, 0, 1, 1, 0,
  38181. 0, 0, 1, 1, 0,
  38182. 0, 1, 1, 1, 0 // 15 - 19
  38183. ];
  38184. var indices = new Array();
  38185. var positions = new Array();
  38186. var normals = new Array();
  38187. var uvs = new Array();
  38188. var current_indice = 0;
  38189. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38190. var face_vertex_pos = new Array(3);
  38191. var face_vertex_uv = new Array(3);
  38192. var v012;
  38193. for (v012 = 0; v012 < 3; v012++) {
  38194. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38195. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38196. }
  38197. // create all with normals
  38198. for (var face = 0; face < 20; face++) {
  38199. // 3 vertex per face
  38200. for (v012 = 0; v012 < 3; v012++) {
  38201. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38202. var v_id = ico_indices[3 * face + v012];
  38203. // vertex have 3D position (x,y,z)
  38204. 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]);
  38205. // Normalize to get normal, then scale to radius
  38206. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38207. // uv Coordinates from vertex ID
  38208. 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);
  38209. }
  38210. // Subdivide the face (interpolate pos, norm, uv)
  38211. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38212. // - norm is linear interpolation of vertex corner normal
  38213. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38214. // - uv is linear interpolation
  38215. //
  38216. // Topology is as below for sub-divide by 2
  38217. // vertex shown as v0,v1,v2
  38218. // interp index is i1 to progress in range [v0,v1[
  38219. // interp index is i2 to progress in range [v0,v2[
  38220. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38221. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38222. //
  38223. //
  38224. // i2 v2
  38225. // ^ ^
  38226. // / / \
  38227. // / / \
  38228. // / / \
  38229. // / / (0,1) \
  38230. // / #---------\
  38231. // / / \ (0,0)'/ \
  38232. // / / \ / \
  38233. // / / \ / \
  38234. // / / (0,0) \ / (1,0) \
  38235. // / #---------#---------\
  38236. // v0 v1
  38237. //
  38238. // --------------------> i1
  38239. //
  38240. // interp of (i1,i2):
  38241. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38242. // along i1 : lerp(x0,x1, i1/(S-i2))
  38243. //
  38244. // centroid of triangle is needed to get help normal computation
  38245. // (c1,c2) are used for centroid location
  38246. var interp_vertex = function (i1, i2, c1, c2) {
  38247. // vertex is interpolated from
  38248. // - face_vertex_pos[0..2]
  38249. // - face_vertex_uv[0..2]
  38250. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38251. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38252. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38253. pos_interp.normalize();
  38254. var vertex_normal;
  38255. if (flat) {
  38256. // in flat mode, recalculate normal as face centroid normal
  38257. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38258. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38259. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38260. }
  38261. else {
  38262. // in smooth mode, recalculate normal from each single vertex position
  38263. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38264. }
  38265. // Vertex normal need correction due to X,Y,Z radius scaling
  38266. vertex_normal.x /= radiusX;
  38267. vertex_normal.y /= radiusY;
  38268. vertex_normal.z /= radiusZ;
  38269. vertex_normal.normalize();
  38270. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38271. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38272. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38273. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38274. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38275. uvs.push(uv_interp.x, uv_interp.y);
  38276. // push each vertex has member of a face
  38277. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38278. indices.push(current_indice);
  38279. current_indice++;
  38280. };
  38281. for (var i2 = 0; i2 < subdivisions; i2++) {
  38282. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38283. // face : (i1,i2) for /\ :
  38284. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38285. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38286. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38287. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38288. if (i1 + i2 + 1 < subdivisions) {
  38289. // face : (i1,i2)' for \/ :
  38290. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38291. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38292. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38293. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38294. }
  38295. }
  38296. }
  38297. }
  38298. // Sides
  38299. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38300. // Result
  38301. var vertexData = new VertexData();
  38302. vertexData.indices = indices;
  38303. vertexData.positions = positions;
  38304. vertexData.normals = normals;
  38305. vertexData.uvs = uvs;
  38306. return vertexData;
  38307. };
  38308. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38309. /**
  38310. * Creates the VertexData for a Polyhedron
  38311. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38312. * * type provided types are:
  38313. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38314. * * 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)
  38315. * * size the size of the IcoSphere, optional default 1
  38316. * * sizeX allows stretching in the x direction, optional, default size
  38317. * * sizeY allows stretching in the y direction, optional, default size
  38318. * * sizeZ allows stretching in the z direction, optional, default size
  38319. * * 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
  38320. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38321. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38322. * * flat when true creates a flat shaded mesh, optional, default true
  38323. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38324. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38325. * * 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)
  38326. * * 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)
  38327. * @returns the VertexData of the Polyhedron
  38328. */
  38329. VertexData.CreatePolyhedron = function (options) {
  38330. // provided polyhedron types :
  38331. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38332. // 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)
  38333. var polyhedra = [];
  38334. 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]] };
  38335. 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]] };
  38336. polyhedra[2] = {
  38337. 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]],
  38338. 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]]
  38339. };
  38340. polyhedra[3] = {
  38341. 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]],
  38342. 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]]
  38343. };
  38344. polyhedra[4] = {
  38345. 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]],
  38346. 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]]
  38347. };
  38348. 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]] };
  38349. 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]] };
  38350. 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]] };
  38351. 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]] };
  38352. 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]] };
  38353. 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]] };
  38354. 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]] };
  38355. 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]] };
  38356. 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]] };
  38357. polyhedra[14] = {
  38358. 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]],
  38359. 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]]
  38360. };
  38361. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38362. var size = options.size;
  38363. var sizeX = options.sizeX || size || 1;
  38364. var sizeY = options.sizeY || size || 1;
  38365. var sizeZ = options.sizeZ || size || 1;
  38366. var data = options.custom || polyhedra[type];
  38367. var nbfaces = data.face.length;
  38368. var faceUV = options.faceUV || new Array(nbfaces);
  38369. var faceColors = options.faceColors;
  38370. var flat = (options.flat === undefined) ? true : options.flat;
  38371. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38372. var positions = new Array();
  38373. var indices = new Array();
  38374. var normals = new Array();
  38375. var uvs = new Array();
  38376. var colors = new Array();
  38377. var index = 0;
  38378. var faceIdx = 0; // face cursor in the array "indexes"
  38379. var indexes = new Array();
  38380. var i = 0;
  38381. var f = 0;
  38382. var u, v, ang, x, y, tmp;
  38383. // default face colors and UV if undefined
  38384. if (flat) {
  38385. for (f = 0; f < nbfaces; f++) {
  38386. if (faceColors && faceColors[f] === undefined) {
  38387. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38388. }
  38389. if (faceUV && faceUV[f] === undefined) {
  38390. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38391. }
  38392. }
  38393. }
  38394. if (!flat) {
  38395. for (i = 0; i < data.vertex.length; i++) {
  38396. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38397. uvs.push(0, 0);
  38398. }
  38399. for (f = 0; f < nbfaces; f++) {
  38400. for (i = 0; i < data.face[f].length - 2; i++) {
  38401. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38402. }
  38403. }
  38404. }
  38405. else {
  38406. for (f = 0; f < nbfaces; f++) {
  38407. var fl = data.face[f].length; // number of vertices of the current face
  38408. ang = 2 * Math.PI / fl;
  38409. x = 0.5 * Math.tan(ang / 2);
  38410. y = 0.5;
  38411. // positions, uvs, colors
  38412. for (i = 0; i < fl; i++) {
  38413. // positions
  38414. 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);
  38415. indexes.push(index);
  38416. index++;
  38417. // uvs
  38418. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38419. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38420. uvs.push(u, v);
  38421. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38422. y = x * Math.sin(ang) + y * Math.cos(ang);
  38423. x = tmp;
  38424. // colors
  38425. if (faceColors) {
  38426. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38427. }
  38428. }
  38429. // indices from indexes
  38430. for (i = 0; i < fl - 2; i++) {
  38431. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38432. }
  38433. faceIdx += fl;
  38434. }
  38435. }
  38436. VertexData.ComputeNormals(positions, indices, normals);
  38437. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38438. var vertexData = new VertexData();
  38439. vertexData.positions = positions;
  38440. vertexData.indices = indices;
  38441. vertexData.normals = normals;
  38442. vertexData.uvs = uvs;
  38443. if (faceColors && flat) {
  38444. vertexData.colors = colors;
  38445. }
  38446. return vertexData;
  38447. };
  38448. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38449. /**
  38450. * Creates the VertexData for a TorusKnot
  38451. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38452. * * radius the radius of the torus knot, optional, default 2
  38453. * * tube the thickness of the tube, optional, default 0.5
  38454. * * radialSegments the number of sides on each tube segments, optional, default 32
  38455. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38456. * * p the number of windings around the z axis, optional, default 2
  38457. * * q the number of windings around the x axis, optional, default 3
  38458. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38459. * * 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)
  38460. * * 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)
  38461. * @returns the VertexData of the Torus Knot
  38462. */
  38463. VertexData.CreateTorusKnot = function (options) {
  38464. var indices = new Array();
  38465. var positions = new Array();
  38466. var normals = new Array();
  38467. var uvs = new Array();
  38468. var radius = options.radius || 2;
  38469. var tube = options.tube || 0.5;
  38470. var radialSegments = options.radialSegments || 32;
  38471. var tubularSegments = options.tubularSegments || 32;
  38472. var p = options.p || 2;
  38473. var q = options.q || 3;
  38474. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38475. // Helper
  38476. var getPos = function (angle) {
  38477. var cu = Math.cos(angle);
  38478. var su = Math.sin(angle);
  38479. var quOverP = q / p * angle;
  38480. var cs = Math.cos(quOverP);
  38481. var tx = radius * (2 + cs) * 0.5 * cu;
  38482. var ty = radius * (2 + cs) * su * 0.5;
  38483. var tz = radius * Math.sin(quOverP) * 0.5;
  38484. return new BABYLON.Vector3(tx, ty, tz);
  38485. };
  38486. // Vertices
  38487. var i;
  38488. var j;
  38489. for (i = 0; i <= radialSegments; i++) {
  38490. var modI = i % radialSegments;
  38491. var u = modI / radialSegments * 2 * p * Math.PI;
  38492. var p1 = getPos(u);
  38493. var p2 = getPos(u + 0.01);
  38494. var tang = p2.subtract(p1);
  38495. var n = p2.add(p1);
  38496. var bitan = BABYLON.Vector3.Cross(tang, n);
  38497. n = BABYLON.Vector3.Cross(bitan, tang);
  38498. bitan.normalize();
  38499. n.normalize();
  38500. for (j = 0; j < tubularSegments; j++) {
  38501. var modJ = j % tubularSegments;
  38502. var v = modJ / tubularSegments * 2 * Math.PI;
  38503. var cx = -tube * Math.cos(v);
  38504. var cy = tube * Math.sin(v);
  38505. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38506. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38507. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38508. uvs.push(i / radialSegments);
  38509. uvs.push(j / tubularSegments);
  38510. }
  38511. }
  38512. for (i = 0; i < radialSegments; i++) {
  38513. for (j = 0; j < tubularSegments; j++) {
  38514. var jNext = (j + 1) % tubularSegments;
  38515. var a = i * tubularSegments + j;
  38516. var b = (i + 1) * tubularSegments + j;
  38517. var c = (i + 1) * tubularSegments + jNext;
  38518. var d = i * tubularSegments + jNext;
  38519. indices.push(d);
  38520. indices.push(b);
  38521. indices.push(a);
  38522. indices.push(d);
  38523. indices.push(c);
  38524. indices.push(b);
  38525. }
  38526. }
  38527. // Normals
  38528. VertexData.ComputeNormals(positions, indices, normals);
  38529. // Sides
  38530. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38531. // Result
  38532. var vertexData = new VertexData();
  38533. vertexData.indices = indices;
  38534. vertexData.positions = positions;
  38535. vertexData.normals = normals;
  38536. vertexData.uvs = uvs;
  38537. return vertexData;
  38538. };
  38539. // Tools
  38540. /**
  38541. * Compute normals for given positions and indices
  38542. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38543. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38544. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38545. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38546. * * facetNormals : optional array of facet normals (vector3)
  38547. * * facetPositions : optional array of facet positions (vector3)
  38548. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38549. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38550. * * bInfo : optional bounding info, required for facetPartitioning computation
  38551. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38552. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38553. * * useRightHandedSystem: optional boolean to for right handed system computation
  38554. * * depthSort : optional boolean to enable the facet depth sort computation
  38555. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38556. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38557. */
  38558. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38559. // temporary scalar variables
  38560. var index = 0; // facet index
  38561. var p1p2x = 0.0; // p1p2 vector x coordinate
  38562. var p1p2y = 0.0; // p1p2 vector y coordinate
  38563. var p1p2z = 0.0; // p1p2 vector z coordinate
  38564. var p3p2x = 0.0; // p3p2 vector x coordinate
  38565. var p3p2y = 0.0; // p3p2 vector y coordinate
  38566. var p3p2z = 0.0; // p3p2 vector z coordinate
  38567. var faceNormalx = 0.0; // facet normal x coordinate
  38568. var faceNormaly = 0.0; // facet normal y coordinate
  38569. var faceNormalz = 0.0; // facet normal z coordinate
  38570. var length = 0.0; // facet normal length before normalization
  38571. var v1x = 0; // vector1 x index in the positions array
  38572. var v1y = 0; // vector1 y index in the positions array
  38573. var v1z = 0; // vector1 z index in the positions array
  38574. var v2x = 0; // vector2 x index in the positions array
  38575. var v2y = 0; // vector2 y index in the positions array
  38576. var v2z = 0; // vector2 z index in the positions array
  38577. var v3x = 0; // vector3 x index in the positions array
  38578. var v3y = 0; // vector3 y index in the positions array
  38579. var v3z = 0; // vector3 z index in the positions array
  38580. var computeFacetNormals = false;
  38581. var computeFacetPositions = false;
  38582. var computeFacetPartitioning = false;
  38583. var computeDepthSort = false;
  38584. var faceNormalSign = 1;
  38585. var ratio = 0;
  38586. var distanceTo = null;
  38587. if (options) {
  38588. computeFacetNormals = (options.facetNormals) ? true : false;
  38589. computeFacetPositions = (options.facetPositions) ? true : false;
  38590. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38591. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38592. ratio = options.ratio || 0;
  38593. computeDepthSort = (options.depthSort) ? true : false;
  38594. distanceTo = (options.distanceTo);
  38595. if (computeDepthSort) {
  38596. if (distanceTo === undefined) {
  38597. distanceTo = BABYLON.Vector3.Zero();
  38598. }
  38599. var depthSortedFacets = options.depthSortedFacets;
  38600. }
  38601. }
  38602. // facetPartitioning reinit if needed
  38603. var xSubRatio = 0;
  38604. var ySubRatio = 0;
  38605. var zSubRatio = 0;
  38606. var subSq = 0;
  38607. if (computeFacetPartitioning && options && options.bbSize) {
  38608. var ox = 0; // X partitioning index for facet position
  38609. var oy = 0; // Y partinioning index for facet position
  38610. var oz = 0; // Z partinioning index for facet position
  38611. var b1x = 0; // X partitioning index for facet v1 vertex
  38612. var b1y = 0; // Y partitioning index for facet v1 vertex
  38613. var b1z = 0; // z partitioning index for facet v1 vertex
  38614. var b2x = 0; // X partitioning index for facet v2 vertex
  38615. var b2y = 0; // Y partitioning index for facet v2 vertex
  38616. var b2z = 0; // Z partitioning index for facet v2 vertex
  38617. var b3x = 0; // X partitioning index for facet v3 vertex
  38618. var b3y = 0; // Y partitioning index for facet v3 vertex
  38619. var b3z = 0; // Z partitioning index for facet v3 vertex
  38620. var block_idx_o = 0; // facet barycenter block index
  38621. var block_idx_v1 = 0; // v1 vertex block index
  38622. var block_idx_v2 = 0; // v2 vertex block index
  38623. var block_idx_v3 = 0; // v3 vertex block index
  38624. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38625. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38626. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38627. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38628. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38629. subSq = options.subDiv.max * options.subDiv.max;
  38630. options.facetPartitioning.length = 0;
  38631. }
  38632. // reset the normals
  38633. for (index = 0; index < positions.length; index++) {
  38634. normals[index] = 0.0;
  38635. }
  38636. // Loop : 1 indice triplet = 1 facet
  38637. var nbFaces = (indices.length / 3) | 0;
  38638. for (index = 0; index < nbFaces; index++) {
  38639. // get the indexes of the coordinates of each vertex of the facet
  38640. v1x = indices[index * 3] * 3;
  38641. v1y = v1x + 1;
  38642. v1z = v1x + 2;
  38643. v2x = indices[index * 3 + 1] * 3;
  38644. v2y = v2x + 1;
  38645. v2z = v2x + 2;
  38646. v3x = indices[index * 3 + 2] * 3;
  38647. v3y = v3x + 1;
  38648. v3z = v3x + 2;
  38649. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38650. p1p2y = positions[v1y] - positions[v2y];
  38651. p1p2z = positions[v1z] - positions[v2z];
  38652. p3p2x = positions[v3x] - positions[v2x];
  38653. p3p2y = positions[v3y] - positions[v2y];
  38654. p3p2z = positions[v3z] - positions[v2z];
  38655. // compute the face normal with the cross product
  38656. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38657. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38658. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38659. // normalize this normal and store it in the array facetData
  38660. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38661. length = (length === 0) ? 1.0 : length;
  38662. faceNormalx /= length;
  38663. faceNormaly /= length;
  38664. faceNormalz /= length;
  38665. if (computeFacetNormals && options) {
  38666. options.facetNormals[index].x = faceNormalx;
  38667. options.facetNormals[index].y = faceNormaly;
  38668. options.facetNormals[index].z = faceNormalz;
  38669. }
  38670. if (computeFacetPositions && options) {
  38671. // compute and the facet barycenter coordinates in the array facetPositions
  38672. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38673. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38674. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38675. }
  38676. if (computeFacetPartitioning && options) {
  38677. // store the facet indexes in arrays in the main facetPartitioning array :
  38678. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38679. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38680. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38681. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38682. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38683. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38684. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38685. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38686. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38687. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38688. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38689. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38690. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38691. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38692. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38693. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38694. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38695. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38696. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38697. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38698. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38699. // push each facet index in each block containing the vertex
  38700. options.facetPartitioning[block_idx_v1].push(index);
  38701. if (block_idx_v2 != block_idx_v1) {
  38702. options.facetPartitioning[block_idx_v2].push(index);
  38703. }
  38704. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38705. options.facetPartitioning[block_idx_v3].push(index);
  38706. }
  38707. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38708. options.facetPartitioning[block_idx_o].push(index);
  38709. }
  38710. }
  38711. if (computeDepthSort && options && options.facetPositions) {
  38712. var dsf = depthSortedFacets[index];
  38713. dsf.ind = index * 3;
  38714. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38715. }
  38716. // compute the normals anyway
  38717. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38718. normals[v1y] += faceNormaly;
  38719. normals[v1z] += faceNormalz;
  38720. normals[v2x] += faceNormalx;
  38721. normals[v2y] += faceNormaly;
  38722. normals[v2z] += faceNormalz;
  38723. normals[v3x] += faceNormalx;
  38724. normals[v3y] += faceNormaly;
  38725. normals[v3z] += faceNormalz;
  38726. }
  38727. // last normalization of each normal
  38728. for (index = 0; index < normals.length / 3; index++) {
  38729. faceNormalx = normals[index * 3];
  38730. faceNormaly = normals[index * 3 + 1];
  38731. faceNormalz = normals[index * 3 + 2];
  38732. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38733. length = (length === 0) ? 1.0 : length;
  38734. faceNormalx /= length;
  38735. faceNormaly /= length;
  38736. faceNormalz /= length;
  38737. normals[index * 3] = faceNormalx;
  38738. normals[index * 3 + 1] = faceNormaly;
  38739. normals[index * 3 + 2] = faceNormalz;
  38740. }
  38741. };
  38742. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38743. var li = indices.length;
  38744. var ln = normals.length;
  38745. var i;
  38746. var n;
  38747. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38748. switch (sideOrientation) {
  38749. case BABYLON.Mesh.FRONTSIDE:
  38750. // nothing changed
  38751. break;
  38752. case BABYLON.Mesh.BACKSIDE:
  38753. var tmp;
  38754. // indices
  38755. for (i = 0; i < li; i += 3) {
  38756. tmp = indices[i];
  38757. indices[i] = indices[i + 2];
  38758. indices[i + 2] = tmp;
  38759. }
  38760. // normals
  38761. for (n = 0; n < ln; n++) {
  38762. normals[n] = -normals[n];
  38763. }
  38764. break;
  38765. case BABYLON.Mesh.DOUBLESIDE:
  38766. // positions
  38767. var lp = positions.length;
  38768. var l = lp / 3;
  38769. for (var p = 0; p < lp; p++) {
  38770. positions[lp + p] = positions[p];
  38771. }
  38772. // indices
  38773. for (i = 0; i < li; i += 3) {
  38774. indices[i + li] = indices[i + 2] + l;
  38775. indices[i + 1 + li] = indices[i + 1] + l;
  38776. indices[i + 2 + li] = indices[i] + l;
  38777. }
  38778. // normals
  38779. for (n = 0; n < ln; n++) {
  38780. normals[ln + n] = -normals[n];
  38781. }
  38782. // uvs
  38783. var lu = uvs.length;
  38784. var u = 0;
  38785. for (u = 0; u < lu; u++) {
  38786. uvs[u + lu] = uvs[u];
  38787. }
  38788. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38789. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38790. u = 0;
  38791. for (i = 0; i < lu / 2; i++) {
  38792. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38793. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38794. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38795. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38796. u += 2;
  38797. }
  38798. break;
  38799. }
  38800. };
  38801. /**
  38802. * Applies VertexData created from the imported parameters to the geometry
  38803. * @param parsedVertexData the parsed data from an imported file
  38804. * @param geometry the geometry to apply the VertexData to
  38805. */
  38806. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38807. var vertexData = new VertexData();
  38808. // positions
  38809. var positions = parsedVertexData.positions;
  38810. if (positions) {
  38811. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38812. }
  38813. // normals
  38814. var normals = parsedVertexData.normals;
  38815. if (normals) {
  38816. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38817. }
  38818. // tangents
  38819. var tangents = parsedVertexData.tangents;
  38820. if (tangents) {
  38821. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38822. }
  38823. // uvs
  38824. var uvs = parsedVertexData.uvs;
  38825. if (uvs) {
  38826. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38827. }
  38828. // uv2s
  38829. var uv2s = parsedVertexData.uv2s;
  38830. if (uv2s) {
  38831. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38832. }
  38833. // uv3s
  38834. var uv3s = parsedVertexData.uv3s;
  38835. if (uv3s) {
  38836. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38837. }
  38838. // uv4s
  38839. var uv4s = parsedVertexData.uv4s;
  38840. if (uv4s) {
  38841. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38842. }
  38843. // uv5s
  38844. var uv5s = parsedVertexData.uv5s;
  38845. if (uv5s) {
  38846. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38847. }
  38848. // uv6s
  38849. var uv6s = parsedVertexData.uv6s;
  38850. if (uv6s) {
  38851. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38852. }
  38853. // colors
  38854. var colors = parsedVertexData.colors;
  38855. if (colors) {
  38856. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38857. }
  38858. // matricesIndices
  38859. var matricesIndices = parsedVertexData.matricesIndices;
  38860. if (matricesIndices) {
  38861. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38862. }
  38863. // matricesWeights
  38864. var matricesWeights = parsedVertexData.matricesWeights;
  38865. if (matricesWeights) {
  38866. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38867. }
  38868. // indices
  38869. var indices = parsedVertexData.indices;
  38870. if (indices) {
  38871. vertexData.indices = indices;
  38872. }
  38873. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38874. };
  38875. return VertexData;
  38876. }());
  38877. BABYLON.VertexData = VertexData;
  38878. })(BABYLON || (BABYLON = {}));
  38879. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38880. var BABYLON;
  38881. (function (BABYLON) {
  38882. /**
  38883. * Class used to store geometry data (vertex buffers + index buffer)
  38884. */
  38885. var Geometry = /** @class */ (function () {
  38886. /**
  38887. * Creates a new geometry
  38888. * @param id defines the unique ID
  38889. * @param scene defines the hosting scene
  38890. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38891. * @param updatable defines if geometry must be updatable (false by default)
  38892. * @param mesh defines the mesh that will be associated with the geometry
  38893. */
  38894. function Geometry(id, scene, vertexData, updatable, mesh) {
  38895. if (updatable === void 0) { updatable = false; }
  38896. if (mesh === void 0) { mesh = null; }
  38897. /**
  38898. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38899. */
  38900. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38901. this._totalVertices = 0;
  38902. this._isDisposed = false;
  38903. this._indexBufferIsUpdatable = false;
  38904. this.id = id;
  38905. this._engine = scene.getEngine();
  38906. this._meshes = [];
  38907. this._scene = scene;
  38908. //Init vertex buffer cache
  38909. this._vertexBuffers = {};
  38910. this._indices = [];
  38911. this._updatable = updatable;
  38912. // vertexData
  38913. if (vertexData) {
  38914. this.setAllVerticesData(vertexData, updatable);
  38915. }
  38916. else {
  38917. this._totalVertices = 0;
  38918. this._indices = [];
  38919. }
  38920. if (this._engine.getCaps().vertexArrayObject) {
  38921. this._vertexArrayObjects = {};
  38922. }
  38923. // applyToMesh
  38924. if (mesh) {
  38925. if (mesh.getClassName() === "LinesMesh") {
  38926. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38927. this._updateExtend();
  38928. }
  38929. this.applyToMesh(mesh);
  38930. mesh.computeWorldMatrix(true);
  38931. }
  38932. }
  38933. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38934. /**
  38935. * 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
  38936. */
  38937. get: function () {
  38938. return this._boundingBias;
  38939. },
  38940. /**
  38941. * 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
  38942. */
  38943. set: function (value) {
  38944. if (this._boundingBias && this._boundingBias.equals(value)) {
  38945. return;
  38946. }
  38947. this._boundingBias = value.clone();
  38948. this._updateBoundingInfo(true, null);
  38949. },
  38950. enumerable: true,
  38951. configurable: true
  38952. });
  38953. /**
  38954. * Static function used to attach a new empty geometry to a mesh
  38955. * @param mesh defines the mesh to attach the geometry to
  38956. * @returns the new {BABYLON.Geometry}
  38957. */
  38958. Geometry.CreateGeometryForMesh = function (mesh) {
  38959. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38960. geometry.applyToMesh(mesh);
  38961. return geometry;
  38962. };
  38963. Object.defineProperty(Geometry.prototype, "extend", {
  38964. /**
  38965. * Gets the current extend of the geometry
  38966. */
  38967. get: function () {
  38968. return this._extend;
  38969. },
  38970. enumerable: true,
  38971. configurable: true
  38972. });
  38973. /**
  38974. * Gets the hosting scene
  38975. * @returns the hosting {BABYLON.Scene}
  38976. */
  38977. Geometry.prototype.getScene = function () {
  38978. return this._scene;
  38979. };
  38980. /**
  38981. * Gets the hosting engine
  38982. * @returns the hosting {BABYLON.Engine}
  38983. */
  38984. Geometry.prototype.getEngine = function () {
  38985. return this._engine;
  38986. };
  38987. /**
  38988. * Defines if the geometry is ready to use
  38989. * @returns true if the geometry is ready to be used
  38990. */
  38991. Geometry.prototype.isReady = function () {
  38992. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38993. };
  38994. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38995. /**
  38996. * Gets a value indicating that the geometry should not be serialized
  38997. */
  38998. get: function () {
  38999. for (var index = 0; index < this._meshes.length; index++) {
  39000. if (!this._meshes[index].doNotSerialize) {
  39001. return false;
  39002. }
  39003. }
  39004. return true;
  39005. },
  39006. enumerable: true,
  39007. configurable: true
  39008. });
  39009. /** @hidden */
  39010. Geometry.prototype._rebuild = function () {
  39011. if (this._vertexArrayObjects) {
  39012. this._vertexArrayObjects = {};
  39013. }
  39014. // Index buffer
  39015. if (this._meshes.length !== 0 && this._indices) {
  39016. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39017. }
  39018. // Vertex buffers
  39019. for (var key in this._vertexBuffers) {
  39020. var vertexBuffer = this._vertexBuffers[key];
  39021. vertexBuffer._rebuild();
  39022. }
  39023. };
  39024. /**
  39025. * Affects all geometry data in one call
  39026. * @param vertexData defines the geometry data
  39027. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  39028. */
  39029. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39030. vertexData.applyToGeometry(this, updatable);
  39031. this.notifyUpdate();
  39032. };
  39033. /**
  39034. * Set specific vertex data
  39035. * @param kind defines the data kind (Position, normal, etc...)
  39036. * @param data defines the vertex data to use
  39037. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  39038. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  39039. */
  39040. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  39041. if (updatable === void 0) { updatable = false; }
  39042. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  39043. this.setVerticesBuffer(buffer);
  39044. };
  39045. /**
  39046. * Removes a specific vertex data
  39047. * @param kind defines the data kind (Position, normal, etc...)
  39048. */
  39049. Geometry.prototype.removeVerticesData = function (kind) {
  39050. if (this._vertexBuffers[kind]) {
  39051. this._vertexBuffers[kind].dispose();
  39052. delete this._vertexBuffers[kind];
  39053. }
  39054. };
  39055. /**
  39056. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  39057. * @param buffer defines the vertex buffer to use
  39058. * @param totalVertices defines the total number of vertices for position kind (could be null)
  39059. */
  39060. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  39061. if (totalVertices === void 0) { totalVertices = null; }
  39062. var kind = buffer.getKind();
  39063. if (this._vertexBuffers[kind]) {
  39064. this._vertexBuffers[kind].dispose();
  39065. }
  39066. this._vertexBuffers[kind] = buffer;
  39067. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39068. var data = buffer.getData();
  39069. if (totalVertices != null) {
  39070. this._totalVertices = totalVertices;
  39071. }
  39072. else {
  39073. if (data != null) {
  39074. this._totalVertices = data.length / (buffer.byteStride / 4);
  39075. }
  39076. }
  39077. this._updateExtend(data);
  39078. this._resetPointsArrayCache();
  39079. var meshes = this._meshes;
  39080. var numOfMeshes = meshes.length;
  39081. for (var index = 0; index < numOfMeshes; index++) {
  39082. var mesh = meshes[index];
  39083. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39084. mesh._createGlobalSubMesh(false);
  39085. mesh.computeWorldMatrix(true);
  39086. }
  39087. }
  39088. this.notifyUpdate(kind);
  39089. if (this._vertexArrayObjects) {
  39090. this._disposeVertexArrayObjects();
  39091. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  39092. }
  39093. };
  39094. /**
  39095. * Update a specific vertex buffer
  39096. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  39097. * It will do nothing if the buffer is not updatable
  39098. * @param kind defines the data kind (Position, normal, etc...)
  39099. * @param data defines the data to use
  39100. * @param offset defines the offset in the target buffer where to store the data
  39101. * @param useBytes set to true if the offset is in bytes
  39102. */
  39103. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  39104. if (useBytes === void 0) { useBytes = false; }
  39105. var vertexBuffer = this.getVertexBuffer(kind);
  39106. if (!vertexBuffer) {
  39107. return;
  39108. }
  39109. vertexBuffer.updateDirectly(data, offset, useBytes);
  39110. this.notifyUpdate(kind);
  39111. };
  39112. /**
  39113. * Update a specific vertex buffer
  39114. * This function will create a new buffer if the current one is not updatable
  39115. * @param kind defines the data kind (Position, normal, etc...)
  39116. * @param data defines the data to use
  39117. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  39118. */
  39119. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39120. if (updateExtends === void 0) { updateExtends = false; }
  39121. var vertexBuffer = this.getVertexBuffer(kind);
  39122. if (!vertexBuffer) {
  39123. return;
  39124. }
  39125. vertexBuffer.update(data);
  39126. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39127. this._updateBoundingInfo(updateExtends, data);
  39128. }
  39129. this.notifyUpdate(kind);
  39130. };
  39131. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39132. if (updateExtends) {
  39133. this._updateExtend(data);
  39134. }
  39135. var meshes = this._meshes;
  39136. var numOfMeshes = meshes.length;
  39137. this._resetPointsArrayCache();
  39138. for (var index = 0; index < numOfMeshes; index++) {
  39139. var mesh = meshes[index];
  39140. if (updateExtends) {
  39141. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39142. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39143. var subMesh = mesh.subMeshes[subIndex];
  39144. subMesh.refreshBoundingInfo();
  39145. }
  39146. }
  39147. }
  39148. };
  39149. /** @hidden */
  39150. Geometry.prototype._bind = function (effect, indexToBind) {
  39151. if (!effect) {
  39152. return;
  39153. }
  39154. if (indexToBind === undefined) {
  39155. indexToBind = this._indexBuffer;
  39156. }
  39157. var vbs = this.getVertexBuffers();
  39158. if (!vbs) {
  39159. return;
  39160. }
  39161. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39162. this._engine.bindBuffers(vbs, indexToBind, effect);
  39163. return;
  39164. }
  39165. // Using VAO
  39166. if (!this._vertexArrayObjects[effect.key]) {
  39167. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39168. }
  39169. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39170. };
  39171. /**
  39172. * Gets total number of vertices
  39173. * @returns the total number of vertices
  39174. */
  39175. Geometry.prototype.getTotalVertices = function () {
  39176. if (!this.isReady()) {
  39177. return 0;
  39178. }
  39179. return this._totalVertices;
  39180. };
  39181. /**
  39182. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39183. * @param kind defines the data kind (Position, normal, etc...)
  39184. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39185. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39186. * @returns a float array containing vertex data
  39187. */
  39188. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39189. var vertexBuffer = this.getVertexBuffer(kind);
  39190. if (!vertexBuffer) {
  39191. return null;
  39192. }
  39193. var data = vertexBuffer.getData();
  39194. if (!data) {
  39195. return null;
  39196. }
  39197. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39198. var count = this._totalVertices * vertexBuffer.getSize();
  39199. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39200. var copy_1 = new Array(count);
  39201. vertexBuffer.forEach(count, function (value, index) {
  39202. copy_1[index] = value;
  39203. });
  39204. return copy_1;
  39205. }
  39206. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39207. if (data instanceof Array) {
  39208. var offset = vertexBuffer.byteOffset / 4;
  39209. return BABYLON.Tools.Slice(data, offset, offset + count);
  39210. }
  39211. else if (data instanceof ArrayBuffer) {
  39212. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39213. }
  39214. else {
  39215. var offset = data.byteOffset + vertexBuffer.byteOffset;
  39216. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39217. var result = new Float32Array(count);
  39218. var source = new Float32Array(data.buffer, offset, count);
  39219. result.set(source);
  39220. return result;
  39221. }
  39222. return new Float32Array(data.buffer, offset, count);
  39223. }
  39224. }
  39225. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39226. return BABYLON.Tools.Slice(data);
  39227. }
  39228. return data;
  39229. };
  39230. /**
  39231. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39232. * @param kind defines the data kind (Position, normal, etc...)
  39233. * @returns true if the vertex buffer with the specified kind is updatable
  39234. */
  39235. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39236. var vb = this._vertexBuffers[kind];
  39237. if (!vb) {
  39238. return false;
  39239. }
  39240. return vb.isUpdatable();
  39241. };
  39242. /**
  39243. * Gets a specific vertex buffer
  39244. * @param kind defines the data kind (Position, normal, etc...)
  39245. * @returns a {BABYLON.VertexBuffer}
  39246. */
  39247. Geometry.prototype.getVertexBuffer = function (kind) {
  39248. if (!this.isReady()) {
  39249. return null;
  39250. }
  39251. return this._vertexBuffers[kind];
  39252. };
  39253. /**
  39254. * Returns all vertex buffers
  39255. * @return an object holding all vertex buffers indexed by kind
  39256. */
  39257. Geometry.prototype.getVertexBuffers = function () {
  39258. if (!this.isReady()) {
  39259. return null;
  39260. }
  39261. return this._vertexBuffers;
  39262. };
  39263. /**
  39264. * Gets a boolean indicating if specific vertex buffer is present
  39265. * @param kind defines the data kind (Position, normal, etc...)
  39266. * @returns true if data is present
  39267. */
  39268. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39269. if (!this._vertexBuffers) {
  39270. if (this._delayInfo) {
  39271. return this._delayInfo.indexOf(kind) !== -1;
  39272. }
  39273. return false;
  39274. }
  39275. return this._vertexBuffers[kind] !== undefined;
  39276. };
  39277. /**
  39278. * Gets a list of all attached data kinds (Position, normal, etc...)
  39279. * @returns a list of string containing all kinds
  39280. */
  39281. Geometry.prototype.getVerticesDataKinds = function () {
  39282. var result = [];
  39283. var kind;
  39284. if (!this._vertexBuffers && this._delayInfo) {
  39285. for (kind in this._delayInfo) {
  39286. result.push(kind);
  39287. }
  39288. }
  39289. else {
  39290. for (kind in this._vertexBuffers) {
  39291. result.push(kind);
  39292. }
  39293. }
  39294. return result;
  39295. };
  39296. /**
  39297. * Update index buffer
  39298. * @param indices defines the indices to store in the index buffer
  39299. * @param offset defines the offset in the target buffer where to store the data
  39300. */
  39301. Geometry.prototype.updateIndices = function (indices, offset) {
  39302. if (!this._indexBuffer) {
  39303. return;
  39304. }
  39305. if (!this._indexBufferIsUpdatable) {
  39306. this.setIndices(indices, null, true);
  39307. }
  39308. else {
  39309. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39310. }
  39311. };
  39312. /**
  39313. * Creates a new index buffer
  39314. * @param indices defines the indices to store in the index buffer
  39315. * @param totalVertices defines the total number of vertices (could be null)
  39316. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39317. */
  39318. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39319. if (totalVertices === void 0) { totalVertices = null; }
  39320. if (updatable === void 0) { updatable = false; }
  39321. if (this._indexBuffer) {
  39322. this._engine._releaseBuffer(this._indexBuffer);
  39323. }
  39324. this._disposeVertexArrayObjects();
  39325. this._indices = indices;
  39326. this._indexBufferIsUpdatable = updatable;
  39327. if (this._meshes.length !== 0 && this._indices) {
  39328. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39329. }
  39330. if (totalVertices != undefined) { // including null and undefined
  39331. this._totalVertices = totalVertices;
  39332. }
  39333. var meshes = this._meshes;
  39334. var numOfMeshes = meshes.length;
  39335. for (var index = 0; index < numOfMeshes; index++) {
  39336. meshes[index]._createGlobalSubMesh(true);
  39337. }
  39338. this.notifyUpdate();
  39339. };
  39340. /**
  39341. * Return the total number of indices
  39342. * @returns the total number of indices
  39343. */
  39344. Geometry.prototype.getTotalIndices = function () {
  39345. if (!this.isReady()) {
  39346. return 0;
  39347. }
  39348. return this._indices.length;
  39349. };
  39350. /**
  39351. * Gets the index buffer array
  39352. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39353. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39354. * @returns the index buffer array
  39355. */
  39356. Geometry.prototype.getIndices = function (copyWhenShared, forceCopy) {
  39357. if (!this.isReady()) {
  39358. return null;
  39359. }
  39360. var orig = this._indices;
  39361. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  39362. return orig;
  39363. }
  39364. else {
  39365. var len = orig.length;
  39366. var copy = [];
  39367. for (var i = 0; i < len; i++) {
  39368. copy.push(orig[i]);
  39369. }
  39370. return copy;
  39371. }
  39372. };
  39373. /**
  39374. * Gets the index buffer
  39375. * @return the index buffer
  39376. */
  39377. Geometry.prototype.getIndexBuffer = function () {
  39378. if (!this.isReady()) {
  39379. return null;
  39380. }
  39381. return this._indexBuffer;
  39382. };
  39383. /** @hidden */
  39384. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39385. if (effect === void 0) { effect = null; }
  39386. if (!effect || !this._vertexArrayObjects) {
  39387. return;
  39388. }
  39389. if (this._vertexArrayObjects[effect.key]) {
  39390. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39391. delete this._vertexArrayObjects[effect.key];
  39392. }
  39393. };
  39394. /**
  39395. * Release the associated resources for a specific mesh
  39396. * @param mesh defines the source mesh
  39397. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39398. */
  39399. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39400. var meshes = this._meshes;
  39401. var index = meshes.indexOf(mesh);
  39402. if (index === -1) {
  39403. return;
  39404. }
  39405. meshes.splice(index, 1);
  39406. mesh._geometry = null;
  39407. if (meshes.length === 0 && shouldDispose) {
  39408. this.dispose();
  39409. }
  39410. };
  39411. /**
  39412. * Apply current geometry to a given mesh
  39413. * @param mesh defines the mesh to apply geometry to
  39414. */
  39415. Geometry.prototype.applyToMesh = function (mesh) {
  39416. if (mesh._geometry === this) {
  39417. return;
  39418. }
  39419. var previousGeometry = mesh._geometry;
  39420. if (previousGeometry) {
  39421. previousGeometry.releaseForMesh(mesh);
  39422. }
  39423. var meshes = this._meshes;
  39424. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39425. mesh._geometry = this;
  39426. this._scene.pushGeometry(this);
  39427. meshes.push(mesh);
  39428. if (this.isReady()) {
  39429. this._applyToMesh(mesh);
  39430. }
  39431. else {
  39432. mesh._boundingInfo = this._boundingInfo;
  39433. }
  39434. };
  39435. Geometry.prototype._updateExtend = function (data) {
  39436. if (data === void 0) { data = null; }
  39437. if (!data) {
  39438. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39439. }
  39440. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39441. };
  39442. Geometry.prototype._applyToMesh = function (mesh) {
  39443. var numOfMeshes = this._meshes.length;
  39444. // vertexBuffers
  39445. for (var kind in this._vertexBuffers) {
  39446. if (numOfMeshes === 1) {
  39447. this._vertexBuffers[kind].create();
  39448. }
  39449. var buffer = this._vertexBuffers[kind].getBuffer();
  39450. if (buffer)
  39451. buffer.references = numOfMeshes;
  39452. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39453. if (!this._extend) {
  39454. this._updateExtend();
  39455. }
  39456. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39457. mesh._createGlobalSubMesh(false);
  39458. //bounding info was just created again, world matrix should be applied again.
  39459. mesh._updateBoundingInfo();
  39460. }
  39461. }
  39462. // indexBuffer
  39463. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39464. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39465. }
  39466. if (this._indexBuffer) {
  39467. this._indexBuffer.references = numOfMeshes;
  39468. }
  39469. };
  39470. Geometry.prototype.notifyUpdate = function (kind) {
  39471. if (this.onGeometryUpdated) {
  39472. this.onGeometryUpdated(this, kind);
  39473. }
  39474. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39475. var mesh = _a[_i];
  39476. mesh._markSubMeshesAsAttributesDirty();
  39477. }
  39478. };
  39479. /**
  39480. * Load the geometry if it was flagged as delay loaded
  39481. * @param scene defines the hosting scene
  39482. * @param onLoaded defines a callback called when the geometry is loaded
  39483. */
  39484. Geometry.prototype.load = function (scene, onLoaded) {
  39485. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39486. return;
  39487. }
  39488. if (this.isReady()) {
  39489. if (onLoaded) {
  39490. onLoaded();
  39491. }
  39492. return;
  39493. }
  39494. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39495. this._queueLoad(scene, onLoaded);
  39496. };
  39497. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39498. var _this = this;
  39499. if (!this.delayLoadingFile) {
  39500. return;
  39501. }
  39502. scene._addPendingData(this);
  39503. scene._loadFile(this.delayLoadingFile, function (data) {
  39504. if (!_this._delayLoadingFunction) {
  39505. return;
  39506. }
  39507. _this._delayLoadingFunction(JSON.parse(data), _this);
  39508. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39509. _this._delayInfo = [];
  39510. scene._removePendingData(_this);
  39511. var meshes = _this._meshes;
  39512. var numOfMeshes = meshes.length;
  39513. for (var index = 0; index < numOfMeshes; index++) {
  39514. _this._applyToMesh(meshes[index]);
  39515. }
  39516. if (onLoaded) {
  39517. onLoaded();
  39518. }
  39519. }, undefined, true);
  39520. };
  39521. /**
  39522. * Invert the geometry to move from a right handed system to a left handed one.
  39523. */
  39524. Geometry.prototype.toLeftHanded = function () {
  39525. // Flip faces
  39526. var tIndices = this.getIndices(false);
  39527. if (tIndices != null && tIndices.length > 0) {
  39528. for (var i = 0; i < tIndices.length; i += 3) {
  39529. var tTemp = tIndices[i + 0];
  39530. tIndices[i + 0] = tIndices[i + 2];
  39531. tIndices[i + 2] = tTemp;
  39532. }
  39533. this.setIndices(tIndices);
  39534. }
  39535. // Negate position.z
  39536. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39537. if (tPositions != null && tPositions.length > 0) {
  39538. for (var i = 0; i < tPositions.length; i += 3) {
  39539. tPositions[i + 2] = -tPositions[i + 2];
  39540. }
  39541. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39542. }
  39543. // Negate normal.z
  39544. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39545. if (tNormals != null && tNormals.length > 0) {
  39546. for (var i = 0; i < tNormals.length; i += 3) {
  39547. tNormals[i + 2] = -tNormals[i + 2];
  39548. }
  39549. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39550. }
  39551. };
  39552. // Cache
  39553. /** @hidden */
  39554. Geometry.prototype._resetPointsArrayCache = function () {
  39555. this._positions = null;
  39556. };
  39557. /** @hidden */
  39558. Geometry.prototype._generatePointsArray = function () {
  39559. if (this._positions)
  39560. return true;
  39561. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39562. if (!data || data.length === 0) {
  39563. return false;
  39564. }
  39565. this._positions = [];
  39566. for (var index = 0; index < data.length; index += 3) {
  39567. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39568. }
  39569. return true;
  39570. };
  39571. /**
  39572. * Gets a value indicating if the geometry is disposed
  39573. * @returns true if the geometry was disposed
  39574. */
  39575. Geometry.prototype.isDisposed = function () {
  39576. return this._isDisposed;
  39577. };
  39578. Geometry.prototype._disposeVertexArrayObjects = function () {
  39579. if (this._vertexArrayObjects) {
  39580. for (var kind in this._vertexArrayObjects) {
  39581. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39582. }
  39583. this._vertexArrayObjects = {};
  39584. }
  39585. };
  39586. /**
  39587. * Free all associated resources
  39588. */
  39589. Geometry.prototype.dispose = function () {
  39590. var meshes = this._meshes;
  39591. var numOfMeshes = meshes.length;
  39592. var index;
  39593. for (index = 0; index < numOfMeshes; index++) {
  39594. this.releaseForMesh(meshes[index]);
  39595. }
  39596. this._meshes = [];
  39597. this._disposeVertexArrayObjects();
  39598. for (var kind in this._vertexBuffers) {
  39599. this._vertexBuffers[kind].dispose();
  39600. }
  39601. this._vertexBuffers = {};
  39602. this._totalVertices = 0;
  39603. if (this._indexBuffer) {
  39604. this._engine._releaseBuffer(this._indexBuffer);
  39605. }
  39606. this._indexBuffer = null;
  39607. this._indices = [];
  39608. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39609. this.delayLoadingFile = null;
  39610. this._delayLoadingFunction = null;
  39611. this._delayInfo = [];
  39612. this._boundingInfo = null;
  39613. this._scene.removeGeometry(this);
  39614. this._isDisposed = true;
  39615. };
  39616. /**
  39617. * Clone the current geometry into a new geometry
  39618. * @param id defines the unique ID of the new geometry
  39619. * @returns a new geometry object
  39620. */
  39621. Geometry.prototype.copy = function (id) {
  39622. var vertexData = new BABYLON.VertexData();
  39623. vertexData.indices = [];
  39624. var indices = this.getIndices();
  39625. if (indices) {
  39626. for (var index = 0; index < indices.length; index++) {
  39627. vertexData.indices.push(indices[index]);
  39628. }
  39629. }
  39630. var updatable = false;
  39631. var stopChecking = false;
  39632. var kind;
  39633. for (kind in this._vertexBuffers) {
  39634. // using slice() to make a copy of the array and not just reference it
  39635. var data = this.getVerticesData(kind);
  39636. if (data instanceof Float32Array) {
  39637. vertexData.set(new Float32Array(data), kind);
  39638. }
  39639. else {
  39640. vertexData.set(data.slice(0), kind);
  39641. }
  39642. if (!stopChecking) {
  39643. var vb = this.getVertexBuffer(kind);
  39644. if (vb) {
  39645. updatable = vb.isUpdatable();
  39646. stopChecking = !updatable;
  39647. }
  39648. }
  39649. }
  39650. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39651. geometry.delayLoadState = this.delayLoadState;
  39652. geometry.delayLoadingFile = this.delayLoadingFile;
  39653. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39654. for (kind in this._delayInfo) {
  39655. geometry._delayInfo = geometry._delayInfo || [];
  39656. geometry._delayInfo.push(kind);
  39657. }
  39658. // Bounding info
  39659. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39660. return geometry;
  39661. };
  39662. /**
  39663. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39664. * @return a JSON representation of the current geometry data (without the vertices data)
  39665. */
  39666. Geometry.prototype.serialize = function () {
  39667. var serializationObject = {};
  39668. serializationObject.id = this.id;
  39669. serializationObject.updatable = this._updatable;
  39670. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39671. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39672. }
  39673. return serializationObject;
  39674. };
  39675. Geometry.prototype.toNumberArray = function (origin) {
  39676. if (Array.isArray(origin)) {
  39677. return origin;
  39678. }
  39679. else {
  39680. return Array.prototype.slice.call(origin);
  39681. }
  39682. };
  39683. /**
  39684. * Serialize all vertices data into a JSON oject
  39685. * @returns a JSON representation of the current geometry data
  39686. */
  39687. Geometry.prototype.serializeVerticeData = function () {
  39688. var serializationObject = this.serialize();
  39689. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39690. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39691. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39692. serializationObject.positions._updatable = true;
  39693. }
  39694. }
  39695. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39696. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39697. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39698. serializationObject.normals._updatable = true;
  39699. }
  39700. }
  39701. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39702. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39703. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39704. serializationObject.tangets._updatable = true;
  39705. }
  39706. }
  39707. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39708. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39709. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39710. serializationObject.uvs._updatable = true;
  39711. }
  39712. }
  39713. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39714. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39715. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39716. serializationObject.uv2s._updatable = true;
  39717. }
  39718. }
  39719. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39720. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39721. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39722. serializationObject.uv3s._updatable = true;
  39723. }
  39724. }
  39725. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39726. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39727. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39728. serializationObject.uv4s._updatable = true;
  39729. }
  39730. }
  39731. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39732. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39733. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39734. serializationObject.uv5s._updatable = true;
  39735. }
  39736. }
  39737. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39738. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39739. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39740. serializationObject.uv6s._updatable = true;
  39741. }
  39742. }
  39743. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39744. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39745. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39746. serializationObject.colors._updatable = true;
  39747. }
  39748. }
  39749. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39750. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39751. serializationObject.matricesIndices._isExpanded = true;
  39752. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39753. serializationObject.matricesIndices._updatable = true;
  39754. }
  39755. }
  39756. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39757. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39758. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39759. serializationObject.matricesWeights._updatable = true;
  39760. }
  39761. }
  39762. serializationObject.indices = this.toNumberArray(this.getIndices());
  39763. return serializationObject;
  39764. };
  39765. // Statics
  39766. /**
  39767. * Extracts a clone of a mesh geometry
  39768. * @param mesh defines the source mesh
  39769. * @param id defines the unique ID of the new geometry object
  39770. * @returns the new geometry object
  39771. */
  39772. Geometry.ExtractFromMesh = function (mesh, id) {
  39773. var geometry = mesh._geometry;
  39774. if (!geometry) {
  39775. return null;
  39776. }
  39777. return geometry.copy(id);
  39778. };
  39779. /**
  39780. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39781. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39782. * Be aware Math.random() could cause collisions, but:
  39783. * "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"
  39784. * @returns a string containing a new GUID
  39785. */
  39786. Geometry.RandomId = function () {
  39787. return BABYLON.Tools.RandomId();
  39788. };
  39789. /** @hidden */
  39790. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39791. var scene = mesh.getScene();
  39792. // Geometry
  39793. var geometryId = parsedGeometry.geometryId;
  39794. if (geometryId) {
  39795. var geometry = scene.getGeometryByID(geometryId);
  39796. if (geometry) {
  39797. geometry.applyToMesh(mesh);
  39798. }
  39799. }
  39800. else if (parsedGeometry instanceof ArrayBuffer) {
  39801. var binaryInfo = mesh._binaryInfo;
  39802. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39803. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39804. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39805. }
  39806. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39807. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39808. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39809. }
  39810. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39811. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39812. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39813. }
  39814. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39815. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39816. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39817. }
  39818. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39819. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39820. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39821. }
  39822. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39823. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39824. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39825. }
  39826. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39827. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39828. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39829. }
  39830. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39831. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39832. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39833. }
  39834. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39835. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39836. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39837. }
  39838. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39839. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39840. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39841. }
  39842. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39843. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39844. var floatIndices = [];
  39845. for (var i = 0; i < matricesIndicesData.length; i++) {
  39846. var index = matricesIndicesData[i];
  39847. floatIndices.push(index & 0x000000FF);
  39848. floatIndices.push((index & 0x0000FF00) >> 8);
  39849. floatIndices.push((index & 0x00FF0000) >> 16);
  39850. floatIndices.push(index >> 24);
  39851. }
  39852. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  39853. }
  39854. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39855. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39856. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39857. }
  39858. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39859. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39860. mesh.setIndices(indicesData, null);
  39861. }
  39862. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39863. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39864. mesh.subMeshes = [];
  39865. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39866. var materialIndex = subMeshesData[(i * 5) + 0];
  39867. var verticesStart = subMeshesData[(i * 5) + 1];
  39868. var verticesCount = subMeshesData[(i * 5) + 2];
  39869. var indexStart = subMeshesData[(i * 5) + 3];
  39870. var indexCount = subMeshesData[(i * 5) + 4];
  39871. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39872. }
  39873. }
  39874. }
  39875. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39876. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39877. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39878. if (parsedGeometry.tangents) {
  39879. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39880. }
  39881. if (parsedGeometry.uvs) {
  39882. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39883. }
  39884. if (parsedGeometry.uvs2) {
  39885. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39886. }
  39887. if (parsedGeometry.uvs3) {
  39888. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39889. }
  39890. if (parsedGeometry.uvs4) {
  39891. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39892. }
  39893. if (parsedGeometry.uvs5) {
  39894. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39895. }
  39896. if (parsedGeometry.uvs6) {
  39897. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39898. }
  39899. if (parsedGeometry.colors) {
  39900. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39901. }
  39902. if (parsedGeometry.matricesIndices) {
  39903. if (!parsedGeometry.matricesIndices._isExpanded) {
  39904. var floatIndices = [];
  39905. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39906. var matricesIndex = parsedGeometry.matricesIndices[i];
  39907. floatIndices.push(matricesIndex & 0x000000FF);
  39908. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39909. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39910. floatIndices.push(matricesIndex >> 24);
  39911. }
  39912. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39913. }
  39914. else {
  39915. delete parsedGeometry.matricesIndices._isExpanded;
  39916. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39917. }
  39918. }
  39919. if (parsedGeometry.matricesIndicesExtra) {
  39920. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39921. var floatIndices = [];
  39922. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39923. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39924. floatIndices.push(matricesIndex & 0x000000FF);
  39925. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39926. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39927. floatIndices.push(matricesIndex >> 24);
  39928. }
  39929. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39930. }
  39931. else {
  39932. delete parsedGeometry.matricesIndices._isExpanded;
  39933. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39934. }
  39935. }
  39936. if (parsedGeometry.matricesWeights) {
  39937. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39938. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39939. }
  39940. if (parsedGeometry.matricesWeightsExtra) {
  39941. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39942. }
  39943. mesh.setIndices(parsedGeometry.indices, null);
  39944. }
  39945. // SubMeshes
  39946. if (parsedGeometry.subMeshes) {
  39947. mesh.subMeshes = [];
  39948. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39949. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39950. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39951. }
  39952. }
  39953. // Flat shading
  39954. if (mesh._shouldGenerateFlatShading) {
  39955. mesh.convertToFlatShadedMesh();
  39956. delete mesh._shouldGenerateFlatShading;
  39957. }
  39958. // Update
  39959. mesh.computeWorldMatrix(true);
  39960. // Octree
  39961. var sceneOctree = scene.selectionOctree;
  39962. if (sceneOctree !== undefined && sceneOctree !== null) {
  39963. sceneOctree.addMesh(mesh);
  39964. }
  39965. };
  39966. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39967. var epsilon = 1e-3;
  39968. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39969. return;
  39970. }
  39971. var noInfluenceBoneIndex = 0.0;
  39972. if (parsedGeometry.skeletonId > -1) {
  39973. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39974. if (!skeleton) {
  39975. return;
  39976. }
  39977. noInfluenceBoneIndex = skeleton.bones.length;
  39978. }
  39979. else {
  39980. return;
  39981. }
  39982. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39983. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39984. var matricesWeights = parsedGeometry.matricesWeights;
  39985. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39986. var influencers = parsedGeometry.numBoneInfluencer;
  39987. var size = matricesWeights.length;
  39988. for (var i = 0; i < size; i += 4) {
  39989. var weight = 0.0;
  39990. var firstZeroWeight = -1;
  39991. for (var j = 0; j < 4; j++) {
  39992. var w = matricesWeights[i + j];
  39993. weight += w;
  39994. if (w < epsilon && firstZeroWeight < 0) {
  39995. firstZeroWeight = j;
  39996. }
  39997. }
  39998. if (matricesWeightsExtra) {
  39999. for (var j = 0; j < 4; j++) {
  40000. var w = matricesWeightsExtra[i + j];
  40001. weight += w;
  40002. if (w < epsilon && firstZeroWeight < 0) {
  40003. firstZeroWeight = j + 4;
  40004. }
  40005. }
  40006. }
  40007. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  40008. firstZeroWeight = influencers - 1;
  40009. }
  40010. if (weight > epsilon) {
  40011. var mweight = 1.0 / weight;
  40012. for (var j = 0; j < 4; j++) {
  40013. matricesWeights[i + j] *= mweight;
  40014. }
  40015. if (matricesWeightsExtra) {
  40016. for (var j = 0; j < 4; j++) {
  40017. matricesWeightsExtra[i + j] *= mweight;
  40018. }
  40019. }
  40020. }
  40021. else {
  40022. if (firstZeroWeight >= 4) {
  40023. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  40024. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  40025. }
  40026. else {
  40027. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  40028. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  40029. }
  40030. }
  40031. }
  40032. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  40033. if (parsedGeometry.matricesWeightsExtra) {
  40034. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  40035. }
  40036. };
  40037. /**
  40038. * Create a new geometry from persisted data (Using .babylon file format)
  40039. * @param parsedVertexData defines the persisted data
  40040. * @param scene defines the hosting scene
  40041. * @param rootUrl defines the root url to use to load assets (like delayed data)
  40042. * @returns the new geometry object
  40043. */
  40044. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  40045. if (scene.getGeometryByID(parsedVertexData.id)) {
  40046. return null; // null since geometry could be something else than a box...
  40047. }
  40048. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  40049. if (BABYLON.Tags) {
  40050. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  40051. }
  40052. if (parsedVertexData.delayLoadingFile) {
  40053. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40054. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  40055. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  40056. geometry._delayInfo = [];
  40057. if (parsedVertexData.hasUVs) {
  40058. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  40059. }
  40060. if (parsedVertexData.hasUVs2) {
  40061. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  40062. }
  40063. if (parsedVertexData.hasUVs3) {
  40064. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  40065. }
  40066. if (parsedVertexData.hasUVs4) {
  40067. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  40068. }
  40069. if (parsedVertexData.hasUVs5) {
  40070. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  40071. }
  40072. if (parsedVertexData.hasUVs6) {
  40073. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  40074. }
  40075. if (parsedVertexData.hasColors) {
  40076. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  40077. }
  40078. if (parsedVertexData.hasMatricesIndices) {
  40079. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40080. }
  40081. if (parsedVertexData.hasMatricesWeights) {
  40082. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40083. }
  40084. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  40085. }
  40086. else {
  40087. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  40088. }
  40089. scene.pushGeometry(geometry, true);
  40090. return geometry;
  40091. };
  40092. return Geometry;
  40093. }());
  40094. BABYLON.Geometry = Geometry;
  40095. // Primitives
  40096. /// Abstract class
  40097. /**
  40098. * Abstract class used to provide common services for all typed geometries
  40099. * @hidden
  40100. */
  40101. var _PrimitiveGeometry = /** @class */ (function (_super) {
  40102. __extends(_PrimitiveGeometry, _super);
  40103. /**
  40104. * Creates a new typed geometry
  40105. * @param id defines the unique ID of the geometry
  40106. * @param scene defines the hosting scene
  40107. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40108. * @param mesh defines the hosting mesh (can be null)
  40109. */
  40110. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  40111. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  40112. if (mesh === void 0) { mesh = null; }
  40113. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  40114. _this._canBeRegenerated = _canBeRegenerated;
  40115. _this._beingRegenerated = true;
  40116. _this.regenerate();
  40117. _this._beingRegenerated = false;
  40118. return _this;
  40119. }
  40120. /**
  40121. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  40122. * @returns true if the geometry can be regenerated
  40123. */
  40124. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  40125. return this._canBeRegenerated;
  40126. };
  40127. /**
  40128. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  40129. */
  40130. _PrimitiveGeometry.prototype.regenerate = function () {
  40131. if (!this._canBeRegenerated) {
  40132. return;
  40133. }
  40134. this._beingRegenerated = true;
  40135. this.setAllVerticesData(this._regenerateVertexData(), false);
  40136. this._beingRegenerated = false;
  40137. };
  40138. /**
  40139. * Clone the geometry
  40140. * @param id defines the unique ID of the new geometry
  40141. * @returns the new geometry
  40142. */
  40143. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40144. return _super.prototype.copy.call(this, id);
  40145. };
  40146. // overrides
  40147. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40148. if (!this._beingRegenerated) {
  40149. return;
  40150. }
  40151. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40152. };
  40153. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40154. if (!this._beingRegenerated) {
  40155. return;
  40156. }
  40157. _super.prototype.setVerticesData.call(this, kind, data, false);
  40158. };
  40159. // to override
  40160. /** @hidden */
  40161. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40162. throw new Error("Abstract method");
  40163. };
  40164. _PrimitiveGeometry.prototype.copy = function (id) {
  40165. throw new Error("Must be overriden in sub-classes.");
  40166. };
  40167. _PrimitiveGeometry.prototype.serialize = function () {
  40168. var serializationObject = _super.prototype.serialize.call(this);
  40169. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40170. return serializationObject;
  40171. };
  40172. return _PrimitiveGeometry;
  40173. }(Geometry));
  40174. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40175. /**
  40176. * Creates a ribbon geometry
  40177. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40178. */
  40179. var RibbonGeometry = /** @class */ (function (_super) {
  40180. __extends(RibbonGeometry, _super);
  40181. /**
  40182. * Creates a ribbon geometry
  40183. * @param id defines the unique ID of the geometry
  40184. * @param scene defines the hosting scene
  40185. * @param pathArray defines the array of paths to use
  40186. * @param closeArray defines if the last path and the first path must be joined
  40187. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40188. * @param offset defines the offset between points
  40189. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40190. * @param mesh defines the hosting mesh (can be null)
  40191. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40192. */
  40193. function RibbonGeometry(id, scene,
  40194. /**
  40195. * Defines the array of paths to use
  40196. */
  40197. pathArray,
  40198. /**
  40199. * Defines if the last and first points of each path in your pathArray must be joined
  40200. */
  40201. closeArray,
  40202. /**
  40203. * Defines if the last and first points of each path in your pathArray must be joined
  40204. */
  40205. closePath,
  40206. /**
  40207. * Defines the offset between points
  40208. */
  40209. offset, canBeRegenerated, mesh,
  40210. /**
  40211. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40212. */
  40213. side) {
  40214. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40215. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40216. _this.pathArray = pathArray;
  40217. _this.closeArray = closeArray;
  40218. _this.closePath = closePath;
  40219. _this.offset = offset;
  40220. _this.side = side;
  40221. return _this;
  40222. }
  40223. /** @hidden */
  40224. RibbonGeometry.prototype._regenerateVertexData = function () {
  40225. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40226. };
  40227. RibbonGeometry.prototype.copy = function (id) {
  40228. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40229. };
  40230. return RibbonGeometry;
  40231. }(_PrimitiveGeometry));
  40232. BABYLON.RibbonGeometry = RibbonGeometry;
  40233. /**
  40234. * Creates a box geometry
  40235. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40236. */
  40237. var BoxGeometry = /** @class */ (function (_super) {
  40238. __extends(BoxGeometry, _super);
  40239. /**
  40240. * Creates a box geometry
  40241. * @param id defines the unique ID of the geometry
  40242. * @param scene defines the hosting scene
  40243. * @param size defines the zise of the box (width, height and depth are the same)
  40244. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40245. * @param mesh defines the hosting mesh (can be null)
  40246. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40247. */
  40248. function BoxGeometry(id, scene,
  40249. /**
  40250. * Defines the zise of the box (width, height and depth are the same)
  40251. */
  40252. size, canBeRegenerated, mesh,
  40253. /**
  40254. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40255. */
  40256. side) {
  40257. if (mesh === void 0) { mesh = null; }
  40258. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40259. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40260. _this.size = size;
  40261. _this.side = side;
  40262. return _this;
  40263. }
  40264. /** @hidden */
  40265. BoxGeometry.prototype._regenerateVertexData = function () {
  40266. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40267. };
  40268. BoxGeometry.prototype.copy = function (id) {
  40269. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40270. };
  40271. BoxGeometry.prototype.serialize = function () {
  40272. var serializationObject = _super.prototype.serialize.call(this);
  40273. serializationObject.size = this.size;
  40274. return serializationObject;
  40275. };
  40276. BoxGeometry.Parse = function (parsedBox, scene) {
  40277. if (scene.getGeometryByID(parsedBox.id)) {
  40278. return null; // null since geometry could be something else than a box...
  40279. }
  40280. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40281. if (BABYLON.Tags) {
  40282. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40283. }
  40284. scene.pushGeometry(box, true);
  40285. return box;
  40286. };
  40287. return BoxGeometry;
  40288. }(_PrimitiveGeometry));
  40289. BABYLON.BoxGeometry = BoxGeometry;
  40290. /**
  40291. * Creates a sphere geometry
  40292. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40293. */
  40294. var SphereGeometry = /** @class */ (function (_super) {
  40295. __extends(SphereGeometry, _super);
  40296. /**
  40297. * Create a new sphere geometry
  40298. * @param id defines the unique ID of the geometry
  40299. * @param scene defines the hosting scene
  40300. * @param segments defines the number of segments to use to create the sphere
  40301. * @param diameter defines the diameter of the sphere
  40302. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40303. * @param mesh defines the hosting mesh (can be null)
  40304. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40305. */
  40306. function SphereGeometry(id, scene,
  40307. /**
  40308. * Defines the number of segments to use to create the sphere
  40309. */
  40310. segments,
  40311. /**
  40312. * Defines the diameter of the sphere
  40313. */
  40314. diameter, canBeRegenerated, mesh,
  40315. /**
  40316. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40317. */
  40318. side) {
  40319. if (mesh === void 0) { mesh = null; }
  40320. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40321. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40322. _this.segments = segments;
  40323. _this.diameter = diameter;
  40324. _this.side = side;
  40325. return _this;
  40326. }
  40327. /** @hidden */
  40328. SphereGeometry.prototype._regenerateVertexData = function () {
  40329. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40330. };
  40331. SphereGeometry.prototype.copy = function (id) {
  40332. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40333. };
  40334. SphereGeometry.prototype.serialize = function () {
  40335. var serializationObject = _super.prototype.serialize.call(this);
  40336. serializationObject.segments = this.segments;
  40337. serializationObject.diameter = this.diameter;
  40338. return serializationObject;
  40339. };
  40340. SphereGeometry.Parse = function (parsedSphere, scene) {
  40341. if (scene.getGeometryByID(parsedSphere.id)) {
  40342. return null; // null since geometry could be something else than a sphere...
  40343. }
  40344. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40345. if (BABYLON.Tags) {
  40346. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40347. }
  40348. scene.pushGeometry(sphere, true);
  40349. return sphere;
  40350. };
  40351. return SphereGeometry;
  40352. }(_PrimitiveGeometry));
  40353. BABYLON.SphereGeometry = SphereGeometry;
  40354. /**
  40355. * Creates a disc geometry
  40356. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40357. */
  40358. var DiscGeometry = /** @class */ (function (_super) {
  40359. __extends(DiscGeometry, _super);
  40360. /**
  40361. * Creates a new disc geometry
  40362. * @param id defines the unique ID of the geometry
  40363. * @param scene defines the hosting scene
  40364. * @param radius defines the radius of the disc
  40365. * @param tessellation defines the tesselation factor to apply to the disc
  40366. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40367. * @param mesh defines the hosting mesh (can be null)
  40368. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40369. */
  40370. function DiscGeometry(id, scene,
  40371. /**
  40372. * Defines the radius of the disc
  40373. */
  40374. radius,
  40375. /**
  40376. * Defines the tesselation factor to apply to the disc
  40377. */
  40378. tessellation, canBeRegenerated, mesh,
  40379. /**
  40380. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40381. */
  40382. side) {
  40383. if (mesh === void 0) { mesh = null; }
  40384. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40385. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40386. _this.radius = radius;
  40387. _this.tessellation = tessellation;
  40388. _this.side = side;
  40389. return _this;
  40390. }
  40391. /** @hidden */
  40392. DiscGeometry.prototype._regenerateVertexData = function () {
  40393. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40394. };
  40395. DiscGeometry.prototype.copy = function (id) {
  40396. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40397. };
  40398. return DiscGeometry;
  40399. }(_PrimitiveGeometry));
  40400. BABYLON.DiscGeometry = DiscGeometry;
  40401. /**
  40402. * Creates a new cylinder geometry
  40403. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40404. */
  40405. var CylinderGeometry = /** @class */ (function (_super) {
  40406. __extends(CylinderGeometry, _super);
  40407. /**
  40408. * Creates a new cylinder geometry
  40409. * @param id defines the unique ID of the geometry
  40410. * @param scene defines the hosting scene
  40411. * @param height defines the height of the cylinder
  40412. * @param diameterTop defines the diameter of the cylinder's top cap
  40413. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40414. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40415. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40416. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40417. * @param mesh defines the hosting mesh (can be null)
  40418. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40419. */
  40420. function CylinderGeometry(id, scene,
  40421. /**
  40422. * Defines the height of the cylinder
  40423. */
  40424. height,
  40425. /**
  40426. * Defines the diameter of the cylinder's top cap
  40427. */
  40428. diameterTop,
  40429. /**
  40430. * Defines the diameter of the cylinder's bottom cap
  40431. */
  40432. diameterBottom,
  40433. /**
  40434. * Defines the tessellation factor to apply to the cylinder
  40435. */
  40436. tessellation,
  40437. /**
  40438. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40439. */
  40440. subdivisions, canBeRegenerated, mesh,
  40441. /**
  40442. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40443. */
  40444. side) {
  40445. if (subdivisions === void 0) { subdivisions = 1; }
  40446. if (mesh === void 0) { mesh = null; }
  40447. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40448. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40449. _this.height = height;
  40450. _this.diameterTop = diameterTop;
  40451. _this.diameterBottom = diameterBottom;
  40452. _this.tessellation = tessellation;
  40453. _this.subdivisions = subdivisions;
  40454. _this.side = side;
  40455. return _this;
  40456. }
  40457. /** @hidden */
  40458. CylinderGeometry.prototype._regenerateVertexData = function () {
  40459. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40460. };
  40461. CylinderGeometry.prototype.copy = function (id) {
  40462. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40463. };
  40464. CylinderGeometry.prototype.serialize = function () {
  40465. var serializationObject = _super.prototype.serialize.call(this);
  40466. serializationObject.height = this.height;
  40467. serializationObject.diameterTop = this.diameterTop;
  40468. serializationObject.diameterBottom = this.diameterBottom;
  40469. serializationObject.tessellation = this.tessellation;
  40470. return serializationObject;
  40471. };
  40472. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40473. if (scene.getGeometryByID(parsedCylinder.id)) {
  40474. return null; // null since geometry could be something else than a cylinder...
  40475. }
  40476. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40477. if (BABYLON.Tags) {
  40478. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40479. }
  40480. scene.pushGeometry(cylinder, true);
  40481. return cylinder;
  40482. };
  40483. return CylinderGeometry;
  40484. }(_PrimitiveGeometry));
  40485. BABYLON.CylinderGeometry = CylinderGeometry;
  40486. /**
  40487. * Creates a new torus geometry
  40488. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40489. */
  40490. var TorusGeometry = /** @class */ (function (_super) {
  40491. __extends(TorusGeometry, _super);
  40492. /**
  40493. * Creates a new torus geometry
  40494. * @param id defines the unique ID of the geometry
  40495. * @param scene defines the hosting scene
  40496. * @param diameter defines the diameter of the torus
  40497. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40498. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40499. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40500. * @param mesh defines the hosting mesh (can be null)
  40501. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40502. */
  40503. function TorusGeometry(id, scene,
  40504. /**
  40505. * Defines the diameter of the torus
  40506. */
  40507. diameter,
  40508. /**
  40509. * Defines the thickness of the torus (ie. internal diameter)
  40510. */
  40511. thickness,
  40512. /**
  40513. * Defines the tesselation factor to apply to the torus
  40514. */
  40515. tessellation, canBeRegenerated, mesh,
  40516. /**
  40517. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40518. */
  40519. side) {
  40520. if (mesh === void 0) { mesh = null; }
  40521. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40522. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40523. _this.diameter = diameter;
  40524. _this.thickness = thickness;
  40525. _this.tessellation = tessellation;
  40526. _this.side = side;
  40527. return _this;
  40528. }
  40529. /** @hidden */
  40530. TorusGeometry.prototype._regenerateVertexData = function () {
  40531. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40532. };
  40533. TorusGeometry.prototype.copy = function (id) {
  40534. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40535. };
  40536. TorusGeometry.prototype.serialize = function () {
  40537. var serializationObject = _super.prototype.serialize.call(this);
  40538. serializationObject.diameter = this.diameter;
  40539. serializationObject.thickness = this.thickness;
  40540. serializationObject.tessellation = this.tessellation;
  40541. return serializationObject;
  40542. };
  40543. TorusGeometry.Parse = function (parsedTorus, scene) {
  40544. if (scene.getGeometryByID(parsedTorus.id)) {
  40545. return null; // null since geometry could be something else than a torus...
  40546. }
  40547. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40548. if (BABYLON.Tags) {
  40549. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40550. }
  40551. scene.pushGeometry(torus, true);
  40552. return torus;
  40553. };
  40554. return TorusGeometry;
  40555. }(_PrimitiveGeometry));
  40556. BABYLON.TorusGeometry = TorusGeometry;
  40557. /**
  40558. * Creates a new ground geometry
  40559. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40560. */
  40561. var GroundGeometry = /** @class */ (function (_super) {
  40562. __extends(GroundGeometry, _super);
  40563. /**
  40564. * Creates a new ground geometry
  40565. * @param id defines the unique ID of the geometry
  40566. * @param scene defines the hosting scene
  40567. * @param width defines the width of the ground
  40568. * @param height defines the height of the ground
  40569. * @param subdivisions defines the subdivisions to apply to the ground
  40570. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40571. * @param mesh defines the hosting mesh (can be null)
  40572. */
  40573. function GroundGeometry(id, scene,
  40574. /**
  40575. * Defines the width of the ground
  40576. */
  40577. width,
  40578. /**
  40579. * Defines the height of the ground
  40580. */
  40581. height,
  40582. /**
  40583. * Defines the subdivisions to apply to the ground
  40584. */
  40585. subdivisions, canBeRegenerated, mesh) {
  40586. if (mesh === void 0) { mesh = null; }
  40587. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40588. _this.width = width;
  40589. _this.height = height;
  40590. _this.subdivisions = subdivisions;
  40591. return _this;
  40592. }
  40593. /** @hidden */
  40594. GroundGeometry.prototype._regenerateVertexData = function () {
  40595. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40596. };
  40597. GroundGeometry.prototype.copy = function (id) {
  40598. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40599. };
  40600. GroundGeometry.prototype.serialize = function () {
  40601. var serializationObject = _super.prototype.serialize.call(this);
  40602. serializationObject.width = this.width;
  40603. serializationObject.height = this.height;
  40604. serializationObject.subdivisions = this.subdivisions;
  40605. return serializationObject;
  40606. };
  40607. GroundGeometry.Parse = function (parsedGround, scene) {
  40608. if (scene.getGeometryByID(parsedGround.id)) {
  40609. return null; // null since geometry could be something else than a ground...
  40610. }
  40611. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40612. if (BABYLON.Tags) {
  40613. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40614. }
  40615. scene.pushGeometry(ground, true);
  40616. return ground;
  40617. };
  40618. return GroundGeometry;
  40619. }(_PrimitiveGeometry));
  40620. BABYLON.GroundGeometry = GroundGeometry;
  40621. /**
  40622. * Creates a tiled ground geometry
  40623. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40624. */
  40625. var TiledGroundGeometry = /** @class */ (function (_super) {
  40626. __extends(TiledGroundGeometry, _super);
  40627. /**
  40628. * Creates a tiled ground geometry
  40629. * @param id defines the unique ID of the geometry
  40630. * @param scene defines the hosting scene
  40631. * @param xmin defines the minimum value on X axis
  40632. * @param zmin defines the minimum value on Z axis
  40633. * @param xmax defines the maximum value on X axis
  40634. * @param zmax defines the maximum value on Z axis
  40635. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40636. * @param precision defines the precision to use when computing the tiles
  40637. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40638. * @param mesh defines the hosting mesh (can be null)
  40639. */
  40640. function TiledGroundGeometry(id, scene,
  40641. /**
  40642. * Defines the minimum value on X axis
  40643. */
  40644. xmin,
  40645. /**
  40646. * Defines the minimum value on Z axis
  40647. */
  40648. zmin,
  40649. /**
  40650. * Defines the maximum value on X axis
  40651. */
  40652. xmax,
  40653. /**
  40654. * Defines the maximum value on Z axis
  40655. */
  40656. zmax,
  40657. /**
  40658. * Defines the subdivisions to apply to the ground
  40659. */
  40660. subdivisions,
  40661. /**
  40662. * Defines the precision to use when computing the tiles
  40663. */
  40664. precision, canBeRegenerated, mesh) {
  40665. if (mesh === void 0) { mesh = null; }
  40666. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40667. _this.xmin = xmin;
  40668. _this.zmin = zmin;
  40669. _this.xmax = xmax;
  40670. _this.zmax = zmax;
  40671. _this.subdivisions = subdivisions;
  40672. _this.precision = precision;
  40673. return _this;
  40674. }
  40675. /** @hidden */
  40676. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40677. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40678. };
  40679. TiledGroundGeometry.prototype.copy = function (id) {
  40680. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40681. };
  40682. return TiledGroundGeometry;
  40683. }(_PrimitiveGeometry));
  40684. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40685. /**
  40686. * Creates a plane geometry
  40687. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40688. */
  40689. var PlaneGeometry = /** @class */ (function (_super) {
  40690. __extends(PlaneGeometry, _super);
  40691. /**
  40692. * Creates a plane geometry
  40693. * @param id defines the unique ID of the geometry
  40694. * @param scene defines the hosting scene
  40695. * @param size defines the size of the plane (width === height)
  40696. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40697. * @param mesh defines the hosting mesh (can be null)
  40698. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40699. */
  40700. function PlaneGeometry(id, scene,
  40701. /**
  40702. * Defines the size of the plane (width === height)
  40703. */
  40704. size, canBeRegenerated, mesh,
  40705. /**
  40706. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40707. */
  40708. side) {
  40709. if (mesh === void 0) { mesh = null; }
  40710. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40711. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40712. _this.size = size;
  40713. _this.side = side;
  40714. return _this;
  40715. }
  40716. /** @hidden */
  40717. PlaneGeometry.prototype._regenerateVertexData = function () {
  40718. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40719. };
  40720. PlaneGeometry.prototype.copy = function (id) {
  40721. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40722. };
  40723. PlaneGeometry.prototype.serialize = function () {
  40724. var serializationObject = _super.prototype.serialize.call(this);
  40725. serializationObject.size = this.size;
  40726. return serializationObject;
  40727. };
  40728. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40729. if (scene.getGeometryByID(parsedPlane.id)) {
  40730. return null; // null since geometry could be something else than a ground...
  40731. }
  40732. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40733. if (BABYLON.Tags) {
  40734. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40735. }
  40736. scene.pushGeometry(plane, true);
  40737. return plane;
  40738. };
  40739. return PlaneGeometry;
  40740. }(_PrimitiveGeometry));
  40741. BABYLON.PlaneGeometry = PlaneGeometry;
  40742. /**
  40743. * Creates a torus knot geometry
  40744. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40745. */
  40746. var TorusKnotGeometry = /** @class */ (function (_super) {
  40747. __extends(TorusKnotGeometry, _super);
  40748. /**
  40749. * Creates a torus knot geometry
  40750. * @param id defines the unique ID of the geometry
  40751. * @param scene defines the hosting scene
  40752. * @param radius defines the radius of the torus knot
  40753. * @param tube defines the thickness of the torus knot tube
  40754. * @param radialSegments defines the number of radial segments
  40755. * @param tubularSegments defines the number of tubular segments
  40756. * @param p defines the first number of windings
  40757. * @param q defines the second number of windings
  40758. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40759. * @param mesh defines the hosting mesh (can be null)
  40760. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40761. */
  40762. function TorusKnotGeometry(id, scene,
  40763. /**
  40764. * Defines the radius of the torus knot
  40765. */
  40766. radius,
  40767. /**
  40768. * Defines the thickness of the torus knot tube
  40769. */
  40770. tube,
  40771. /**
  40772. * Defines the number of radial segments
  40773. */
  40774. radialSegments,
  40775. /**
  40776. * Defines the number of tubular segments
  40777. */
  40778. tubularSegments,
  40779. /**
  40780. * Defines the first number of windings
  40781. */
  40782. p,
  40783. /**
  40784. * Defines the second number of windings
  40785. */
  40786. q, canBeRegenerated, mesh,
  40787. /**
  40788. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40789. */
  40790. side) {
  40791. if (mesh === void 0) { mesh = null; }
  40792. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40793. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40794. _this.radius = radius;
  40795. _this.tube = tube;
  40796. _this.radialSegments = radialSegments;
  40797. _this.tubularSegments = tubularSegments;
  40798. _this.p = p;
  40799. _this.q = q;
  40800. _this.side = side;
  40801. return _this;
  40802. }
  40803. /** @hidden */
  40804. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40805. 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 });
  40806. };
  40807. TorusKnotGeometry.prototype.copy = function (id) {
  40808. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40809. };
  40810. TorusKnotGeometry.prototype.serialize = function () {
  40811. var serializationObject = _super.prototype.serialize.call(this);
  40812. serializationObject.radius = this.radius;
  40813. serializationObject.tube = this.tube;
  40814. serializationObject.radialSegments = this.radialSegments;
  40815. serializationObject.tubularSegments = this.tubularSegments;
  40816. serializationObject.p = this.p;
  40817. serializationObject.q = this.q;
  40818. return serializationObject;
  40819. };
  40820. ;
  40821. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40822. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40823. return null; // null since geometry could be something else than a ground...
  40824. }
  40825. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40826. if (BABYLON.Tags) {
  40827. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40828. }
  40829. scene.pushGeometry(torusKnot, true);
  40830. return torusKnot;
  40831. };
  40832. return TorusKnotGeometry;
  40833. }(_PrimitiveGeometry));
  40834. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40835. //}
  40836. })(BABYLON || (BABYLON = {}));
  40837. //# sourceMappingURL=babylon.geometry.js.map
  40838. var BABYLON;
  40839. (function (BABYLON) {
  40840. /**
  40841. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40842. */
  40843. var PerformanceMonitor = /** @class */ (function () {
  40844. /**
  40845. * constructor
  40846. * @param frameSampleSize The number of samples required to saturate the sliding window
  40847. */
  40848. function PerformanceMonitor(frameSampleSize) {
  40849. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40850. this._enabled = true;
  40851. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40852. }
  40853. /**
  40854. * Samples current frame
  40855. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40856. */
  40857. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40858. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40859. if (!this._enabled)
  40860. return;
  40861. if (this._lastFrameTimeMs != null) {
  40862. var dt = timeMs - this._lastFrameTimeMs;
  40863. this._rollingFrameTime.add(dt);
  40864. }
  40865. this._lastFrameTimeMs = timeMs;
  40866. };
  40867. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40868. /**
  40869. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40870. * @return Average frame time in milliseconds
  40871. */
  40872. get: function () {
  40873. return this._rollingFrameTime.average;
  40874. },
  40875. enumerable: true,
  40876. configurable: true
  40877. });
  40878. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40879. /**
  40880. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40881. * @return Frame time variance in milliseconds squared
  40882. */
  40883. get: function () {
  40884. return this._rollingFrameTime.variance;
  40885. },
  40886. enumerable: true,
  40887. configurable: true
  40888. });
  40889. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40890. /**
  40891. * Returns the frame time of the most recent frame
  40892. * @return Frame time in milliseconds
  40893. */
  40894. get: function () {
  40895. return this._rollingFrameTime.history(0);
  40896. },
  40897. enumerable: true,
  40898. configurable: true
  40899. });
  40900. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40901. /**
  40902. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40903. * @return Framerate in frames per second
  40904. */
  40905. get: function () {
  40906. return 1000.0 / this._rollingFrameTime.average;
  40907. },
  40908. enumerable: true,
  40909. configurable: true
  40910. });
  40911. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40912. /**
  40913. * Returns the average framerate in frames per second using the most recent frame time
  40914. * @return Framerate in frames per second
  40915. */
  40916. get: function () {
  40917. var history = this._rollingFrameTime.history(0);
  40918. if (history === 0) {
  40919. return 0;
  40920. }
  40921. return 1000.0 / history;
  40922. },
  40923. enumerable: true,
  40924. configurable: true
  40925. });
  40926. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40927. /**
  40928. * Returns true if enough samples have been taken to completely fill the sliding window
  40929. * @return true if saturated
  40930. */
  40931. get: function () {
  40932. return this._rollingFrameTime.isSaturated();
  40933. },
  40934. enumerable: true,
  40935. configurable: true
  40936. });
  40937. /**
  40938. * Enables contributions to the sliding window sample set
  40939. */
  40940. PerformanceMonitor.prototype.enable = function () {
  40941. this._enabled = true;
  40942. };
  40943. /**
  40944. * Disables contributions to the sliding window sample set
  40945. * Samples will not be interpolated over the disabled period
  40946. */
  40947. PerformanceMonitor.prototype.disable = function () {
  40948. this._enabled = false;
  40949. //clear last sample to avoid interpolating over the disabled period when next enabled
  40950. this._lastFrameTimeMs = null;
  40951. };
  40952. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40953. /**
  40954. * Returns true if sampling is enabled
  40955. * @return true if enabled
  40956. */
  40957. get: function () {
  40958. return this._enabled;
  40959. },
  40960. enumerable: true,
  40961. configurable: true
  40962. });
  40963. /**
  40964. * Resets performance monitor
  40965. */
  40966. PerformanceMonitor.prototype.reset = function () {
  40967. //clear last sample to avoid interpolating over the disabled period when next enabled
  40968. this._lastFrameTimeMs = null;
  40969. //wipe record
  40970. this._rollingFrameTime.reset();
  40971. };
  40972. return PerformanceMonitor;
  40973. }());
  40974. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40975. /**
  40976. * RollingAverage
  40977. *
  40978. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40979. */
  40980. var RollingAverage = /** @class */ (function () {
  40981. /**
  40982. * constructor
  40983. * @param length The number of samples required to saturate the sliding window
  40984. */
  40985. function RollingAverage(length) {
  40986. this._samples = new Array(length);
  40987. this.reset();
  40988. }
  40989. /**
  40990. * Adds a sample to the sample set
  40991. * @param v The sample value
  40992. */
  40993. RollingAverage.prototype.add = function (v) {
  40994. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40995. var delta;
  40996. //we need to check if we've already wrapped round
  40997. if (this.isSaturated()) {
  40998. //remove bottom of stack from mean
  40999. var bottomValue = this._samples[this._pos];
  41000. delta = bottomValue - this.average;
  41001. this.average -= delta / (this._sampleCount - 1);
  41002. this._m2 -= delta * (bottomValue - this.average);
  41003. }
  41004. else {
  41005. this._sampleCount++;
  41006. }
  41007. //add new value to mean
  41008. delta = v - this.average;
  41009. this.average += delta / (this._sampleCount);
  41010. this._m2 += delta * (v - this.average);
  41011. //set the new variance
  41012. this.variance = this._m2 / (this._sampleCount - 1);
  41013. this._samples[this._pos] = v;
  41014. this._pos++;
  41015. this._pos %= this._samples.length; //positive wrap around
  41016. };
  41017. /**
  41018. * Returns previously added values or null if outside of history or outside the sliding window domain
  41019. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  41020. * @return Value previously recorded with add() or null if outside of range
  41021. */
  41022. RollingAverage.prototype.history = function (i) {
  41023. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  41024. return 0;
  41025. }
  41026. var i0 = this._wrapPosition(this._pos - 1.0);
  41027. return this._samples[this._wrapPosition(i0 - i)];
  41028. };
  41029. /**
  41030. * Returns true if enough samples have been taken to completely fill the sliding window
  41031. * @return true if sample-set saturated
  41032. */
  41033. RollingAverage.prototype.isSaturated = function () {
  41034. return this._sampleCount >= this._samples.length;
  41035. };
  41036. /**
  41037. * Resets the rolling average (equivalent to 0 samples taken so far)
  41038. */
  41039. RollingAverage.prototype.reset = function () {
  41040. this.average = 0;
  41041. this.variance = 0;
  41042. this._sampleCount = 0;
  41043. this._pos = 0;
  41044. this._m2 = 0;
  41045. };
  41046. /**
  41047. * Wraps a value around the sample range boundaries
  41048. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  41049. * @return Wrapped position in sample range
  41050. */
  41051. RollingAverage.prototype._wrapPosition = function (i) {
  41052. var max = this._samples.length;
  41053. return ((i % max) + max) % max;
  41054. };
  41055. return RollingAverage;
  41056. }());
  41057. BABYLON.RollingAverage = RollingAverage;
  41058. })(BABYLON || (BABYLON = {}));
  41059. //# sourceMappingURL=babylon.performanceMonitor.js.map
  41060. var BABYLON;
  41061. (function (BABYLON) {
  41062. /**
  41063. * "Static Class" containing the most commonly used helper while dealing with material for
  41064. * rendering purpose.
  41065. *
  41066. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41067. *
  41068. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41069. */
  41070. var MaterialHelper = /** @class */ (function () {
  41071. function MaterialHelper() {
  41072. }
  41073. /**
  41074. * Bind the current view position to an effect.
  41075. * @param effect The effect to be bound
  41076. * @param scene The scene the eyes position is used from
  41077. */
  41078. MaterialHelper.BindEyePosition = function (effect, scene) {
  41079. if (scene._forcedViewPosition) {
  41080. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  41081. return;
  41082. }
  41083. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41084. };
  41085. /**
  41086. * Helps preparing the defines values about the UVs in used in the effect.
  41087. * UVs are shared as much as we can accross chanels in the shaders.
  41088. * @param texture The texture we are preparing the UVs for
  41089. * @param defines The defines to update
  41090. * @param key The chanel key "diffuse", "specular"... used in the shader
  41091. */
  41092. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  41093. defines._needUVs = true;
  41094. defines[key] = true;
  41095. if (texture.getTextureMatrix().isIdentity(true)) {
  41096. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  41097. if (texture.coordinatesIndex === 0) {
  41098. defines["MAINUV1"] = true;
  41099. }
  41100. else {
  41101. defines["MAINUV2"] = true;
  41102. }
  41103. }
  41104. else {
  41105. defines[key + "DIRECTUV"] = 0;
  41106. }
  41107. };
  41108. /**
  41109. * Binds a texture matrix value to its corrsponding uniform
  41110. * @param texture The texture to bind the matrix for
  41111. * @param uniformBuffer The uniform buffer receivin the data
  41112. * @param key The chanel key "diffuse", "specular"... used in the shader
  41113. */
  41114. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  41115. var matrix = texture.getTextureMatrix();
  41116. if (!matrix.isIdentity(true)) {
  41117. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  41118. }
  41119. };
  41120. /**
  41121. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  41122. * @param mesh defines the current mesh
  41123. * @param scene defines the current scene
  41124. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  41125. * @param pointsCloud defines if point cloud rendering has to be turned on
  41126. * @param fogEnabled defines if fog has to be turned on
  41127. * @param alphaTest defines if alpha testing has to be turned on
  41128. * @param defines defines the current list of defines
  41129. */
  41130. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  41131. if (defines._areMiscDirty) {
  41132. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  41133. defines["POINTSIZE"] = pointsCloud;
  41134. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41135. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41136. defines["ALPHATEST"] = alphaTest;
  41137. }
  41138. };
  41139. /**
  41140. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41141. * @param scene defines the current scene
  41142. * @param engine defines the current engine
  41143. * @param defines specifies the list of active defines
  41144. * @param useInstances defines if instances have to be turned on
  41145. * @param useClipPlane defines if clip plane have to be turned on
  41146. */
  41147. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41148. if (useClipPlane === void 0) { useClipPlane = null; }
  41149. var changed = false;
  41150. var useClipPlane1 = false;
  41151. var useClipPlane2 = false;
  41152. var useClipPlane3 = false;
  41153. var useClipPlane4 = false;
  41154. useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane;
  41155. useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane;
  41156. useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane;
  41157. useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane;
  41158. if (defines["CLIPPLANE"] !== useClipPlane1) {
  41159. defines["CLIPPLANE"] = useClipPlane1;
  41160. changed = true;
  41161. }
  41162. if (defines["CLIPPLANE2"] !== useClipPlane2) {
  41163. defines["CLIPPLANE2"] = useClipPlane2;
  41164. changed = true;
  41165. }
  41166. if (defines["CLIPPLANE3"] !== useClipPlane3) {
  41167. defines["CLIPPLANE3"] = useClipPlane3;
  41168. changed = true;
  41169. }
  41170. if (defines["CLIPPLANE4"] !== useClipPlane4) {
  41171. defines["CLIPPLANE4"] = useClipPlane4;
  41172. changed = true;
  41173. }
  41174. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41175. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41176. changed = true;
  41177. }
  41178. if (defines["INSTANCES"] !== useInstances) {
  41179. defines["INSTANCES"] = useInstances;
  41180. changed = true;
  41181. }
  41182. if (changed) {
  41183. defines.markAsUnprocessed();
  41184. }
  41185. };
  41186. /**
  41187. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41188. * @param mesh The mesh containing the geometry data we will draw
  41189. * @param defines The defines to update
  41190. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41191. * @param useBones Precise whether bones should be used or not (override mesh info)
  41192. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41193. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41194. * @returns false if defines are considered not dirty and have not been checked
  41195. */
  41196. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41197. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41198. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41199. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41200. return false;
  41201. }
  41202. defines._normals = defines._needNormals;
  41203. defines._uvs = defines._needUVs;
  41204. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41205. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41206. defines["TANGENT"] = true;
  41207. }
  41208. if (defines._needUVs) {
  41209. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41210. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41211. }
  41212. else {
  41213. defines["UV1"] = false;
  41214. defines["UV2"] = false;
  41215. }
  41216. if (useVertexColor) {
  41217. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41218. defines["VERTEXCOLOR"] = hasVertexColors;
  41219. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41220. }
  41221. if (useBones) {
  41222. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41223. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41224. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41225. }
  41226. else {
  41227. defines["NUM_BONE_INFLUENCERS"] = 0;
  41228. defines["BonesPerMesh"] = 0;
  41229. }
  41230. }
  41231. if (useMorphTargets) {
  41232. var manager = mesh.morphTargetManager;
  41233. if (manager) {
  41234. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41235. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41236. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41237. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41238. }
  41239. else {
  41240. defines["MORPHTARGETS_TANGENT"] = false;
  41241. defines["MORPHTARGETS_NORMAL"] = false;
  41242. defines["MORPHTARGETS"] = false;
  41243. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41244. }
  41245. }
  41246. return true;
  41247. };
  41248. /**
  41249. * Prepares the defines related to the light information passed in parameter
  41250. * @param scene The scene we are intending to draw
  41251. * @param mesh The mesh the effect is compiling for
  41252. * @param defines The defines to update
  41253. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41254. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41255. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41256. * @returns true if normals will be required for the rest of the effect
  41257. */
  41258. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41259. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41260. if (disableLighting === void 0) { disableLighting = false; }
  41261. if (!defines._areLightsDirty) {
  41262. return defines._needNormals;
  41263. }
  41264. var lightIndex = 0;
  41265. var needNormals = false;
  41266. var needRebuild = false;
  41267. var lightmapMode = false;
  41268. var shadowEnabled = false;
  41269. var specularEnabled = false;
  41270. if (scene.lightsEnabled && !disableLighting) {
  41271. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41272. var light = _a[_i];
  41273. needNormals = true;
  41274. if (defines["LIGHT" + lightIndex] === undefined) {
  41275. needRebuild = true;
  41276. }
  41277. defines["LIGHT" + lightIndex] = true;
  41278. defines["SPOTLIGHT" + lightIndex] = false;
  41279. defines["HEMILIGHT" + lightIndex] = false;
  41280. defines["POINTLIGHT" + lightIndex] = false;
  41281. defines["DIRLIGHT" + lightIndex] = false;
  41282. light.prepareLightSpecificDefines(defines, lightIndex);
  41283. // FallOff.
  41284. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  41285. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  41286. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  41287. switch (light.falloffType) {
  41288. case BABYLON.Light.FALLOFF_GLTF:
  41289. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  41290. break;
  41291. case BABYLON.Light.FALLOFF_PHYSICAL:
  41292. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  41293. break;
  41294. case BABYLON.Light.FALLOFF_STANDARD:
  41295. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  41296. break;
  41297. }
  41298. // Specular
  41299. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41300. specularEnabled = true;
  41301. }
  41302. // Shadows
  41303. defines["SHADOW" + lightIndex] = false;
  41304. defines["SHADOWPCF" + lightIndex] = false;
  41305. defines["SHADOWPCSS" + lightIndex] = false;
  41306. defines["SHADOWPOISSON" + lightIndex] = false;
  41307. defines["SHADOWESM" + lightIndex] = false;
  41308. defines["SHADOWCUBE" + lightIndex] = false;
  41309. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41310. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41311. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41312. var shadowGenerator = light.getShadowGenerator();
  41313. if (shadowGenerator) {
  41314. var shadowMap = shadowGenerator.getShadowMap();
  41315. if (shadowMap) {
  41316. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  41317. shadowEnabled = true;
  41318. shadowGenerator.prepareDefines(defines, lightIndex);
  41319. }
  41320. }
  41321. }
  41322. }
  41323. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41324. lightmapMode = true;
  41325. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41326. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41327. }
  41328. else {
  41329. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41330. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41331. }
  41332. lightIndex++;
  41333. if (lightIndex === maxSimultaneousLights)
  41334. break;
  41335. }
  41336. }
  41337. defines["SPECULARTERM"] = specularEnabled;
  41338. defines["SHADOWS"] = shadowEnabled;
  41339. // Resetting all other lights if any
  41340. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41341. if (defines["LIGHT" + index] !== undefined) {
  41342. defines["LIGHT" + index] = false;
  41343. defines["HEMILIGHT" + lightIndex] = false;
  41344. defines["POINTLIGHT" + lightIndex] = false;
  41345. defines["DIRLIGHT" + lightIndex] = false;
  41346. defines["SPOTLIGHT" + lightIndex] = false;
  41347. defines["SHADOW" + lightIndex] = false;
  41348. }
  41349. }
  41350. var caps = scene.getEngine().getCaps();
  41351. if (defines["SHADOWFLOAT"] === undefined) {
  41352. needRebuild = true;
  41353. }
  41354. defines["SHADOWFLOAT"] = shadowEnabled &&
  41355. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41356. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41357. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41358. if (needRebuild) {
  41359. defines.rebuild();
  41360. }
  41361. return needNormals;
  41362. };
  41363. /**
  41364. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41365. * that won t be acctive due to defines being turned off.
  41366. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41367. * @param samplersList The samplers list
  41368. * @param defines The defines helping in the list generation
  41369. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41370. */
  41371. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41372. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41373. var uniformsList;
  41374. var uniformBuffersList = null;
  41375. if (uniformsListOrOptions.uniformsNames) {
  41376. var options = uniformsListOrOptions;
  41377. uniformsList = options.uniformsNames;
  41378. uniformBuffersList = options.uniformBuffersNames;
  41379. samplersList = options.samplers;
  41380. defines = options.defines;
  41381. maxSimultaneousLights = options.maxSimultaneousLights;
  41382. }
  41383. else {
  41384. uniformsList = uniformsListOrOptions;
  41385. if (!samplersList) {
  41386. samplersList = [];
  41387. }
  41388. }
  41389. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41390. if (!defines["LIGHT" + lightIndex]) {
  41391. break;
  41392. }
  41393. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41394. if (uniformBuffersList) {
  41395. uniformBuffersList.push("Light" + lightIndex);
  41396. }
  41397. samplersList.push("shadowSampler" + lightIndex);
  41398. samplersList.push("depthSampler" + lightIndex);
  41399. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41400. samplersList.push("projectionLightSampler" + lightIndex);
  41401. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41402. }
  41403. }
  41404. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41405. uniformsList.push("morphTargetInfluences");
  41406. }
  41407. };
  41408. /**
  41409. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41410. * @param defines The defines to update while falling back
  41411. * @param fallbacks The authorized effect fallbacks
  41412. * @param maxSimultaneousLights The maximum number of lights allowed
  41413. * @param rank the current rank of the Effect
  41414. * @returns The newly affected rank
  41415. */
  41416. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41417. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41418. if (rank === void 0) { rank = 0; }
  41419. var lightFallbackRank = 0;
  41420. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41421. if (!defines["LIGHT" + lightIndex]) {
  41422. break;
  41423. }
  41424. if (lightIndex > 0) {
  41425. lightFallbackRank = rank + lightIndex;
  41426. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41427. }
  41428. if (!defines["SHADOWS"]) {
  41429. if (defines["SHADOW" + lightIndex]) {
  41430. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41431. }
  41432. if (defines["SHADOWPCF" + lightIndex]) {
  41433. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41434. }
  41435. if (defines["SHADOWPCSS" + lightIndex]) {
  41436. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41437. }
  41438. if (defines["SHADOWPOISSON" + lightIndex]) {
  41439. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41440. }
  41441. if (defines["SHADOWESM" + lightIndex]) {
  41442. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41443. }
  41444. }
  41445. }
  41446. return lightFallbackRank++;
  41447. };
  41448. /**
  41449. * Prepares the list of attributes required for morph targets according to the effect defines.
  41450. * @param attribs The current list of supported attribs
  41451. * @param mesh The mesh to prepare the morph targets attributes for
  41452. * @param defines The current Defines of the effect
  41453. */
  41454. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41455. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41456. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41457. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41458. var manager = mesh.morphTargetManager;
  41459. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41460. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41461. for (var index = 0; index < influencers; index++) {
  41462. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41463. if (normal) {
  41464. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41465. }
  41466. if (tangent) {
  41467. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41468. }
  41469. if (attribs.length > maxAttributesCount) {
  41470. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41471. }
  41472. }
  41473. }
  41474. };
  41475. /**
  41476. * Prepares the list of attributes required for bones according to the effect defines.
  41477. * @param attribs The current list of supported attribs
  41478. * @param mesh The mesh to prepare the bones attributes for
  41479. * @param defines The current Defines of the effect
  41480. * @param fallbacks The current efffect fallback strategy
  41481. */
  41482. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41483. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41484. fallbacks.addCPUSkinningFallback(0, mesh);
  41485. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41486. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41487. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41488. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41489. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41490. }
  41491. }
  41492. };
  41493. /**
  41494. * Prepares the list of attributes required for instances according to the effect defines.
  41495. * @param attribs The current list of supported attribs
  41496. * @param defines The current Defines of the effect
  41497. */
  41498. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41499. if (defines["INSTANCES"]) {
  41500. attribs.push("world0");
  41501. attribs.push("world1");
  41502. attribs.push("world2");
  41503. attribs.push("world3");
  41504. }
  41505. };
  41506. /**
  41507. * Binds the light shadow information to the effect for the given mesh.
  41508. * @param light The light containing the generator
  41509. * @param scene The scene the lights belongs to
  41510. * @param mesh The mesh we are binding the information to render
  41511. * @param lightIndex The light index in the effect used to render the mesh
  41512. * @param effect The effect we are binding the data to
  41513. */
  41514. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41515. if (light.shadowEnabled && mesh.receiveShadows) {
  41516. var shadowGenerator = light.getShadowGenerator();
  41517. if (shadowGenerator) {
  41518. shadowGenerator.bindShadowLight(lightIndex, effect);
  41519. }
  41520. }
  41521. };
  41522. /**
  41523. * Binds the light information to the effect.
  41524. * @param light The light containing the generator
  41525. * @param effect The effect we are binding the data to
  41526. * @param lightIndex The light index in the effect used to render
  41527. */
  41528. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41529. light.transferToEffect(effect, lightIndex + "");
  41530. };
  41531. /**
  41532. * Binds the lights information from the scene to the effect for the given mesh.
  41533. * @param scene The scene the lights belongs to
  41534. * @param mesh The mesh we are binding the information to render
  41535. * @param effect The effect we are binding the data to
  41536. * @param defines The generated defines for the effect
  41537. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41538. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41539. */
  41540. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41541. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41542. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41543. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41544. for (var i = 0; i < len; i++) {
  41545. var light = mesh._lightSources[i];
  41546. var iAsString = i.toString();
  41547. var scaledIntensity = light.getScaledIntensity();
  41548. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41549. MaterialHelper.BindLightProperties(light, effect, i);
  41550. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41551. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41552. if (defines["SPECULARTERM"]) {
  41553. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41554. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41555. }
  41556. // Shadows
  41557. if (scene.shadowsEnabled) {
  41558. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41559. }
  41560. light._uniformBuffer.update();
  41561. }
  41562. };
  41563. /**
  41564. * Binds the fog information from the scene to the effect for the given mesh.
  41565. * @param scene The scene the lights belongs to
  41566. * @param mesh The mesh we are binding the information to render
  41567. * @param effect The effect we are binding the data to
  41568. */
  41569. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41570. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41571. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41572. effect.setColor3("vFogColor", scene.fogColor);
  41573. }
  41574. };
  41575. /**
  41576. * Binds the bones information from the mesh to the effect.
  41577. * @param mesh The mesh we are binding the information to render
  41578. * @param effect The effect we are binding the data to
  41579. */
  41580. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41581. if (!effect || !mesh) {
  41582. return;
  41583. }
  41584. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41585. mesh.computeBonesUsingShaders = false;
  41586. }
  41587. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41588. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41589. if (matrices) {
  41590. effect.setMatrices("mBones", matrices);
  41591. }
  41592. }
  41593. };
  41594. /**
  41595. * Binds the morph targets information from the mesh to the effect.
  41596. * @param abstractMesh The mesh we are binding the information to render
  41597. * @param effect The effect we are binding the data to
  41598. */
  41599. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41600. var manager = abstractMesh.morphTargetManager;
  41601. if (!abstractMesh || !manager) {
  41602. return;
  41603. }
  41604. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41605. };
  41606. /**
  41607. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41608. * @param defines The generated defines used in the effect
  41609. * @param effect The effect we are binding the data to
  41610. * @param scene The scene we are willing to render with logarithmic scale for
  41611. */
  41612. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41613. if (defines["LOGARITHMICDEPTH"]) {
  41614. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41615. }
  41616. };
  41617. /**
  41618. * Binds the clip plane information from the scene to the effect.
  41619. * @param scene The scene the clip plane information are extracted from
  41620. * @param effect The effect we are binding the data to
  41621. */
  41622. MaterialHelper.BindClipPlane = function (effect, scene) {
  41623. if (scene.clipPlane) {
  41624. var clipPlane = scene.clipPlane;
  41625. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41626. }
  41627. if (scene.clipPlane2) {
  41628. var clipPlane = scene.clipPlane2;
  41629. effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41630. }
  41631. if (scene.clipPlane3) {
  41632. var clipPlane = scene.clipPlane3;
  41633. effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41634. }
  41635. if (scene.clipPlane4) {
  41636. var clipPlane = scene.clipPlane4;
  41637. effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41638. }
  41639. };
  41640. return MaterialHelper;
  41641. }());
  41642. BABYLON.MaterialHelper = MaterialHelper;
  41643. })(BABYLON || (BABYLON = {}));
  41644. //# sourceMappingURL=babylon.materialHelper.js.map
  41645. var BABYLON;
  41646. (function (BABYLON) {
  41647. var PushMaterial = /** @class */ (function (_super) {
  41648. __extends(PushMaterial, _super);
  41649. function PushMaterial(name, scene) {
  41650. var _this = _super.call(this, name, scene) || this;
  41651. _this._normalMatrix = new BABYLON.Matrix();
  41652. _this.storeEffectOnSubMeshes = true;
  41653. return _this;
  41654. }
  41655. PushMaterial.prototype.getEffect = function () {
  41656. return this._activeEffect;
  41657. };
  41658. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41659. if (!mesh) {
  41660. return false;
  41661. }
  41662. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41663. return true;
  41664. }
  41665. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41666. };
  41667. /**
  41668. * Binds the given world matrix to the active effect
  41669. *
  41670. * @param world the matrix to bind
  41671. */
  41672. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41673. this._activeEffect.setMatrix("world", world);
  41674. };
  41675. /**
  41676. * Binds the given normal matrix to the active effect
  41677. *
  41678. * @param normalMatrix the matrix to bind
  41679. */
  41680. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41681. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41682. };
  41683. PushMaterial.prototype.bind = function (world, mesh) {
  41684. if (!mesh) {
  41685. return;
  41686. }
  41687. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41688. };
  41689. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41690. if (effect === void 0) { effect = null; }
  41691. _super.prototype._afterBind.call(this, mesh);
  41692. this.getScene()._cachedEffect = effect;
  41693. };
  41694. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41695. if (visibility === void 0) { visibility = 1; }
  41696. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41697. };
  41698. return PushMaterial;
  41699. }(BABYLON.Material));
  41700. BABYLON.PushMaterial = PushMaterial;
  41701. })(BABYLON || (BABYLON = {}));
  41702. //# sourceMappingURL=babylon.pushMaterial.js.map
  41703. var BABYLON;
  41704. (function (BABYLON) {
  41705. /** @hidden */
  41706. var StandardMaterialDefines = /** @class */ (function (_super) {
  41707. __extends(StandardMaterialDefines, _super);
  41708. function StandardMaterialDefines() {
  41709. var _this = _super.call(this) || this;
  41710. _this.MAINUV1 = false;
  41711. _this.MAINUV2 = false;
  41712. _this.DIFFUSE = false;
  41713. _this.DIFFUSEDIRECTUV = 0;
  41714. _this.AMBIENT = false;
  41715. _this.AMBIENTDIRECTUV = 0;
  41716. _this.OPACITY = false;
  41717. _this.OPACITYDIRECTUV = 0;
  41718. _this.OPACITYRGB = false;
  41719. _this.REFLECTION = false;
  41720. _this.EMISSIVE = false;
  41721. _this.EMISSIVEDIRECTUV = 0;
  41722. _this.SPECULAR = false;
  41723. _this.SPECULARDIRECTUV = 0;
  41724. _this.BUMP = false;
  41725. _this.BUMPDIRECTUV = 0;
  41726. _this.PARALLAX = false;
  41727. _this.PARALLAXOCCLUSION = false;
  41728. _this.SPECULAROVERALPHA = false;
  41729. _this.CLIPPLANE = false;
  41730. _this.CLIPPLANE2 = false;
  41731. _this.CLIPPLANE3 = false;
  41732. _this.CLIPPLANE4 = false;
  41733. _this.ALPHATEST = false;
  41734. _this.DEPTHPREPASS = false;
  41735. _this.ALPHAFROMDIFFUSE = false;
  41736. _this.POINTSIZE = false;
  41737. _this.FOG = false;
  41738. _this.SPECULARTERM = false;
  41739. _this.DIFFUSEFRESNEL = false;
  41740. _this.OPACITYFRESNEL = false;
  41741. _this.REFLECTIONFRESNEL = false;
  41742. _this.REFRACTIONFRESNEL = false;
  41743. _this.EMISSIVEFRESNEL = false;
  41744. _this.FRESNEL = false;
  41745. _this.NORMAL = false;
  41746. _this.UV1 = false;
  41747. _this.UV2 = false;
  41748. _this.VERTEXCOLOR = false;
  41749. _this.VERTEXALPHA = false;
  41750. _this.NUM_BONE_INFLUENCERS = 0;
  41751. _this.BonesPerMesh = 0;
  41752. _this.INSTANCES = false;
  41753. _this.GLOSSINESS = false;
  41754. _this.ROUGHNESS = false;
  41755. _this.EMISSIVEASILLUMINATION = false;
  41756. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41757. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41758. _this.LIGHTMAP = false;
  41759. _this.LIGHTMAPDIRECTUV = 0;
  41760. _this.OBJECTSPACE_NORMALMAP = false;
  41761. _this.USELIGHTMAPASSHADOWMAP = false;
  41762. _this.REFLECTIONMAP_3D = false;
  41763. _this.REFLECTIONMAP_SPHERICAL = false;
  41764. _this.REFLECTIONMAP_PLANAR = false;
  41765. _this.REFLECTIONMAP_CUBIC = false;
  41766. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41767. _this.REFLECTIONMAP_PROJECTION = false;
  41768. _this.REFLECTIONMAP_SKYBOX = false;
  41769. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  41770. _this.REFLECTIONMAP_EXPLICIT = false;
  41771. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41772. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41773. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41774. _this.INVERTCUBICMAP = false;
  41775. _this.LOGARITHMICDEPTH = false;
  41776. _this.REFRACTION = false;
  41777. _this.REFRACTIONMAP_3D = false;
  41778. _this.REFLECTIONOVERALPHA = false;
  41779. _this.TWOSIDEDLIGHTING = false;
  41780. _this.SHADOWFLOAT = false;
  41781. _this.MORPHTARGETS = false;
  41782. _this.MORPHTARGETS_NORMAL = false;
  41783. _this.MORPHTARGETS_TANGENT = false;
  41784. _this.NUM_MORPH_INFLUENCERS = 0;
  41785. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41786. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41787. _this.IMAGEPROCESSING = false;
  41788. _this.VIGNETTE = false;
  41789. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41790. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41791. _this.TONEMAPPING = false;
  41792. _this.TONEMAPPING_ACES = false;
  41793. _this.CONTRAST = false;
  41794. _this.COLORCURVES = false;
  41795. _this.COLORGRADING = false;
  41796. _this.COLORGRADING3D = false;
  41797. _this.SAMPLER3DGREENDEPTH = false;
  41798. _this.SAMPLER3DBGRMAP = false;
  41799. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41800. /**
  41801. * If the reflection texture on this material is in linear color space
  41802. * @hidden
  41803. */
  41804. _this.IS_REFLECTION_LINEAR = false;
  41805. /**
  41806. * If the refraction texture on this material is in linear color space
  41807. * @hidden
  41808. */
  41809. _this.IS_REFRACTION_LINEAR = false;
  41810. _this.EXPOSURE = false;
  41811. _this.rebuild();
  41812. return _this;
  41813. }
  41814. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41815. var modes = [
  41816. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41817. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41818. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41819. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41820. ];
  41821. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41822. var mode = modes_1[_i];
  41823. this[mode] = (mode === modeToEnable);
  41824. }
  41825. };
  41826. return StandardMaterialDefines;
  41827. }(BABYLON.MaterialDefines));
  41828. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41829. var StandardMaterial = /** @class */ (function (_super) {
  41830. __extends(StandardMaterial, _super);
  41831. function StandardMaterial(name, scene) {
  41832. var _this = _super.call(this, name, scene) || this;
  41833. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41834. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41835. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41836. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41837. _this.specularPower = 64;
  41838. _this._useAlphaFromDiffuseTexture = false;
  41839. _this._useEmissiveAsIllumination = false;
  41840. _this._linkEmissiveWithDiffuse = false;
  41841. _this._useSpecularOverAlpha = false;
  41842. _this._useReflectionOverAlpha = false;
  41843. _this._disableLighting = false;
  41844. _this._useObjectSpaceNormalMap = false;
  41845. _this._useParallax = false;
  41846. _this._useParallaxOcclusion = false;
  41847. _this.parallaxScaleBias = 0.05;
  41848. _this._roughness = 0;
  41849. _this.indexOfRefraction = 0.98;
  41850. _this.invertRefractionY = true;
  41851. /**
  41852. * Defines the alpha limits in alpha test mode
  41853. */
  41854. _this.alphaCutOff = 0.4;
  41855. _this._useLightmapAsShadowmap = false;
  41856. _this._useReflectionFresnelFromSpecular = false;
  41857. _this._useGlossinessFromSpecularMapAlpha = false;
  41858. _this._maxSimultaneousLights = 4;
  41859. /**
  41860. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41861. */
  41862. _this._invertNormalMapX = false;
  41863. /**
  41864. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41865. */
  41866. _this._invertNormalMapY = false;
  41867. /**
  41868. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41869. */
  41870. _this._twoSidedLighting = false;
  41871. _this._renderTargets = new BABYLON.SmartArray(16);
  41872. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41873. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41874. // Setup the default processing configuration to the scene.
  41875. _this._attachImageProcessingConfiguration(null);
  41876. _this.getRenderTargetTextures = function () {
  41877. _this._renderTargets.reset();
  41878. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41879. _this._renderTargets.push(_this._reflectionTexture);
  41880. }
  41881. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41882. _this._renderTargets.push(_this._refractionTexture);
  41883. }
  41884. return _this._renderTargets;
  41885. };
  41886. return _this;
  41887. }
  41888. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41889. /**
  41890. * Gets the image processing configuration used either in this material.
  41891. */
  41892. get: function () {
  41893. return this._imageProcessingConfiguration;
  41894. },
  41895. /**
  41896. * Sets the Default image processing configuration used either in the this material.
  41897. *
  41898. * If sets to null, the scene one is in use.
  41899. */
  41900. set: function (value) {
  41901. this._attachImageProcessingConfiguration(value);
  41902. // Ensure the effect will be rebuilt.
  41903. this._markAllSubMeshesAsTexturesDirty();
  41904. },
  41905. enumerable: true,
  41906. configurable: true
  41907. });
  41908. /**
  41909. * Attaches a new image processing configuration to the Standard Material.
  41910. * @param configuration
  41911. */
  41912. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41913. var _this = this;
  41914. if (configuration === this._imageProcessingConfiguration) {
  41915. return;
  41916. }
  41917. // Detaches observer.
  41918. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41919. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41920. }
  41921. // Pick the scene configuration if needed.
  41922. if (!configuration) {
  41923. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41924. }
  41925. else {
  41926. this._imageProcessingConfiguration = configuration;
  41927. }
  41928. // Attaches observer.
  41929. if (this._imageProcessingConfiguration) {
  41930. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41931. _this._markAllSubMeshesAsImageProcessingDirty();
  41932. });
  41933. }
  41934. };
  41935. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  41936. /**
  41937. * Gets wether the color curves effect is enabled.
  41938. */
  41939. get: function () {
  41940. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41941. },
  41942. /**
  41943. * Sets wether the color curves effect is enabled.
  41944. */
  41945. set: function (value) {
  41946. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41947. },
  41948. enumerable: true,
  41949. configurable: true
  41950. });
  41951. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  41952. /**
  41953. * Gets wether the color grading effect is enabled.
  41954. */
  41955. get: function () {
  41956. return this.imageProcessingConfiguration.colorGradingEnabled;
  41957. },
  41958. /**
  41959. * Gets wether the color grading effect is enabled.
  41960. */
  41961. set: function (value) {
  41962. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41963. },
  41964. enumerable: true,
  41965. configurable: true
  41966. });
  41967. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  41968. /**
  41969. * Gets wether tonemapping is enabled or not.
  41970. */
  41971. get: function () {
  41972. return this._imageProcessingConfiguration.toneMappingEnabled;
  41973. },
  41974. /**
  41975. * Sets wether tonemapping is enabled or not
  41976. */
  41977. set: function (value) {
  41978. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41979. },
  41980. enumerable: true,
  41981. configurable: true
  41982. });
  41983. ;
  41984. ;
  41985. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  41986. /**
  41987. * The camera exposure used on this material.
  41988. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41989. * This corresponds to a photographic exposure.
  41990. */
  41991. get: function () {
  41992. return this._imageProcessingConfiguration.exposure;
  41993. },
  41994. /**
  41995. * The camera exposure used on this material.
  41996. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41997. * This corresponds to a photographic exposure.
  41998. */
  41999. set: function (value) {
  42000. this._imageProcessingConfiguration.exposure = value;
  42001. },
  42002. enumerable: true,
  42003. configurable: true
  42004. });
  42005. ;
  42006. ;
  42007. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42008. /**
  42009. * Gets The camera contrast used on this material.
  42010. */
  42011. get: function () {
  42012. return this._imageProcessingConfiguration.contrast;
  42013. },
  42014. /**
  42015. * Sets The camera contrast used on this material.
  42016. */
  42017. set: function (value) {
  42018. this._imageProcessingConfiguration.contrast = value;
  42019. },
  42020. enumerable: true,
  42021. configurable: true
  42022. });
  42023. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42024. /**
  42025. * Gets the Color Grading 2D Lookup Texture.
  42026. */
  42027. get: function () {
  42028. return this._imageProcessingConfiguration.colorGradingTexture;
  42029. },
  42030. /**
  42031. * Sets the Color Grading 2D Lookup Texture.
  42032. */
  42033. set: function (value) {
  42034. this._imageProcessingConfiguration.colorGradingTexture = value;
  42035. },
  42036. enumerable: true,
  42037. configurable: true
  42038. });
  42039. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42040. /**
  42041. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42042. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42043. * 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;
  42044. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42045. */
  42046. get: function () {
  42047. return this._imageProcessingConfiguration.colorCurves;
  42048. },
  42049. /**
  42050. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42051. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42052. * 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;
  42053. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42054. */
  42055. set: function (value) {
  42056. this._imageProcessingConfiguration.colorCurves = value;
  42057. },
  42058. enumerable: true,
  42059. configurable: true
  42060. });
  42061. StandardMaterial.prototype.getClassName = function () {
  42062. return "StandardMaterial";
  42063. };
  42064. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42065. get: function () {
  42066. return this._useLogarithmicDepth;
  42067. },
  42068. set: function (value) {
  42069. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42070. this._markAllSubMeshesAsMiscDirty();
  42071. },
  42072. enumerable: true,
  42073. configurable: true
  42074. });
  42075. StandardMaterial.prototype.needAlphaBlending = function () {
  42076. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42077. };
  42078. StandardMaterial.prototype.needAlphaTesting = function () {
  42079. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42080. };
  42081. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42082. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42083. };
  42084. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42085. return this._diffuseTexture;
  42086. };
  42087. /**
  42088. * Child classes can use it to update shaders
  42089. */
  42090. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42091. if (useInstances === void 0) { useInstances = false; }
  42092. if (subMesh.effect && this.isFrozen) {
  42093. if (this._wasPreviouslyReady) {
  42094. return true;
  42095. }
  42096. }
  42097. if (!subMesh._materialDefines) {
  42098. subMesh._materialDefines = new StandardMaterialDefines();
  42099. }
  42100. var scene = this.getScene();
  42101. var defines = subMesh._materialDefines;
  42102. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42103. if (defines._renderId === scene.getRenderId()) {
  42104. return true;
  42105. }
  42106. }
  42107. var engine = scene.getEngine();
  42108. // Lights
  42109. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42110. // Textures
  42111. if (defines._areTexturesDirty) {
  42112. defines._needUVs = false;
  42113. defines.MAINUV1 = false;
  42114. defines.MAINUV2 = false;
  42115. if (scene.texturesEnabled) {
  42116. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42117. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42118. return false;
  42119. }
  42120. else {
  42121. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42122. }
  42123. }
  42124. else {
  42125. defines.DIFFUSE = false;
  42126. }
  42127. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42128. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42129. return false;
  42130. }
  42131. else {
  42132. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42133. }
  42134. }
  42135. else {
  42136. defines.AMBIENT = false;
  42137. }
  42138. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42139. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42140. return false;
  42141. }
  42142. else {
  42143. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42144. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42145. }
  42146. }
  42147. else {
  42148. defines.OPACITY = false;
  42149. }
  42150. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42151. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42152. return false;
  42153. }
  42154. else {
  42155. defines._needNormals = true;
  42156. defines.REFLECTION = true;
  42157. defines.ROUGHNESS = (this._roughness > 0);
  42158. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42159. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42160. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42161. switch (this._reflectionTexture.coordinatesMode) {
  42162. case BABYLON.Texture.EXPLICIT_MODE:
  42163. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42164. break;
  42165. case BABYLON.Texture.PLANAR_MODE:
  42166. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42167. break;
  42168. case BABYLON.Texture.PROJECTION_MODE:
  42169. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42170. break;
  42171. case BABYLON.Texture.SKYBOX_MODE:
  42172. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42173. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !this._reflectionTexture.getReflectionTextureMatrix().isIdentity();
  42174. break;
  42175. case BABYLON.Texture.SPHERICAL_MODE:
  42176. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42177. break;
  42178. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42179. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42180. break;
  42181. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42182. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42183. break;
  42184. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42185. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42186. break;
  42187. case BABYLON.Texture.CUBIC_MODE:
  42188. case BABYLON.Texture.INVCUBIC_MODE:
  42189. default:
  42190. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42191. break;
  42192. }
  42193. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42194. }
  42195. }
  42196. else {
  42197. defines.REFLECTION = false;
  42198. }
  42199. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42200. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42201. return false;
  42202. }
  42203. else {
  42204. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42205. }
  42206. }
  42207. else {
  42208. defines.EMISSIVE = false;
  42209. }
  42210. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42211. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42212. return false;
  42213. }
  42214. else {
  42215. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42216. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42217. }
  42218. }
  42219. else {
  42220. defines.LIGHTMAP = false;
  42221. }
  42222. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42223. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42224. return false;
  42225. }
  42226. else {
  42227. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42228. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42229. }
  42230. }
  42231. else {
  42232. defines.SPECULAR = false;
  42233. }
  42234. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42235. // Bump texure can not be not blocking.
  42236. if (!this._bumpTexture.isReady()) {
  42237. return false;
  42238. }
  42239. else {
  42240. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42241. defines.PARALLAX = this._useParallax;
  42242. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42243. }
  42244. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42245. }
  42246. else {
  42247. defines.BUMP = false;
  42248. }
  42249. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42250. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42251. return false;
  42252. }
  42253. else {
  42254. defines._needUVs = true;
  42255. defines.REFRACTION = true;
  42256. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42257. }
  42258. }
  42259. else {
  42260. defines.REFRACTION = false;
  42261. }
  42262. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42263. }
  42264. else {
  42265. defines.DIFFUSE = false;
  42266. defines.AMBIENT = false;
  42267. defines.OPACITY = false;
  42268. defines.REFLECTION = false;
  42269. defines.EMISSIVE = false;
  42270. defines.LIGHTMAP = false;
  42271. defines.BUMP = false;
  42272. defines.REFRACTION = false;
  42273. }
  42274. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42275. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42276. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42277. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42278. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42279. }
  42280. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  42281. if (!this._imageProcessingConfiguration.isReady()) {
  42282. return false;
  42283. }
  42284. this._imageProcessingConfiguration.prepareDefines(defines);
  42285. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  42286. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  42287. }
  42288. if (defines._areFresnelDirty) {
  42289. if (StandardMaterial.FresnelEnabled) {
  42290. // Fresnel
  42291. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42292. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42293. this._reflectionFresnelParameters) {
  42294. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42295. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42296. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42297. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42298. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42299. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42300. defines._needNormals = true;
  42301. defines.FRESNEL = true;
  42302. }
  42303. }
  42304. else {
  42305. defines.FRESNEL = false;
  42306. }
  42307. }
  42308. // Misc.
  42309. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42310. // Attribs
  42311. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42312. // Values that need to be evaluated on every frame
  42313. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42314. // Get correct effect
  42315. if (defines.isDirty) {
  42316. defines.markAsProcessed();
  42317. scene.resetCachedMaterial();
  42318. // Fallbacks
  42319. var fallbacks = new BABYLON.EffectFallbacks();
  42320. if (defines.REFLECTION) {
  42321. fallbacks.addFallback(0, "REFLECTION");
  42322. }
  42323. if (defines.SPECULAR) {
  42324. fallbacks.addFallback(0, "SPECULAR");
  42325. }
  42326. if (defines.BUMP) {
  42327. fallbacks.addFallback(0, "BUMP");
  42328. }
  42329. if (defines.PARALLAX) {
  42330. fallbacks.addFallback(1, "PARALLAX");
  42331. }
  42332. if (defines.PARALLAXOCCLUSION) {
  42333. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42334. }
  42335. if (defines.SPECULAROVERALPHA) {
  42336. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42337. }
  42338. if (defines.FOG) {
  42339. fallbacks.addFallback(1, "FOG");
  42340. }
  42341. if (defines.POINTSIZE) {
  42342. fallbacks.addFallback(0, "POINTSIZE");
  42343. }
  42344. if (defines.LOGARITHMICDEPTH) {
  42345. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42346. }
  42347. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42348. if (defines.SPECULARTERM) {
  42349. fallbacks.addFallback(0, "SPECULARTERM");
  42350. }
  42351. if (defines.DIFFUSEFRESNEL) {
  42352. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42353. }
  42354. if (defines.OPACITYFRESNEL) {
  42355. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42356. }
  42357. if (defines.REFLECTIONFRESNEL) {
  42358. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42359. }
  42360. if (defines.EMISSIVEFRESNEL) {
  42361. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42362. }
  42363. if (defines.FRESNEL) {
  42364. fallbacks.addFallback(4, "FRESNEL");
  42365. }
  42366. //Attributes
  42367. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42368. if (defines.NORMAL) {
  42369. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42370. }
  42371. if (defines.UV1) {
  42372. attribs.push(BABYLON.VertexBuffer.UVKind);
  42373. }
  42374. if (defines.UV2) {
  42375. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42376. }
  42377. if (defines.VERTEXCOLOR) {
  42378. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42379. }
  42380. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42381. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42382. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42383. var shaderName = "default";
  42384. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42385. "vFogInfos", "vFogColor", "pointSize",
  42386. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42387. "mBones",
  42388. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42389. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42390. "vReflectionPosition", "vReflectionSize",
  42391. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42392. ];
  42393. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42394. var uniformBuffers = ["Material", "Scene"];
  42395. if (BABYLON.ImageProcessingConfiguration) {
  42396. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42397. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42398. }
  42399. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42400. uniformsNames: uniforms,
  42401. uniformBuffersNames: uniformBuffers,
  42402. samplers: samplers,
  42403. defines: defines,
  42404. maxSimultaneousLights: this._maxSimultaneousLights
  42405. });
  42406. if (this.customShaderNameResolve) {
  42407. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42408. }
  42409. var join = defines.toString();
  42410. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42411. attributes: attribs,
  42412. uniformsNames: uniforms,
  42413. uniformBuffersNames: uniformBuffers,
  42414. samplers: samplers,
  42415. defines: join,
  42416. fallbacks: fallbacks,
  42417. onCompiled: this.onCompiled,
  42418. onError: this.onError,
  42419. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42420. }, engine), defines);
  42421. this.buildUniformLayout();
  42422. }
  42423. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42424. return false;
  42425. }
  42426. defines._renderId = scene.getRenderId();
  42427. this._wasPreviouslyReady = true;
  42428. return true;
  42429. };
  42430. StandardMaterial.prototype.buildUniformLayout = function () {
  42431. // Order is important !
  42432. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42433. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42434. this._uniformBuffer.addUniform("opacityParts", 4);
  42435. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42436. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42437. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42438. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42439. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42440. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42441. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42442. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42443. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42444. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42445. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42446. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42447. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42448. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42449. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42450. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42451. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42452. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42453. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42454. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42455. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42456. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42457. this._uniformBuffer.addUniform("specularMatrix", 16);
  42458. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42459. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42460. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42461. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42462. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42463. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42464. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42465. this._uniformBuffer.addUniform("pointSize", 1);
  42466. this._uniformBuffer.create();
  42467. };
  42468. StandardMaterial.prototype.unbind = function () {
  42469. if (this._activeEffect) {
  42470. var needFlag = false;
  42471. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42472. this._activeEffect.setTexture("reflection2DSampler", null);
  42473. needFlag = true;
  42474. }
  42475. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42476. this._activeEffect.setTexture("refraction2DSampler", null);
  42477. needFlag = true;
  42478. }
  42479. if (needFlag) {
  42480. this._markAllSubMeshesAsTexturesDirty();
  42481. }
  42482. }
  42483. _super.prototype.unbind.call(this);
  42484. };
  42485. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42486. var scene = this.getScene();
  42487. var defines = subMesh._materialDefines;
  42488. if (!defines) {
  42489. return;
  42490. }
  42491. var effect = subMesh.effect;
  42492. if (!effect) {
  42493. return;
  42494. }
  42495. this._activeEffect = effect;
  42496. // Matrices
  42497. this.bindOnlyWorldMatrix(world);
  42498. // Normal Matrix
  42499. if (defines.OBJECTSPACE_NORMALMAP) {
  42500. world.toNormalMatrix(this._normalMatrix);
  42501. this.bindOnlyNormalMatrix(this._normalMatrix);
  42502. }
  42503. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42504. // Bones
  42505. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42506. if (mustRebind) {
  42507. this._uniformBuffer.bindToEffect(effect, "Material");
  42508. this.bindViewProjection(effect);
  42509. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42510. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42511. // Fresnel
  42512. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42513. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42514. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42515. }
  42516. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42517. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42518. }
  42519. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42520. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42521. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42522. }
  42523. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42524. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42525. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42526. }
  42527. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42528. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42529. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42530. }
  42531. }
  42532. // Textures
  42533. if (scene.texturesEnabled) {
  42534. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42535. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42536. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42537. if (this._diffuseTexture.hasAlpha) {
  42538. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42539. }
  42540. }
  42541. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42542. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42543. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42544. }
  42545. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42546. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42547. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42548. }
  42549. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42550. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42551. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42552. if (this._reflectionTexture.boundingBoxSize) {
  42553. var cubeTexture = this._reflectionTexture;
  42554. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42555. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42556. }
  42557. }
  42558. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42559. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42560. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42561. }
  42562. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42563. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42564. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42565. }
  42566. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42567. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42568. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42569. }
  42570. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42571. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42572. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42573. if (scene._mirroredCameraPosition) {
  42574. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42575. }
  42576. else {
  42577. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42578. }
  42579. }
  42580. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42581. var depth = 1.0;
  42582. if (!this._refractionTexture.isCube) {
  42583. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42584. if (this._refractionTexture.depth) {
  42585. depth = this._refractionTexture.depth;
  42586. }
  42587. }
  42588. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42589. }
  42590. }
  42591. // Point size
  42592. if (this.pointsCloud) {
  42593. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42594. }
  42595. if (defines.SPECULARTERM) {
  42596. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42597. }
  42598. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42599. // Diffuse
  42600. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42601. }
  42602. // Textures
  42603. if (scene.texturesEnabled) {
  42604. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42605. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42606. }
  42607. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42608. effect.setTexture("ambientSampler", this._ambientTexture);
  42609. }
  42610. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42611. effect.setTexture("opacitySampler", this._opacityTexture);
  42612. }
  42613. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42614. if (this._reflectionTexture.isCube) {
  42615. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42616. }
  42617. else {
  42618. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42619. }
  42620. }
  42621. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42622. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42623. }
  42624. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42625. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42626. }
  42627. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42628. effect.setTexture("specularSampler", this._specularTexture);
  42629. }
  42630. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42631. effect.setTexture("bumpSampler", this._bumpTexture);
  42632. }
  42633. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42634. var depth = 1.0;
  42635. if (this._refractionTexture.isCube) {
  42636. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42637. }
  42638. else {
  42639. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42640. }
  42641. }
  42642. }
  42643. // Clip plane
  42644. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42645. // Colors
  42646. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42647. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42648. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42649. }
  42650. if (mustRebind || !this.isFrozen) {
  42651. // Lights
  42652. if (scene.lightsEnabled && !this._disableLighting) {
  42653. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42654. }
  42655. // View
  42656. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42657. this.bindView(effect);
  42658. }
  42659. // Fog
  42660. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42661. // Morph targets
  42662. if (defines.NUM_MORPH_INFLUENCERS) {
  42663. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42664. }
  42665. // Log. depth
  42666. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42667. // image processing
  42668. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42669. this._imageProcessingConfiguration.bind(this._activeEffect);
  42670. }
  42671. }
  42672. this._uniformBuffer.update();
  42673. this._afterBind(mesh, this._activeEffect);
  42674. };
  42675. StandardMaterial.prototype.getAnimatables = function () {
  42676. var results = [];
  42677. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42678. results.push(this._diffuseTexture);
  42679. }
  42680. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42681. results.push(this._ambientTexture);
  42682. }
  42683. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42684. results.push(this._opacityTexture);
  42685. }
  42686. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42687. results.push(this._reflectionTexture);
  42688. }
  42689. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42690. results.push(this._emissiveTexture);
  42691. }
  42692. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42693. results.push(this._specularTexture);
  42694. }
  42695. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42696. results.push(this._bumpTexture);
  42697. }
  42698. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42699. results.push(this._lightmapTexture);
  42700. }
  42701. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42702. results.push(this._refractionTexture);
  42703. }
  42704. return results;
  42705. };
  42706. StandardMaterial.prototype.getActiveTextures = function () {
  42707. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42708. if (this._diffuseTexture) {
  42709. activeTextures.push(this._diffuseTexture);
  42710. }
  42711. if (this._ambientTexture) {
  42712. activeTextures.push(this._ambientTexture);
  42713. }
  42714. if (this._opacityTexture) {
  42715. activeTextures.push(this._opacityTexture);
  42716. }
  42717. if (this._reflectionTexture) {
  42718. activeTextures.push(this._reflectionTexture);
  42719. }
  42720. if (this._emissiveTexture) {
  42721. activeTextures.push(this._emissiveTexture);
  42722. }
  42723. if (this._specularTexture) {
  42724. activeTextures.push(this._specularTexture);
  42725. }
  42726. if (this._bumpTexture) {
  42727. activeTextures.push(this._bumpTexture);
  42728. }
  42729. if (this._lightmapTexture) {
  42730. activeTextures.push(this._lightmapTexture);
  42731. }
  42732. if (this._refractionTexture) {
  42733. activeTextures.push(this._refractionTexture);
  42734. }
  42735. return activeTextures;
  42736. };
  42737. StandardMaterial.prototype.hasTexture = function (texture) {
  42738. if (_super.prototype.hasTexture.call(this, texture)) {
  42739. return true;
  42740. }
  42741. if (this._diffuseTexture === texture) {
  42742. return true;
  42743. }
  42744. if (this._ambientTexture === texture) {
  42745. return true;
  42746. }
  42747. if (this._opacityTexture === texture) {
  42748. return true;
  42749. }
  42750. if (this._reflectionTexture === texture) {
  42751. return true;
  42752. }
  42753. if (this._emissiveTexture === texture) {
  42754. return true;
  42755. }
  42756. if (this._specularTexture === texture) {
  42757. return true;
  42758. }
  42759. if (this._bumpTexture === texture) {
  42760. return true;
  42761. }
  42762. if (this._lightmapTexture === texture) {
  42763. return true;
  42764. }
  42765. if (this._refractionTexture === texture) {
  42766. return true;
  42767. }
  42768. return false;
  42769. };
  42770. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42771. if (forceDisposeTextures) {
  42772. if (this._diffuseTexture) {
  42773. this._diffuseTexture.dispose();
  42774. }
  42775. if (this._ambientTexture) {
  42776. this._ambientTexture.dispose();
  42777. }
  42778. if (this._opacityTexture) {
  42779. this._opacityTexture.dispose();
  42780. }
  42781. if (this._reflectionTexture) {
  42782. this._reflectionTexture.dispose();
  42783. }
  42784. if (this._emissiveTexture) {
  42785. this._emissiveTexture.dispose();
  42786. }
  42787. if (this._specularTexture) {
  42788. this._specularTexture.dispose();
  42789. }
  42790. if (this._bumpTexture) {
  42791. this._bumpTexture.dispose();
  42792. }
  42793. if (this._lightmapTexture) {
  42794. this._lightmapTexture.dispose();
  42795. }
  42796. if (this._refractionTexture) {
  42797. this._refractionTexture.dispose();
  42798. }
  42799. }
  42800. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42801. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42802. }
  42803. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42804. };
  42805. StandardMaterial.prototype.clone = function (name) {
  42806. var _this = this;
  42807. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42808. result.name = name;
  42809. result.id = name;
  42810. return result;
  42811. };
  42812. StandardMaterial.prototype.serialize = function () {
  42813. return BABYLON.SerializationHelper.Serialize(this);
  42814. };
  42815. // Statics
  42816. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42817. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42818. };
  42819. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42820. get: function () {
  42821. return StandardMaterial._DiffuseTextureEnabled;
  42822. },
  42823. set: function (value) {
  42824. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42825. return;
  42826. }
  42827. StandardMaterial._DiffuseTextureEnabled = value;
  42828. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42829. },
  42830. enumerable: true,
  42831. configurable: true
  42832. });
  42833. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42834. get: function () {
  42835. return StandardMaterial._AmbientTextureEnabled;
  42836. },
  42837. set: function (value) {
  42838. if (StandardMaterial._AmbientTextureEnabled === value) {
  42839. return;
  42840. }
  42841. StandardMaterial._AmbientTextureEnabled = value;
  42842. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42843. },
  42844. enumerable: true,
  42845. configurable: true
  42846. });
  42847. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42848. get: function () {
  42849. return StandardMaterial._OpacityTextureEnabled;
  42850. },
  42851. set: function (value) {
  42852. if (StandardMaterial._OpacityTextureEnabled === value) {
  42853. return;
  42854. }
  42855. StandardMaterial._OpacityTextureEnabled = value;
  42856. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42857. },
  42858. enumerable: true,
  42859. configurable: true
  42860. });
  42861. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42862. get: function () {
  42863. return StandardMaterial._ReflectionTextureEnabled;
  42864. },
  42865. set: function (value) {
  42866. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42867. return;
  42868. }
  42869. StandardMaterial._ReflectionTextureEnabled = value;
  42870. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42871. },
  42872. enumerable: true,
  42873. configurable: true
  42874. });
  42875. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42876. get: function () {
  42877. return StandardMaterial._EmissiveTextureEnabled;
  42878. },
  42879. set: function (value) {
  42880. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42881. return;
  42882. }
  42883. StandardMaterial._EmissiveTextureEnabled = value;
  42884. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42885. },
  42886. enumerable: true,
  42887. configurable: true
  42888. });
  42889. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42890. get: function () {
  42891. return StandardMaterial._SpecularTextureEnabled;
  42892. },
  42893. set: function (value) {
  42894. if (StandardMaterial._SpecularTextureEnabled === value) {
  42895. return;
  42896. }
  42897. StandardMaterial._SpecularTextureEnabled = value;
  42898. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42899. },
  42900. enumerable: true,
  42901. configurable: true
  42902. });
  42903. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42904. get: function () {
  42905. return StandardMaterial._BumpTextureEnabled;
  42906. },
  42907. set: function (value) {
  42908. if (StandardMaterial._BumpTextureEnabled === value) {
  42909. return;
  42910. }
  42911. StandardMaterial._BumpTextureEnabled = value;
  42912. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42913. },
  42914. enumerable: true,
  42915. configurable: true
  42916. });
  42917. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42918. get: function () {
  42919. return StandardMaterial._LightmapTextureEnabled;
  42920. },
  42921. set: function (value) {
  42922. if (StandardMaterial._LightmapTextureEnabled === value) {
  42923. return;
  42924. }
  42925. StandardMaterial._LightmapTextureEnabled = value;
  42926. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42927. },
  42928. enumerable: true,
  42929. configurable: true
  42930. });
  42931. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  42932. get: function () {
  42933. return StandardMaterial._RefractionTextureEnabled;
  42934. },
  42935. set: function (value) {
  42936. if (StandardMaterial._RefractionTextureEnabled === value) {
  42937. return;
  42938. }
  42939. StandardMaterial._RefractionTextureEnabled = value;
  42940. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42941. },
  42942. enumerable: true,
  42943. configurable: true
  42944. });
  42945. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  42946. get: function () {
  42947. return StandardMaterial._ColorGradingTextureEnabled;
  42948. },
  42949. set: function (value) {
  42950. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  42951. return;
  42952. }
  42953. StandardMaterial._ColorGradingTextureEnabled = value;
  42954. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42955. },
  42956. enumerable: true,
  42957. configurable: true
  42958. });
  42959. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  42960. get: function () {
  42961. return StandardMaterial._FresnelEnabled;
  42962. },
  42963. set: function (value) {
  42964. if (StandardMaterial._FresnelEnabled === value) {
  42965. return;
  42966. }
  42967. StandardMaterial._FresnelEnabled = value;
  42968. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  42969. },
  42970. enumerable: true,
  42971. configurable: true
  42972. });
  42973. // Flags used to enable or disable a type of texture for all Standard Materials
  42974. StandardMaterial._DiffuseTextureEnabled = true;
  42975. StandardMaterial._AmbientTextureEnabled = true;
  42976. StandardMaterial._OpacityTextureEnabled = true;
  42977. StandardMaterial._ReflectionTextureEnabled = true;
  42978. StandardMaterial._EmissiveTextureEnabled = true;
  42979. StandardMaterial._SpecularTextureEnabled = true;
  42980. StandardMaterial._BumpTextureEnabled = true;
  42981. StandardMaterial._LightmapTextureEnabled = true;
  42982. StandardMaterial._RefractionTextureEnabled = true;
  42983. StandardMaterial._ColorGradingTextureEnabled = true;
  42984. StandardMaterial._FresnelEnabled = true;
  42985. __decorate([
  42986. BABYLON.serializeAsTexture("diffuseTexture")
  42987. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  42988. __decorate([
  42989. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42990. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  42991. __decorate([
  42992. BABYLON.serializeAsTexture("ambientTexture")
  42993. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  42994. __decorate([
  42995. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42996. ], StandardMaterial.prototype, "ambientTexture", void 0);
  42997. __decorate([
  42998. BABYLON.serializeAsTexture("opacityTexture")
  42999. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43000. __decorate([
  43001. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43002. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43003. __decorate([
  43004. BABYLON.serializeAsTexture("reflectionTexture")
  43005. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43006. __decorate([
  43007. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43008. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43009. __decorate([
  43010. BABYLON.serializeAsTexture("emissiveTexture")
  43011. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43012. __decorate([
  43013. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43014. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43015. __decorate([
  43016. BABYLON.serializeAsTexture("specularTexture")
  43017. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43018. __decorate([
  43019. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43020. ], StandardMaterial.prototype, "specularTexture", void 0);
  43021. __decorate([
  43022. BABYLON.serializeAsTexture("bumpTexture")
  43023. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43024. __decorate([
  43025. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43026. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43027. __decorate([
  43028. BABYLON.serializeAsTexture("lightmapTexture")
  43029. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43030. __decorate([
  43031. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43032. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43033. __decorate([
  43034. BABYLON.serializeAsTexture("refractionTexture")
  43035. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43036. __decorate([
  43037. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43038. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43039. __decorate([
  43040. BABYLON.serializeAsColor3("ambient")
  43041. ], StandardMaterial.prototype, "ambientColor", void 0);
  43042. __decorate([
  43043. BABYLON.serializeAsColor3("diffuse")
  43044. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43045. __decorate([
  43046. BABYLON.serializeAsColor3("specular")
  43047. ], StandardMaterial.prototype, "specularColor", void 0);
  43048. __decorate([
  43049. BABYLON.serializeAsColor3("emissive")
  43050. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43051. __decorate([
  43052. BABYLON.serialize()
  43053. ], StandardMaterial.prototype, "specularPower", void 0);
  43054. __decorate([
  43055. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43056. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43057. __decorate([
  43058. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43059. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43060. __decorate([
  43061. BABYLON.serialize("useEmissiveAsIllumination")
  43062. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43063. __decorate([
  43064. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43065. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43066. __decorate([
  43067. BABYLON.serialize("linkEmissiveWithDiffuse")
  43068. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43069. __decorate([
  43070. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43071. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43072. __decorate([
  43073. BABYLON.serialize("useSpecularOverAlpha")
  43074. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43075. __decorate([
  43076. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43077. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43078. __decorate([
  43079. BABYLON.serialize("useReflectionOverAlpha")
  43080. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43081. __decorate([
  43082. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43083. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43084. __decorate([
  43085. BABYLON.serialize("disableLighting")
  43086. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43087. __decorate([
  43088. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43089. ], StandardMaterial.prototype, "disableLighting", void 0);
  43090. __decorate([
  43091. BABYLON.serialize("useObjectSpaceNormalMap")
  43092. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43093. __decorate([
  43094. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43095. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43096. __decorate([
  43097. BABYLON.serialize("useParallax")
  43098. ], StandardMaterial.prototype, "_useParallax", void 0);
  43099. __decorate([
  43100. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43101. ], StandardMaterial.prototype, "useParallax", void 0);
  43102. __decorate([
  43103. BABYLON.serialize("useParallaxOcclusion")
  43104. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43105. __decorate([
  43106. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43107. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43108. __decorate([
  43109. BABYLON.serialize()
  43110. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43111. __decorate([
  43112. BABYLON.serialize("roughness")
  43113. ], StandardMaterial.prototype, "_roughness", void 0);
  43114. __decorate([
  43115. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43116. ], StandardMaterial.prototype, "roughness", void 0);
  43117. __decorate([
  43118. BABYLON.serialize()
  43119. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43120. __decorate([
  43121. BABYLON.serialize()
  43122. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43123. __decorate([
  43124. BABYLON.serialize()
  43125. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  43126. __decorate([
  43127. BABYLON.serialize("useLightmapAsShadowmap")
  43128. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43129. __decorate([
  43130. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43131. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43132. __decorate([
  43133. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  43134. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  43135. __decorate([
  43136. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43137. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  43138. __decorate([
  43139. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  43140. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  43141. __decorate([
  43142. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  43143. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  43144. __decorate([
  43145. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  43146. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  43147. __decorate([
  43148. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43149. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  43150. __decorate([
  43151. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  43152. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  43153. __decorate([
  43154. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43155. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  43156. __decorate([
  43157. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  43158. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  43159. __decorate([
  43160. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43161. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  43162. __decorate([
  43163. BABYLON.serialize("useReflectionFresnelFromSpecular")
  43164. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  43165. __decorate([
  43166. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43167. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  43168. __decorate([
  43169. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  43170. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  43171. __decorate([
  43172. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43173. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  43174. __decorate([
  43175. BABYLON.serialize("maxSimultaneousLights")
  43176. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  43177. __decorate([
  43178. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43179. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  43180. __decorate([
  43181. BABYLON.serialize("invertNormalMapX")
  43182. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  43183. __decorate([
  43184. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43185. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  43186. __decorate([
  43187. BABYLON.serialize("invertNormalMapY")
  43188. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  43189. __decorate([
  43190. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43191. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  43192. __decorate([
  43193. BABYLON.serialize("twoSidedLighting")
  43194. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  43195. __decorate([
  43196. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43197. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  43198. __decorate([
  43199. BABYLON.serialize()
  43200. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  43201. return StandardMaterial;
  43202. }(BABYLON.PushMaterial));
  43203. BABYLON.StandardMaterial = StandardMaterial;
  43204. })(BABYLON || (BABYLON = {}));
  43205. //# sourceMappingURL=babylon.standardMaterial.js.map
  43206. var BABYLON;
  43207. (function (BABYLON) {
  43208. /**
  43209. * Class representing spherical polynomial coefficients to the 3rd degree
  43210. */
  43211. var SphericalPolynomial = /** @class */ (function () {
  43212. function SphericalPolynomial() {
  43213. /**
  43214. * The x coefficients of the spherical polynomial
  43215. */
  43216. this.x = BABYLON.Vector3.Zero();
  43217. /**
  43218. * The y coefficients of the spherical polynomial
  43219. */
  43220. this.y = BABYLON.Vector3.Zero();
  43221. /**
  43222. * The z coefficients of the spherical polynomial
  43223. */
  43224. this.z = BABYLON.Vector3.Zero();
  43225. /**
  43226. * The xx coefficients of the spherical polynomial
  43227. */
  43228. this.xx = BABYLON.Vector3.Zero();
  43229. /**
  43230. * The yy coefficients of the spherical polynomial
  43231. */
  43232. this.yy = BABYLON.Vector3.Zero();
  43233. /**
  43234. * The zz coefficients of the spherical polynomial
  43235. */
  43236. this.zz = BABYLON.Vector3.Zero();
  43237. /**
  43238. * The xy coefficients of the spherical polynomial
  43239. */
  43240. this.xy = BABYLON.Vector3.Zero();
  43241. /**
  43242. * The yz coefficients of the spherical polynomial
  43243. */
  43244. this.yz = BABYLON.Vector3.Zero();
  43245. /**
  43246. * The zx coefficients of the spherical polynomial
  43247. */
  43248. this.zx = BABYLON.Vector3.Zero();
  43249. }
  43250. /**
  43251. * Adds an ambient color to the spherical polynomial
  43252. * @param color the color to add
  43253. */
  43254. SphericalPolynomial.prototype.addAmbient = function (color) {
  43255. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  43256. this.xx = this.xx.add(colorVector);
  43257. this.yy = this.yy.add(colorVector);
  43258. this.zz = this.zz.add(colorVector);
  43259. };
  43260. /**
  43261. * Scales the spherical polynomial by the given amount
  43262. * @param scale the amount to scale
  43263. */
  43264. SphericalPolynomial.prototype.scale = function (scale) {
  43265. this.x = this.x.scale(scale);
  43266. this.y = this.y.scale(scale);
  43267. this.z = this.z.scale(scale);
  43268. this.xx = this.xx.scale(scale);
  43269. this.yy = this.yy.scale(scale);
  43270. this.zz = this.zz.scale(scale);
  43271. this.yz = this.yz.scale(scale);
  43272. this.zx = this.zx.scale(scale);
  43273. this.xy = this.xy.scale(scale);
  43274. };
  43275. /**
  43276. * Gets the spherical polynomial from harmonics
  43277. * @param harmonics the spherical harmonics
  43278. * @returns the spherical polynomial
  43279. */
  43280. SphericalPolynomial.FromHarmonics = function (harmonics) {
  43281. var result = new SphericalPolynomial();
  43282. result.x = harmonics.l11.scale(1.02333);
  43283. result.y = harmonics.l1_1.scale(1.02333);
  43284. result.z = harmonics.l10.scale(1.02333);
  43285. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  43286. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  43287. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  43288. result.yz = harmonics.l2_1.scale(0.858086);
  43289. result.zx = harmonics.l21.scale(0.858086);
  43290. result.xy = harmonics.l2_2.scale(0.858086);
  43291. result.scale(1.0 / Math.PI);
  43292. return result;
  43293. };
  43294. /**
  43295. * Constructs a spherical polynomial from an array.
  43296. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  43297. * @returns the spherical polynomial
  43298. */
  43299. SphericalPolynomial.FromArray = function (data) {
  43300. var sp = new SphericalPolynomial();
  43301. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  43302. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  43303. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  43304. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  43305. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  43306. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  43307. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  43308. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  43309. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  43310. return sp;
  43311. };
  43312. return SphericalPolynomial;
  43313. }());
  43314. BABYLON.SphericalPolynomial = SphericalPolynomial;
  43315. /**
  43316. * Class representing spherical harmonics coefficients to the 3rd degree
  43317. */
  43318. var SphericalHarmonics = /** @class */ (function () {
  43319. function SphericalHarmonics() {
  43320. /**
  43321. * The l0,0 coefficients of the spherical harmonics
  43322. */
  43323. this.l00 = BABYLON.Vector3.Zero();
  43324. /**
  43325. * The l1,-1 coefficients of the spherical harmonics
  43326. */
  43327. this.l1_1 = BABYLON.Vector3.Zero();
  43328. /**
  43329. * The l1,0 coefficients of the spherical harmonics
  43330. */
  43331. this.l10 = BABYLON.Vector3.Zero();
  43332. /**
  43333. * The l1,1 coefficients of the spherical harmonics
  43334. */
  43335. this.l11 = BABYLON.Vector3.Zero();
  43336. /**
  43337. * The l2,-2 coefficients of the spherical harmonics
  43338. */
  43339. this.l2_2 = BABYLON.Vector3.Zero();
  43340. /**
  43341. * The l2,-1 coefficients of the spherical harmonics
  43342. */
  43343. this.l2_1 = BABYLON.Vector3.Zero();
  43344. /**
  43345. * The l2,0 coefficients of the spherical harmonics
  43346. */
  43347. this.l20 = BABYLON.Vector3.Zero();
  43348. /**
  43349. * The l2,1 coefficients of the spherical harmonics
  43350. */
  43351. this.l21 = BABYLON.Vector3.Zero();
  43352. /**
  43353. * The l2,2 coefficients of the spherical harmonics
  43354. */
  43355. this.lL22 = BABYLON.Vector3.Zero();
  43356. }
  43357. /**
  43358. * Adds a light to the spherical harmonics
  43359. * @param direction the direction of the light
  43360. * @param color the color of the light
  43361. * @param deltaSolidAngle the delta solid angle of the light
  43362. */
  43363. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  43364. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  43365. var c = colorVector.scale(deltaSolidAngle);
  43366. this.l00 = this.l00.add(c.scale(0.282095));
  43367. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  43368. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  43369. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  43370. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  43371. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  43372. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  43373. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  43374. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  43375. };
  43376. /**
  43377. * Scales the spherical harmonics by the given amount
  43378. * @param scale the amount to scale
  43379. */
  43380. SphericalHarmonics.prototype.scale = function (scale) {
  43381. this.l00 = this.l00.scale(scale);
  43382. this.l1_1 = this.l1_1.scale(scale);
  43383. this.l10 = this.l10.scale(scale);
  43384. this.l11 = this.l11.scale(scale);
  43385. this.l2_2 = this.l2_2.scale(scale);
  43386. this.l2_1 = this.l2_1.scale(scale);
  43387. this.l20 = this.l20.scale(scale);
  43388. this.l21 = this.l21.scale(scale);
  43389. this.lL22 = this.lL22.scale(scale);
  43390. };
  43391. /**
  43392. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  43393. *
  43394. * ```
  43395. * E_lm = A_l * L_lm
  43396. * ```
  43397. *
  43398. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  43399. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  43400. * the scaling factors are given in equation 9.
  43401. */
  43402. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  43403. // Constant (Band 0)
  43404. this.l00 = this.l00.scale(3.141593);
  43405. // Linear (Band 1)
  43406. this.l1_1 = this.l1_1.scale(2.094395);
  43407. this.l10 = this.l10.scale(2.094395);
  43408. this.l11 = this.l11.scale(2.094395);
  43409. // Quadratic (Band 2)
  43410. this.l2_2 = this.l2_2.scale(0.785398);
  43411. this.l2_1 = this.l2_1.scale(0.785398);
  43412. this.l20 = this.l20.scale(0.785398);
  43413. this.l21 = this.l21.scale(0.785398);
  43414. this.lL22 = this.lL22.scale(0.785398);
  43415. };
  43416. /**
  43417. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  43418. *
  43419. * ```
  43420. * L = (1/pi) * E * rho
  43421. * ```
  43422. *
  43423. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  43424. */
  43425. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  43426. this.scale(1.0 / Math.PI);
  43427. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  43428. // (The pixel shader must apply albedo after texture fetches, etc).
  43429. };
  43430. /**
  43431. * Gets the spherical harmonics from polynomial
  43432. * @param polynomial the spherical polynomial
  43433. * @returns the spherical harmonics
  43434. */
  43435. SphericalHarmonics.FromPolynomial = function (polynomial) {
  43436. var result = new SphericalHarmonics();
  43437. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  43438. result.l1_1 = polynomial.y.scale(0.977204);
  43439. result.l10 = polynomial.z.scale(0.977204);
  43440. result.l11 = polynomial.x.scale(0.977204);
  43441. result.l2_2 = polynomial.xy.scale(1.16538);
  43442. result.l2_1 = polynomial.yz.scale(1.16538);
  43443. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  43444. result.l21 = polynomial.zx.scale(1.16538);
  43445. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  43446. result.scale(Math.PI);
  43447. return result;
  43448. };
  43449. /**
  43450. * Constructs a spherical harmonics from an array.
  43451. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  43452. * @returns the spherical harmonics
  43453. */
  43454. SphericalHarmonics.FromArray = function (data) {
  43455. var sh = new SphericalHarmonics();
  43456. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  43457. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  43458. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  43459. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  43460. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  43461. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  43462. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  43463. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  43464. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  43465. return sh;
  43466. };
  43467. return SphericalHarmonics;
  43468. }());
  43469. BABYLON.SphericalHarmonics = SphericalHarmonics;
  43470. })(BABYLON || (BABYLON = {}));
  43471. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  43472. var BABYLON;
  43473. (function (BABYLON) {
  43474. var FileFaceOrientation = /** @class */ (function () {
  43475. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  43476. this.name = name;
  43477. this.worldAxisForNormal = worldAxisForNormal;
  43478. this.worldAxisForFileX = worldAxisForFileX;
  43479. this.worldAxisForFileY = worldAxisForFileY;
  43480. }
  43481. return FileFaceOrientation;
  43482. }());
  43483. ;
  43484. /**
  43485. * Helper class dealing with the extraction of spherical polynomial dataArray
  43486. * from a cube map.
  43487. */
  43488. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  43489. function CubeMapToSphericalPolynomialTools() {
  43490. }
  43491. /**
  43492. * Converts a texture to the according Spherical Polynomial data.
  43493. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43494. *
  43495. * @param texture The texture to extract the information from.
  43496. * @return The Spherical Polynomial data.
  43497. */
  43498. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  43499. if (!texture.isCube) {
  43500. // Only supports cube Textures currently.
  43501. return null;
  43502. }
  43503. var size = texture.getSize().width;
  43504. var right = texture.readPixels(0);
  43505. var left = texture.readPixels(1);
  43506. var up;
  43507. var down;
  43508. if (texture.isRenderTarget) {
  43509. up = texture.readPixels(3);
  43510. down = texture.readPixels(2);
  43511. }
  43512. else {
  43513. up = texture.readPixels(2);
  43514. down = texture.readPixels(3);
  43515. }
  43516. var front = texture.readPixels(4);
  43517. var back = texture.readPixels(5);
  43518. var gammaSpace = texture.gammaSpace;
  43519. // Always read as RGBA.
  43520. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  43521. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  43522. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43523. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  43524. }
  43525. var cubeInfo = {
  43526. size: size,
  43527. right: right,
  43528. left: left,
  43529. up: up,
  43530. down: down,
  43531. front: front,
  43532. back: back,
  43533. format: format,
  43534. type: type,
  43535. gammaSpace: gammaSpace,
  43536. };
  43537. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  43538. };
  43539. /**
  43540. * Converts a cubemap to the according Spherical Polynomial data.
  43541. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43542. *
  43543. * @param cubeInfo The Cube map to extract the information from.
  43544. * @return The Spherical Polynomial data.
  43545. */
  43546. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  43547. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  43548. var totalSolidAngle = 0.0;
  43549. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  43550. var du = 2.0 / cubeInfo.size;
  43551. var dv = du;
  43552. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  43553. var minUV = du * 0.5 - 1.0;
  43554. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  43555. var fileFace = this.FileFaces[faceIndex];
  43556. var dataArray = cubeInfo[fileFace.name];
  43557. var v = minUV;
  43558. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  43559. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  43560. // Because SP is still linear, so summation is fine in that basis.
  43561. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  43562. for (var y = 0; y < cubeInfo.size; y++) {
  43563. var u = minUV;
  43564. for (var x = 0; x < cubeInfo.size; x++) {
  43565. // World direction (not normalised)
  43566. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  43567. worldDirection.normalize();
  43568. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  43569. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  43570. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  43571. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  43572. // Handle Integer types.
  43573. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43574. r /= 255;
  43575. g /= 255;
  43576. b /= 255;
  43577. }
  43578. // Handle Gamma space textures.
  43579. if (cubeInfo.gammaSpace) {
  43580. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  43581. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  43582. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  43583. }
  43584. var color = new BABYLON.Color3(r, g, b);
  43585. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  43586. totalSolidAngle += deltaSolidAngle;
  43587. u += du;
  43588. }
  43589. v += dv;
  43590. }
  43591. }
  43592. // Solid angle for entire sphere is 4*pi
  43593. var sphereSolidAngle = 4.0 * Math.PI;
  43594. // Adjust the solid angle to allow for how many faces we processed.
  43595. var facesProcessed = 6.0;
  43596. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  43597. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  43598. // This is needed because the numerical integration over the cube uses a
  43599. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  43600. // and also to compensate for accumulative error due to float precision in the summation.
  43601. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  43602. sphericalHarmonics.scale(correctionFactor);
  43603. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  43604. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  43605. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  43606. };
  43607. CubeMapToSphericalPolynomialTools.FileFaces = [
  43608. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  43609. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  43610. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  43611. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  43612. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  43613. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  43614. ];
  43615. return CubeMapToSphericalPolynomialTools;
  43616. }());
  43617. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  43618. })(BABYLON || (BABYLON = {}));
  43619. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  43620. var BABYLON;
  43621. (function (BABYLON) {
  43622. /**
  43623. * Manages the defines for the PBR Material.
  43624. * @hiddenChildren
  43625. */
  43626. var PBRMaterialDefines = /** @class */ (function (_super) {
  43627. __extends(PBRMaterialDefines, _super);
  43628. /**
  43629. * Initializes the PBR Material defines.
  43630. */
  43631. function PBRMaterialDefines() {
  43632. var _this = _super.call(this) || this;
  43633. _this.PBR = true;
  43634. _this.MAINUV1 = false;
  43635. _this.MAINUV2 = false;
  43636. _this.UV1 = false;
  43637. _this.UV2 = false;
  43638. _this.ALBEDO = false;
  43639. _this.ALBEDODIRECTUV = 0;
  43640. _this.VERTEXCOLOR = false;
  43641. _this.AMBIENT = false;
  43642. _this.AMBIENTDIRECTUV = 0;
  43643. _this.AMBIENTINGRAYSCALE = false;
  43644. _this.OPACITY = false;
  43645. _this.VERTEXALPHA = false;
  43646. _this.OPACITYDIRECTUV = 0;
  43647. _this.OPACITYRGB = false;
  43648. _this.ALPHATEST = false;
  43649. _this.DEPTHPREPASS = false;
  43650. _this.ALPHABLEND = false;
  43651. _this.ALPHAFROMALBEDO = false;
  43652. _this.ALPHATESTVALUE = "0.5";
  43653. _this.SPECULAROVERALPHA = false;
  43654. _this.RADIANCEOVERALPHA = false;
  43655. _this.ALPHAFRESNEL = false;
  43656. _this.LINEARALPHAFRESNEL = false;
  43657. _this.PREMULTIPLYALPHA = false;
  43658. _this.EMISSIVE = false;
  43659. _this.EMISSIVEDIRECTUV = 0;
  43660. _this.REFLECTIVITY = false;
  43661. _this.REFLECTIVITYDIRECTUV = 0;
  43662. _this.SPECULARTERM = false;
  43663. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43664. _this.MICROSURFACEAUTOMATIC = false;
  43665. _this.LODBASEDMICROSFURACE = false;
  43666. _this.MICROSURFACEMAP = false;
  43667. _this.MICROSURFACEMAPDIRECTUV = 0;
  43668. _this.METALLICWORKFLOW = false;
  43669. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43670. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43671. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43672. _this.AOSTOREINMETALMAPRED = false;
  43673. _this.ENVIRONMENTBRDF = false;
  43674. _this.NORMAL = false;
  43675. _this.TANGENT = false;
  43676. _this.BUMP = false;
  43677. _this.BUMPDIRECTUV = 0;
  43678. _this.OBJECTSPACE_NORMALMAP = false;
  43679. _this.PARALLAX = false;
  43680. _this.PARALLAXOCCLUSION = false;
  43681. _this.NORMALXYSCALE = true;
  43682. _this.LIGHTMAP = false;
  43683. _this.LIGHTMAPDIRECTUV = 0;
  43684. _this.USELIGHTMAPASSHADOWMAP = false;
  43685. _this.GAMMALIGHTMAP = false;
  43686. _this.REFLECTION = false;
  43687. _this.REFLECTIONMAP_3D = false;
  43688. _this.REFLECTIONMAP_SPHERICAL = false;
  43689. _this.REFLECTIONMAP_PLANAR = false;
  43690. _this.REFLECTIONMAP_CUBIC = false;
  43691. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43692. _this.REFLECTIONMAP_PROJECTION = false;
  43693. _this.REFLECTIONMAP_SKYBOX = false;
  43694. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  43695. _this.REFLECTIONMAP_EXPLICIT = false;
  43696. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43697. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43698. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43699. _this.INVERTCUBICMAP = false;
  43700. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43701. _this.USESPHERICALINVERTEX = false;
  43702. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43703. _this.LODINREFLECTIONALPHA = false;
  43704. _this.GAMMAREFLECTION = false;
  43705. _this.RGBDREFLECTION = false;
  43706. _this.RADIANCEOCCLUSION = false;
  43707. _this.HORIZONOCCLUSION = false;
  43708. _this.REFRACTION = false;
  43709. _this.REFRACTIONMAP_3D = false;
  43710. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43711. _this.LODINREFRACTIONALPHA = false;
  43712. _this.GAMMAREFRACTION = false;
  43713. _this.RGBDREFRACTION = false;
  43714. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43715. _this.INSTANCES = false;
  43716. _this.NUM_BONE_INFLUENCERS = 0;
  43717. _this.BonesPerMesh = 0;
  43718. _this.NONUNIFORMSCALING = false;
  43719. _this.MORPHTARGETS = false;
  43720. _this.MORPHTARGETS_NORMAL = false;
  43721. _this.MORPHTARGETS_TANGENT = false;
  43722. _this.NUM_MORPH_INFLUENCERS = 0;
  43723. _this.IMAGEPROCESSING = false;
  43724. _this.VIGNETTE = false;
  43725. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43726. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43727. _this.TONEMAPPING = false;
  43728. _this.TONEMAPPING_ACES = false;
  43729. _this.CONTRAST = false;
  43730. _this.COLORCURVES = false;
  43731. _this.COLORGRADING = false;
  43732. _this.COLORGRADING3D = false;
  43733. _this.SAMPLER3DGREENDEPTH = false;
  43734. _this.SAMPLER3DBGRMAP = false;
  43735. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43736. _this.EXPOSURE = false;
  43737. _this.USEPHYSICALLIGHTFALLOFF = false;
  43738. _this.USEGLTFLIGHTFALLOFF = false;
  43739. _this.TWOSIDEDLIGHTING = false;
  43740. _this.SHADOWFLOAT = false;
  43741. _this.CLIPPLANE = false;
  43742. _this.CLIPPLANE2 = false;
  43743. _this.CLIPPLANE3 = false;
  43744. _this.CLIPPLANE4 = false;
  43745. _this.POINTSIZE = false;
  43746. _this.FOG = false;
  43747. _this.LOGARITHMICDEPTH = false;
  43748. _this.FORCENORMALFORWARD = false;
  43749. _this.SPECULARAA = false;
  43750. _this.UNLIT = false;
  43751. _this.rebuild();
  43752. return _this;
  43753. }
  43754. /**
  43755. * Resets the PBR Material defines.
  43756. */
  43757. PBRMaterialDefines.prototype.reset = function () {
  43758. _super.prototype.reset.call(this);
  43759. this.ALPHATESTVALUE = "0.5";
  43760. this.PBR = true;
  43761. };
  43762. return PBRMaterialDefines;
  43763. }(BABYLON.MaterialDefines));
  43764. /**
  43765. * The Physically based material base class of BJS.
  43766. *
  43767. * This offers the main features of a standard PBR material.
  43768. * For more information, please refer to the documentation :
  43769. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43770. */
  43771. var PBRBaseMaterial = /** @class */ (function (_super) {
  43772. __extends(PBRBaseMaterial, _super);
  43773. /**
  43774. * Instantiates a new PBRMaterial instance.
  43775. *
  43776. * @param name The material name
  43777. * @param scene The scene the material will be use in.
  43778. */
  43779. function PBRBaseMaterial(name, scene) {
  43780. var _this = _super.call(this, name, scene) || this;
  43781. /**
  43782. * Intensity of the direct lights e.g. the four lights available in your scene.
  43783. * This impacts both the direct diffuse and specular highlights.
  43784. */
  43785. _this._directIntensity = 1.0;
  43786. /**
  43787. * Intensity of the emissive part of the material.
  43788. * This helps controlling the emissive effect without modifying the emissive color.
  43789. */
  43790. _this._emissiveIntensity = 1.0;
  43791. /**
  43792. * Intensity of the environment e.g. how much the environment will light the object
  43793. * either through harmonics for rough material or through the refelction for shiny ones.
  43794. */
  43795. _this._environmentIntensity = 1.0;
  43796. /**
  43797. * This is a special control allowing the reduction of the specular highlights coming from the
  43798. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43799. */
  43800. _this._specularIntensity = 1.0;
  43801. /**
  43802. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43803. */
  43804. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43805. /**
  43806. * Debug Control allowing disabling the bump map on this material.
  43807. */
  43808. _this._disableBumpMap = false;
  43809. /**
  43810. * AKA Occlusion Texture Intensity in other nomenclature.
  43811. */
  43812. _this._ambientTextureStrength = 1.0;
  43813. /**
  43814. * Defines how much the AO map is occluding the analytical lights (point spot...).
  43815. * 1 means it completely occludes it
  43816. * 0 mean it has no impact
  43817. */
  43818. _this._ambientTextureImpactOnAnalyticalLights = BABYLON.PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  43819. /**
  43820. * The color of a material in ambient lighting.
  43821. */
  43822. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43823. /**
  43824. * AKA Diffuse Color in other nomenclature.
  43825. */
  43826. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43827. /**
  43828. * AKA Specular Color in other nomenclature.
  43829. */
  43830. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43831. /**
  43832. * The color applied when light is reflected from a material.
  43833. */
  43834. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43835. /**
  43836. * The color applied when light is emitted from a material.
  43837. */
  43838. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43839. /**
  43840. * AKA Glossiness in other nomenclature.
  43841. */
  43842. _this._microSurface = 0.9;
  43843. /**
  43844. * source material index of refraction (IOR)' / 'destination material IOR.
  43845. */
  43846. _this._indexOfRefraction = 0.66;
  43847. /**
  43848. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43849. */
  43850. _this._invertRefractionY = false;
  43851. /**
  43852. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43853. * Materials half opaque for instance using refraction could benefit from this control.
  43854. */
  43855. _this._linkRefractionWithTransparency = false;
  43856. /**
  43857. * Specifies that the material will use the light map as a show map.
  43858. */
  43859. _this._useLightmapAsShadowmap = false;
  43860. /**
  43861. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43862. * makes the reflect vector face the model (under horizon).
  43863. */
  43864. _this._useHorizonOcclusion = true;
  43865. /**
  43866. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43867. * too much the area relying on ambient texture to define their ambient occlusion.
  43868. */
  43869. _this._useRadianceOcclusion = true;
  43870. /**
  43871. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43872. */
  43873. _this._useAlphaFromAlbedoTexture = false;
  43874. /**
  43875. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43876. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43877. */
  43878. _this._useSpecularOverAlpha = true;
  43879. /**
  43880. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43881. */
  43882. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43883. /**
  43884. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43885. */
  43886. _this._useRoughnessFromMetallicTextureAlpha = true;
  43887. /**
  43888. * Specifies if the metallic texture contains the roughness information in its green channel.
  43889. */
  43890. _this._useRoughnessFromMetallicTextureGreen = false;
  43891. /**
  43892. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43893. */
  43894. _this._useMetallnessFromMetallicTextureBlue = false;
  43895. /**
  43896. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43897. */
  43898. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43899. /**
  43900. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43901. */
  43902. _this._useAmbientInGrayScale = false;
  43903. /**
  43904. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43905. * The material will try to infer what glossiness each pixel should be.
  43906. */
  43907. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43908. /**
  43909. * Defines the falloff type used in this material.
  43910. * It by default is Physical.
  43911. */
  43912. _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  43913. /**
  43914. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43915. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43916. */
  43917. _this._useRadianceOverAlpha = true;
  43918. /**
  43919. * Allows using an object space normal map (instead of tangent space).
  43920. */
  43921. _this._useObjectSpaceNormalMap = false;
  43922. /**
  43923. * Allows using the bump map in parallax mode.
  43924. */
  43925. _this._useParallax = false;
  43926. /**
  43927. * Allows using the bump map in parallax occlusion mode.
  43928. */
  43929. _this._useParallaxOcclusion = false;
  43930. /**
  43931. * Controls the scale bias of the parallax mode.
  43932. */
  43933. _this._parallaxScaleBias = 0.05;
  43934. /**
  43935. * If sets to true, disables all the lights affecting the material.
  43936. */
  43937. _this._disableLighting = false;
  43938. /**
  43939. * Number of Simultaneous lights allowed on the material.
  43940. */
  43941. _this._maxSimultaneousLights = 4;
  43942. /**
  43943. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43944. */
  43945. _this._invertNormalMapX = false;
  43946. /**
  43947. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43948. */
  43949. _this._invertNormalMapY = false;
  43950. /**
  43951. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43952. */
  43953. _this._twoSidedLighting = false;
  43954. /**
  43955. * Defines the alpha limits in alpha test mode.
  43956. */
  43957. _this._alphaCutOff = 0.4;
  43958. /**
  43959. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43960. */
  43961. _this._forceAlphaTest = false;
  43962. /**
  43963. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43964. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43965. */
  43966. _this._useAlphaFresnel = false;
  43967. /**
  43968. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43969. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43970. */
  43971. _this._useLinearAlphaFresnel = false;
  43972. /**
  43973. * The transparency mode of the material.
  43974. */
  43975. _this._transparencyMode = null;
  43976. /**
  43977. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43978. * from cos thetav and roughness:
  43979. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43980. */
  43981. _this._environmentBRDFTexture = null;
  43982. /**
  43983. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43984. */
  43985. _this._forceIrradianceInFragment = false;
  43986. /**
  43987. * Force normal to face away from face.
  43988. */
  43989. _this._forceNormalForward = false;
  43990. /**
  43991. * Enables specular anti aliasing in the PBR shader.
  43992. * It will both interacts on the Geometry for analytical and IBL lighting.
  43993. * It also prefilter the roughness map based on the bump values.
  43994. */
  43995. _this._enableSpecularAntiAliasing = false;
  43996. /**
  43997. * Stores the available render targets.
  43998. */
  43999. _this._renderTargets = new BABYLON.SmartArray(16);
  44000. /**
  44001. * Sets the global ambient color for the material used in lighting calculations.
  44002. */
  44003. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44004. /**
  44005. * If set to true, no lighting calculations will be applied.
  44006. */
  44007. _this._unlit = false;
  44008. // Setup the default processing configuration to the scene.
  44009. _this._attachImageProcessingConfiguration(null);
  44010. _this.getRenderTargetTextures = function () {
  44011. _this._renderTargets.reset();
  44012. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44013. _this._renderTargets.push(_this._reflectionTexture);
  44014. }
  44015. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44016. _this._renderTargets.push(_this._refractionTexture);
  44017. }
  44018. return _this._renderTargets;
  44019. };
  44020. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44021. return _this;
  44022. }
  44023. /**
  44024. * Attaches a new image processing configuration to the PBR Material.
  44025. * @param configuration
  44026. */
  44027. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44028. var _this = this;
  44029. if (configuration === this._imageProcessingConfiguration) {
  44030. return;
  44031. }
  44032. // Detaches observer.
  44033. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44034. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44035. }
  44036. // Pick the scene configuration if needed.
  44037. if (!configuration) {
  44038. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44039. }
  44040. else {
  44041. this._imageProcessingConfiguration = configuration;
  44042. }
  44043. // Attaches observer.
  44044. if (this._imageProcessingConfiguration) {
  44045. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44046. _this._markAllSubMeshesAsImageProcessingDirty();
  44047. });
  44048. }
  44049. };
  44050. /**
  44051. * Gets the name of the material class.
  44052. */
  44053. PBRBaseMaterial.prototype.getClassName = function () {
  44054. return "PBRBaseMaterial";
  44055. };
  44056. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  44057. /**
  44058. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44059. */
  44060. get: function () {
  44061. return this._useLogarithmicDepth;
  44062. },
  44063. /**
  44064. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44065. */
  44066. set: function (value) {
  44067. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44068. },
  44069. enumerable: true,
  44070. configurable: true
  44071. });
  44072. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  44073. /**
  44074. * Gets the current transparency mode.
  44075. */
  44076. get: function () {
  44077. return this._transparencyMode;
  44078. },
  44079. /**
  44080. * Sets the transparency mode of the material.
  44081. *
  44082. * | Value | Type | Description |
  44083. * | ----- | ----------------------------------- | ----------- |
  44084. * | 0 | OPAQUE | |
  44085. * | 1 | ALPHATEST | |
  44086. * | 2 | ALPHABLEND | |
  44087. * | 3 | ALPHATESTANDBLEND | |
  44088. *
  44089. */
  44090. set: function (value) {
  44091. if (this._transparencyMode === value) {
  44092. return;
  44093. }
  44094. this._transparencyMode = value;
  44095. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  44096. this._markAllSubMeshesAsTexturesAndMiscDirty();
  44097. },
  44098. enumerable: true,
  44099. configurable: true
  44100. });
  44101. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  44102. /**
  44103. * Returns true if alpha blending should be disabled.
  44104. */
  44105. get: function () {
  44106. return (this._linkRefractionWithTransparency ||
  44107. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  44108. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44109. },
  44110. enumerable: true,
  44111. configurable: true
  44112. });
  44113. /**
  44114. * Specifies whether or not this material should be rendered in alpha blend mode.
  44115. */
  44116. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  44117. if (this._disableAlphaBlending) {
  44118. return false;
  44119. }
  44120. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  44121. };
  44122. /**
  44123. * Specifies if the mesh will require alpha blending.
  44124. * @param mesh - BJS mesh.
  44125. */
  44126. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  44127. if (this._disableAlphaBlending) {
  44128. return false;
  44129. }
  44130. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  44131. };
  44132. /**
  44133. * Specifies whether or not this material should be rendered in alpha test mode.
  44134. */
  44135. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  44136. if (this._forceAlphaTest) {
  44137. return true;
  44138. }
  44139. if (this._linkRefractionWithTransparency) {
  44140. return false;
  44141. }
  44142. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44143. };
  44144. /**
  44145. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  44146. */
  44147. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44148. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  44149. };
  44150. /**
  44151. * Gets the texture used for the alpha test.
  44152. */
  44153. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  44154. return this._albedoTexture;
  44155. };
  44156. /**
  44157. * Specifies that the submesh is ready to be used.
  44158. * @param mesh - BJS mesh.
  44159. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  44160. * @param useInstances - Specifies that instances should be used.
  44161. * @returns - boolean indicating that the submesh is ready or not.
  44162. */
  44163. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44164. if (subMesh.effect && this.isFrozen) {
  44165. if (this._wasPreviouslyReady) {
  44166. return true;
  44167. }
  44168. }
  44169. if (!subMesh._materialDefines) {
  44170. subMesh._materialDefines = new PBRMaterialDefines();
  44171. }
  44172. var defines = subMesh._materialDefines;
  44173. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44174. if (defines._renderId === this.getScene().getRenderId()) {
  44175. return true;
  44176. }
  44177. }
  44178. var scene = this.getScene();
  44179. var engine = scene.getEngine();
  44180. if (defines._areTexturesDirty) {
  44181. if (scene.texturesEnabled) {
  44182. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44183. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  44184. return false;
  44185. }
  44186. }
  44187. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44188. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44189. return false;
  44190. }
  44191. }
  44192. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44193. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44194. return false;
  44195. }
  44196. }
  44197. var reflectionTexture = this._getReflectionTexture();
  44198. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44199. if (!reflectionTexture.isReadyOrNotBlocking()) {
  44200. return false;
  44201. }
  44202. }
  44203. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44204. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44205. return false;
  44206. }
  44207. }
  44208. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44209. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44210. return false;
  44211. }
  44212. }
  44213. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44214. if (this._metallicTexture) {
  44215. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  44216. return false;
  44217. }
  44218. }
  44219. else if (this._reflectivityTexture) {
  44220. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  44221. return false;
  44222. }
  44223. }
  44224. if (this._microSurfaceTexture) {
  44225. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  44226. return false;
  44227. }
  44228. }
  44229. }
  44230. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44231. // Bump texture cannot be not blocking.
  44232. if (!this._bumpTexture.isReady()) {
  44233. return false;
  44234. }
  44235. }
  44236. var refractionTexture = this._getRefractionTexture();
  44237. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44238. if (!refractionTexture.isReadyOrNotBlocking()) {
  44239. return false;
  44240. }
  44241. }
  44242. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44243. // This is blocking.
  44244. if (!this._environmentBRDFTexture.isReady()) {
  44245. return false;
  44246. }
  44247. }
  44248. }
  44249. }
  44250. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44251. if (!this._imageProcessingConfiguration.isReady()) {
  44252. return false;
  44253. }
  44254. }
  44255. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44256. mesh.createNormals(true);
  44257. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  44258. }
  44259. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  44260. if (effect) {
  44261. scene.resetCachedMaterial();
  44262. subMesh.setEffect(effect, defines);
  44263. this.buildUniformLayout();
  44264. }
  44265. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44266. return false;
  44267. }
  44268. defines._renderId = scene.getRenderId();
  44269. this._wasPreviouslyReady = true;
  44270. return true;
  44271. };
  44272. /**
  44273. * Specifies if the material uses metallic roughness workflow.
  44274. * @returns boolean specifiying if the material uses metallic roughness workflow.
  44275. */
  44276. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  44277. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44278. return true;
  44279. }
  44280. return false;
  44281. };
  44282. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44283. if (onCompiled === void 0) { onCompiled = null; }
  44284. if (onError === void 0) { onError = null; }
  44285. if (useInstances === void 0) { useInstances = null; }
  44286. if (useClipPlane === void 0) { useClipPlane = null; }
  44287. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44288. if (!defines.isDirty) {
  44289. return null;
  44290. }
  44291. defines.markAsProcessed();
  44292. var scene = this.getScene();
  44293. var engine = scene.getEngine();
  44294. // Fallbacks
  44295. var fallbacks = new BABYLON.EffectFallbacks();
  44296. var fallbackRank = 0;
  44297. if (defines.USESPHERICALINVERTEX) {
  44298. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44299. }
  44300. if (defines.FOG) {
  44301. fallbacks.addFallback(fallbackRank, "FOG");
  44302. }
  44303. if (defines.SPECULARAA) {
  44304. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  44305. }
  44306. if (defines.POINTSIZE) {
  44307. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44308. }
  44309. if (defines.LOGARITHMICDEPTH) {
  44310. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44311. }
  44312. if (defines.PARALLAX) {
  44313. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44314. }
  44315. if (defines.PARALLAXOCCLUSION) {
  44316. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44317. }
  44318. if (defines.ENVIRONMENTBRDF) {
  44319. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44320. }
  44321. if (defines.TANGENT) {
  44322. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44323. }
  44324. if (defines.BUMP) {
  44325. fallbacks.addFallback(fallbackRank++, "BUMP");
  44326. }
  44327. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44328. if (defines.SPECULARTERM) {
  44329. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44330. }
  44331. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44332. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44333. }
  44334. if (defines.LIGHTMAP) {
  44335. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44336. }
  44337. if (defines.NORMAL) {
  44338. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44339. }
  44340. if (defines.AMBIENT) {
  44341. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44342. }
  44343. if (defines.EMISSIVE) {
  44344. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44345. }
  44346. if (defines.VERTEXCOLOR) {
  44347. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44348. }
  44349. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44350. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44351. }
  44352. if (defines.MORPHTARGETS) {
  44353. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44354. }
  44355. //Attributes
  44356. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44357. if (defines.NORMAL) {
  44358. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44359. }
  44360. if (defines.TANGENT) {
  44361. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44362. }
  44363. if (defines.UV1) {
  44364. attribs.push(BABYLON.VertexBuffer.UVKind);
  44365. }
  44366. if (defines.UV2) {
  44367. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44368. }
  44369. if (defines.VERTEXCOLOR) {
  44370. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44371. }
  44372. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44373. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44374. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44375. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44376. "vFogInfos", "vFogColor", "pointSize",
  44377. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44378. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44379. "mBones",
  44380. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44381. "vLightingIntensity",
  44382. "logarithmicDepthConstant",
  44383. "vSphericalX", "vSphericalY", "vSphericalZ",
  44384. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44385. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44386. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44387. "vTangentSpaceParams"
  44388. ];
  44389. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44390. "bumpSampler", "lightmapSampler", "opacitySampler",
  44391. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44392. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44393. "microSurfaceSampler", "environmentBrdfSampler"];
  44394. var uniformBuffers = ["Material", "Scene"];
  44395. if (BABYLON.ImageProcessingConfiguration) {
  44396. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44397. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44398. }
  44399. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44400. uniformsNames: uniforms,
  44401. uniformBuffersNames: uniformBuffers,
  44402. samplers: samplers,
  44403. defines: defines,
  44404. maxSimultaneousLights: this._maxSimultaneousLights
  44405. });
  44406. var join = defines.toString();
  44407. return engine.createEffect("pbr", {
  44408. attributes: attribs,
  44409. uniformsNames: uniforms,
  44410. uniformBuffersNames: uniformBuffers,
  44411. samplers: samplers,
  44412. defines: join,
  44413. fallbacks: fallbacks,
  44414. onCompiled: onCompiled,
  44415. onError: onError,
  44416. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44417. }, engine);
  44418. };
  44419. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44420. if (useInstances === void 0) { useInstances = null; }
  44421. if (useClipPlane === void 0) { useClipPlane = null; }
  44422. var scene = this.getScene();
  44423. var engine = scene.getEngine();
  44424. // Lights
  44425. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44426. defines._needNormals = true;
  44427. // Textures
  44428. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44429. if (defines._areTexturesDirty) {
  44430. defines._needUVs = false;
  44431. if (scene.texturesEnabled) {
  44432. if (scene.getEngine().getCaps().textureLOD) {
  44433. defines.LODBASEDMICROSFURACE = true;
  44434. }
  44435. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44436. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44437. }
  44438. else {
  44439. defines.ALBEDO = false;
  44440. }
  44441. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44442. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44443. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44444. }
  44445. else {
  44446. defines.AMBIENT = false;
  44447. }
  44448. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44449. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44450. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44451. }
  44452. else {
  44453. defines.OPACITY = false;
  44454. }
  44455. var reflectionTexture = this._getReflectionTexture();
  44456. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44457. defines.REFLECTION = true;
  44458. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44459. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  44460. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44461. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44462. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44463. defines.INVERTCUBICMAP = true;
  44464. }
  44465. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44466. switch (reflectionTexture.coordinatesMode) {
  44467. case BABYLON.Texture.EXPLICIT_MODE:
  44468. defines.REFLECTIONMAP_EXPLICIT = true;
  44469. break;
  44470. case BABYLON.Texture.PLANAR_MODE:
  44471. defines.REFLECTIONMAP_PLANAR = true;
  44472. break;
  44473. case BABYLON.Texture.PROJECTION_MODE:
  44474. defines.REFLECTIONMAP_PROJECTION = true;
  44475. break;
  44476. case BABYLON.Texture.SKYBOX_MODE:
  44477. defines.REFLECTIONMAP_SKYBOX = true;
  44478. break;
  44479. case BABYLON.Texture.SPHERICAL_MODE:
  44480. defines.REFLECTIONMAP_SPHERICAL = true;
  44481. break;
  44482. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44483. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44484. break;
  44485. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44486. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44487. break;
  44488. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44489. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44490. break;
  44491. case BABYLON.Texture.CUBIC_MODE:
  44492. case BABYLON.Texture.INVCUBIC_MODE:
  44493. default:
  44494. defines.REFLECTIONMAP_CUBIC = true;
  44495. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44496. break;
  44497. }
  44498. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44499. if (reflectionTexture.sphericalPolynomial) {
  44500. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44501. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44502. defines.USESPHERICALINVERTEX = false;
  44503. }
  44504. else {
  44505. defines.USESPHERICALINVERTEX = true;
  44506. }
  44507. }
  44508. }
  44509. else {
  44510. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  44511. }
  44512. }
  44513. else {
  44514. defines.REFLECTION = false;
  44515. defines.REFLECTIONMAP_3D = false;
  44516. defines.REFLECTIONMAP_SPHERICAL = false;
  44517. defines.REFLECTIONMAP_PLANAR = false;
  44518. defines.REFLECTIONMAP_CUBIC = false;
  44519. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44520. defines.REFLECTIONMAP_PROJECTION = false;
  44521. defines.REFLECTIONMAP_SKYBOX = false;
  44522. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  44523. defines.REFLECTIONMAP_EXPLICIT = false;
  44524. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44525. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44526. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44527. defines.INVERTCUBICMAP = false;
  44528. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44529. defines.USESPHERICALINVERTEX = false;
  44530. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44531. defines.LODINREFLECTIONALPHA = false;
  44532. defines.GAMMAREFLECTION = false;
  44533. defines.RGBDREFLECTION = false;
  44534. }
  44535. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44536. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44537. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44538. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44539. }
  44540. else {
  44541. defines.LIGHTMAP = false;
  44542. }
  44543. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44544. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44545. }
  44546. else {
  44547. defines.EMISSIVE = false;
  44548. }
  44549. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44550. if (this._metallicTexture) {
  44551. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44552. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44553. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44554. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44555. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44556. }
  44557. else if (this._reflectivityTexture) {
  44558. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44559. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44560. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44561. }
  44562. else {
  44563. defines.REFLECTIVITY = false;
  44564. }
  44565. if (this._microSurfaceTexture) {
  44566. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44567. }
  44568. else {
  44569. defines.MICROSURFACEMAP = false;
  44570. }
  44571. }
  44572. else {
  44573. defines.REFLECTIVITY = false;
  44574. defines.MICROSURFACEMAP = false;
  44575. }
  44576. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44577. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44578. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44579. defines.PARALLAX = true;
  44580. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44581. }
  44582. else {
  44583. defines.PARALLAX = false;
  44584. }
  44585. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44586. }
  44587. else {
  44588. defines.BUMP = false;
  44589. }
  44590. var refractionTexture = this._getRefractionTexture();
  44591. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44592. defines.REFRACTION = true;
  44593. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44594. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44595. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44596. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44597. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44598. if (this._linkRefractionWithTransparency) {
  44599. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44600. }
  44601. }
  44602. else {
  44603. defines.REFRACTION = false;
  44604. }
  44605. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44606. defines.ENVIRONMENTBRDF = true;
  44607. }
  44608. else {
  44609. defines.ENVIRONMENTBRDF = false;
  44610. }
  44611. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44612. defines.ALPHAFROMALBEDO = true;
  44613. }
  44614. else {
  44615. defines.ALPHAFROMALBEDO = false;
  44616. }
  44617. }
  44618. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44619. if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
  44620. defines.USEPHYSICALLIGHTFALLOFF = false;
  44621. defines.USEGLTFLIGHTFALLOFF = false;
  44622. }
  44623. else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
  44624. defines.USEPHYSICALLIGHTFALLOFF = false;
  44625. defines.USEGLTFLIGHTFALLOFF = true;
  44626. }
  44627. else {
  44628. defines.USEPHYSICALLIGHTFALLOFF = true;
  44629. defines.USEGLTFLIGHTFALLOFF = false;
  44630. }
  44631. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44632. if (!this.backFaceCulling && this._twoSidedLighting) {
  44633. defines.TWOSIDEDLIGHTING = true;
  44634. }
  44635. else {
  44636. defines.TWOSIDEDLIGHTING = false;
  44637. }
  44638. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44639. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44640. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44641. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44642. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44643. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44644. }
  44645. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44646. this._imageProcessingConfiguration.prepareDefines(defines);
  44647. }
  44648. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44649. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44650. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44651. // Misc.
  44652. if (defines._areMiscDirty) {
  44653. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44654. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44655. }
  44656. // Values that need to be evaluated on every frame
  44657. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44658. // Attribs
  44659. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44660. };
  44661. /**
  44662. * Force shader compilation
  44663. */
  44664. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44665. var _this = this;
  44666. var localOptions = __assign({ clipPlane: false }, options);
  44667. var defines = new PBRMaterialDefines();
  44668. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44669. if (effect.isReady()) {
  44670. if (onCompiled) {
  44671. onCompiled(this);
  44672. }
  44673. }
  44674. else {
  44675. effect.onCompileObservable.add(function () {
  44676. if (onCompiled) {
  44677. onCompiled(_this);
  44678. }
  44679. });
  44680. }
  44681. };
  44682. /**
  44683. * Initializes the uniform buffer layout for the shader.
  44684. */
  44685. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44686. // Order is important !
  44687. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44688. this._uniformBuffer.addUniform("vAmbientInfos", 4);
  44689. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44690. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44691. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44692. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44693. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44694. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44695. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44696. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44697. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44698. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44699. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44700. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44701. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44702. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44703. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44704. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44705. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44706. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44707. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44708. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44709. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44710. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44711. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44712. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44713. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44714. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44715. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44716. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44717. this._uniformBuffer.addUniform("pointSize", 1);
  44718. this._uniformBuffer.create();
  44719. };
  44720. /**
  44721. * Unbinds the textures.
  44722. */
  44723. PBRBaseMaterial.prototype.unbind = function () {
  44724. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44725. this._uniformBuffer.setTexture("reflectionSampler", null);
  44726. }
  44727. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44728. this._uniformBuffer.setTexture("refractionSampler", null);
  44729. }
  44730. _super.prototype.unbind.call(this);
  44731. };
  44732. /**
  44733. * Binds the submesh data.
  44734. * @param world - The world matrix.
  44735. * @param mesh - The BJS mesh.
  44736. * @param subMesh - A submesh of the BJS mesh.
  44737. */
  44738. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44739. var scene = this.getScene();
  44740. var defines = subMesh._materialDefines;
  44741. if (!defines) {
  44742. return;
  44743. }
  44744. var effect = subMesh.effect;
  44745. if (!effect) {
  44746. return;
  44747. }
  44748. this._activeEffect = effect;
  44749. // Matrices
  44750. this.bindOnlyWorldMatrix(world);
  44751. // Normal Matrix
  44752. if (defines.OBJECTSPACE_NORMALMAP) {
  44753. world.toNormalMatrix(this._normalMatrix);
  44754. this.bindOnlyNormalMatrix(this._normalMatrix);
  44755. }
  44756. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44757. // Bones
  44758. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44759. var reflectionTexture = null;
  44760. if (mustRebind) {
  44761. this._uniformBuffer.bindToEffect(effect, "Material");
  44762. this.bindViewProjection(effect);
  44763. reflectionTexture = this._getReflectionTexture();
  44764. var refractionTexture = this._getRefractionTexture();
  44765. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44766. // Texture uniforms
  44767. if (scene.texturesEnabled) {
  44768. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44769. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44770. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44771. }
  44772. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44773. this._uniformBuffer.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);
  44774. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44775. }
  44776. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44777. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44778. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44779. }
  44780. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44781. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44782. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44783. if (reflectionTexture.boundingBoxSize) {
  44784. var cubeTexture = reflectionTexture;
  44785. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44786. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44787. }
  44788. var polynomials = reflectionTexture.sphericalPolynomial;
  44789. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44790. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44791. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44792. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44793. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44794. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44795. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44796. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44797. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44798. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44799. }
  44800. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44801. }
  44802. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44803. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44804. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44805. }
  44806. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44807. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44808. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44809. }
  44810. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44811. if (this._metallicTexture) {
  44812. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44813. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44814. }
  44815. else if (this._reflectivityTexture) {
  44816. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44817. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44818. }
  44819. if (this._microSurfaceTexture) {
  44820. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44821. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44822. }
  44823. }
  44824. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44825. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44826. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44827. if (scene._mirroredCameraPosition) {
  44828. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44829. }
  44830. else {
  44831. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44832. }
  44833. }
  44834. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44835. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44836. var depth = 1.0;
  44837. if (!refractionTexture.isCube) {
  44838. if (refractionTexture.depth) {
  44839. depth = refractionTexture.depth;
  44840. }
  44841. }
  44842. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44843. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44844. }
  44845. }
  44846. // Point size
  44847. if (this.pointsCloud) {
  44848. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44849. }
  44850. // Colors
  44851. if (defines.METALLICWORKFLOW) {
  44852. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44853. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44854. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44855. }
  44856. else {
  44857. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44858. }
  44859. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44860. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44861. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44862. // Misc
  44863. this._lightingInfos.x = this._directIntensity;
  44864. this._lightingInfos.y = this._emissiveIntensity;
  44865. this._lightingInfos.z = this._environmentIntensity;
  44866. this._lightingInfos.w = this._specularIntensity;
  44867. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44868. }
  44869. // Textures
  44870. if (scene.texturesEnabled) {
  44871. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44872. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44873. }
  44874. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44875. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44876. }
  44877. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44878. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44879. }
  44880. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44881. if (defines.LODBASEDMICROSFURACE) {
  44882. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44883. }
  44884. else {
  44885. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44886. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44887. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44888. }
  44889. }
  44890. if (defines.ENVIRONMENTBRDF) {
  44891. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44892. }
  44893. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44894. if (defines.LODBASEDMICROSFURACE) {
  44895. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44896. }
  44897. else {
  44898. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44899. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44900. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44901. }
  44902. }
  44903. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44904. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44905. }
  44906. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44907. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44908. }
  44909. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44910. if (this._metallicTexture) {
  44911. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44912. }
  44913. else if (this._reflectivityTexture) {
  44914. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44915. }
  44916. if (this._microSurfaceTexture) {
  44917. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44918. }
  44919. }
  44920. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44921. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44922. }
  44923. }
  44924. // Clip plane
  44925. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44926. // Colors
  44927. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44928. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44929. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44930. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44931. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44932. }
  44933. if (mustRebind || !this.isFrozen) {
  44934. // Lights
  44935. if (scene.lightsEnabled && !this._disableLighting) {
  44936. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD);
  44937. }
  44938. // View
  44939. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44940. this.bindView(effect);
  44941. }
  44942. // Fog
  44943. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44944. // Morph targets
  44945. if (defines.NUM_MORPH_INFLUENCERS) {
  44946. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44947. }
  44948. // image processing
  44949. this._imageProcessingConfiguration.bind(this._activeEffect);
  44950. // Log. depth
  44951. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44952. }
  44953. this._uniformBuffer.update();
  44954. this._afterBind(mesh, this._activeEffect);
  44955. };
  44956. /**
  44957. * Returns the animatable textures.
  44958. * @returns - Array of animatable textures.
  44959. */
  44960. PBRBaseMaterial.prototype.getAnimatables = function () {
  44961. var results = [];
  44962. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44963. results.push(this._albedoTexture);
  44964. }
  44965. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44966. results.push(this._ambientTexture);
  44967. }
  44968. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44969. results.push(this._opacityTexture);
  44970. }
  44971. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44972. results.push(this._reflectionTexture);
  44973. }
  44974. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44975. results.push(this._emissiveTexture);
  44976. }
  44977. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44978. results.push(this._metallicTexture);
  44979. }
  44980. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44981. results.push(this._reflectivityTexture);
  44982. }
  44983. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44984. results.push(this._bumpTexture);
  44985. }
  44986. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44987. results.push(this._lightmapTexture);
  44988. }
  44989. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44990. results.push(this._refractionTexture);
  44991. }
  44992. return results;
  44993. };
  44994. /**
  44995. * Returns the texture used for reflections.
  44996. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44997. */
  44998. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44999. if (this._reflectionTexture) {
  45000. return this._reflectionTexture;
  45001. }
  45002. return this.getScene().environmentTexture;
  45003. };
  45004. /**
  45005. * Returns the texture used for refraction or null if none is used.
  45006. * @returns - Refection texture if present. If no refraction texture and refraction
  45007. * is linked with transparency, returns environment texture. Otherwise, returns null.
  45008. */
  45009. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  45010. if (this._refractionTexture) {
  45011. return this._refractionTexture;
  45012. }
  45013. if (this._linkRefractionWithTransparency) {
  45014. return this.getScene().environmentTexture;
  45015. }
  45016. return null;
  45017. };
  45018. /**
  45019. * Disposes the resources of the material.
  45020. * @param forceDisposeEffect - Forces the disposal of effects.
  45021. * @param forceDisposeTextures - Forces the disposal of all textures.
  45022. */
  45023. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45024. if (forceDisposeTextures) {
  45025. if (this._albedoTexture) {
  45026. this._albedoTexture.dispose();
  45027. }
  45028. if (this._ambientTexture) {
  45029. this._ambientTexture.dispose();
  45030. }
  45031. if (this._opacityTexture) {
  45032. this._opacityTexture.dispose();
  45033. }
  45034. if (this._reflectionTexture) {
  45035. this._reflectionTexture.dispose();
  45036. }
  45037. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  45038. this._environmentBRDFTexture.dispose();
  45039. }
  45040. if (this._emissiveTexture) {
  45041. this._emissiveTexture.dispose();
  45042. }
  45043. if (this._metallicTexture) {
  45044. this._metallicTexture.dispose();
  45045. }
  45046. if (this._reflectivityTexture) {
  45047. this._reflectivityTexture.dispose();
  45048. }
  45049. if (this._bumpTexture) {
  45050. this._bumpTexture.dispose();
  45051. }
  45052. if (this._lightmapTexture) {
  45053. this._lightmapTexture.dispose();
  45054. }
  45055. if (this._refractionTexture) {
  45056. this._refractionTexture.dispose();
  45057. }
  45058. }
  45059. this._renderTargets.dispose();
  45060. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45061. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45062. }
  45063. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45064. };
  45065. /**
  45066. * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
  45067. */
  45068. PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
  45069. /**
  45070. * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
  45071. * to enhance interoperability with other engines.
  45072. */
  45073. PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
  45074. /**
  45075. * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
  45076. * to enhance interoperability with other materials.
  45077. */
  45078. PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
  45079. /**
  45080. * Stores the reflectivity values based on metallic roughness workflow.
  45081. */
  45082. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  45083. __decorate([
  45084. BABYLON.serializeAsImageProcessingConfiguration()
  45085. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  45086. __decorate([
  45087. BABYLON.serialize()
  45088. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  45089. __decorate([
  45090. BABYLON.serialize()
  45091. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45092. return PBRBaseMaterial;
  45093. }(BABYLON.PushMaterial));
  45094. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  45095. })(BABYLON || (BABYLON = {}));
  45096. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  45097. var BABYLON;
  45098. (function (BABYLON) {
  45099. /**
  45100. * The Physically based simple base material of BJS.
  45101. *
  45102. * This enables better naming and convention enforcements on top of the pbrMaterial.
  45103. * It is used as the base class for both the specGloss and metalRough conventions.
  45104. */
  45105. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  45106. __extends(PBRBaseSimpleMaterial, _super);
  45107. /**
  45108. * Instantiates a new PBRMaterial instance.
  45109. *
  45110. * @param name The material name
  45111. * @param scene The scene the material will be use in.
  45112. */
  45113. function PBRBaseSimpleMaterial(name, scene) {
  45114. var _this = _super.call(this, name, scene) || this;
  45115. /**
  45116. * Number of Simultaneous lights allowed on the material.
  45117. */
  45118. _this.maxSimultaneousLights = 4;
  45119. /**
  45120. * If sets to true, disables all the lights affecting the material.
  45121. */
  45122. _this.disableLighting = false;
  45123. /**
  45124. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45125. */
  45126. _this.invertNormalMapX = false;
  45127. /**
  45128. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45129. */
  45130. _this.invertNormalMapY = false;
  45131. /**
  45132. * Emissivie color used to self-illuminate the model.
  45133. */
  45134. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45135. /**
  45136. * Occlusion Channel Strenght.
  45137. */
  45138. _this.occlusionStrength = 1.0;
  45139. _this.useLightmapAsShadowmap = false;
  45140. _this._useAlphaFromAlbedoTexture = true;
  45141. _this._useAmbientInGrayScale = true;
  45142. return _this;
  45143. }
  45144. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  45145. /**
  45146. * Gets the current double sided mode.
  45147. */
  45148. get: function () {
  45149. return this._twoSidedLighting;
  45150. },
  45151. /**
  45152. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45153. */
  45154. set: function (value) {
  45155. if (this._twoSidedLighting === value) {
  45156. return;
  45157. }
  45158. this._twoSidedLighting = value;
  45159. this.backFaceCulling = !value;
  45160. this._markAllSubMeshesAsTexturesDirty();
  45161. },
  45162. enumerable: true,
  45163. configurable: true
  45164. });
  45165. /**
  45166. * Return the active textures of the material.
  45167. */
  45168. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  45169. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45170. if (this.environmentTexture) {
  45171. activeTextures.push(this.environmentTexture);
  45172. }
  45173. if (this.normalTexture) {
  45174. activeTextures.push(this.normalTexture);
  45175. }
  45176. if (this.emissiveTexture) {
  45177. activeTextures.push(this.emissiveTexture);
  45178. }
  45179. if (this.occlusionTexture) {
  45180. activeTextures.push(this.occlusionTexture);
  45181. }
  45182. if (this.lightmapTexture) {
  45183. activeTextures.push(this.lightmapTexture);
  45184. }
  45185. return activeTextures;
  45186. };
  45187. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  45188. if (_super.prototype.hasTexture.call(this, texture)) {
  45189. return true;
  45190. }
  45191. if (this.lightmapTexture === texture) {
  45192. return true;
  45193. }
  45194. return false;
  45195. };
  45196. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  45197. return "PBRBaseSimpleMaterial";
  45198. };
  45199. __decorate([
  45200. BABYLON.serialize(),
  45201. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45202. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  45203. __decorate([
  45204. BABYLON.serialize(),
  45205. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45206. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  45207. __decorate([
  45208. BABYLON.serializeAsTexture(),
  45209. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  45210. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  45211. __decorate([
  45212. BABYLON.serialize(),
  45213. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45214. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  45215. __decorate([
  45216. BABYLON.serialize(),
  45217. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45218. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  45219. __decorate([
  45220. BABYLON.serializeAsTexture(),
  45221. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  45222. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  45223. __decorate([
  45224. BABYLON.serializeAsColor3("emissive"),
  45225. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45226. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  45227. __decorate([
  45228. BABYLON.serializeAsTexture(),
  45229. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45230. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  45231. __decorate([
  45232. BABYLON.serialize(),
  45233. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  45234. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  45235. __decorate([
  45236. BABYLON.serializeAsTexture(),
  45237. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  45238. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  45239. __decorate([
  45240. BABYLON.serialize(),
  45241. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  45242. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  45243. __decorate([
  45244. BABYLON.serialize()
  45245. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  45246. __decorate([
  45247. BABYLON.serializeAsTexture(),
  45248. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45249. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  45250. __decorate([
  45251. BABYLON.serialize(),
  45252. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45253. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45254. return PBRBaseSimpleMaterial;
  45255. }(BABYLON.PBRBaseMaterial));
  45256. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  45257. })(BABYLON || (BABYLON = {}));
  45258. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  45259. var BABYLON;
  45260. (function (BABYLON) {
  45261. /**
  45262. * The Physically based material of BJS.
  45263. *
  45264. * This offers the main features of a standard PBR material.
  45265. * For more information, please refer to the documentation :
  45266. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45267. */
  45268. var PBRMaterial = /** @class */ (function (_super) {
  45269. __extends(PBRMaterial, _super);
  45270. /**
  45271. * Instantiates a new PBRMaterial instance.
  45272. *
  45273. * @param name The material name
  45274. * @param scene The scene the material will be use in.
  45275. */
  45276. function PBRMaterial(name, scene) {
  45277. var _this = _super.call(this, name, scene) || this;
  45278. /**
  45279. * Intensity of the direct lights e.g. the four lights available in your scene.
  45280. * This impacts both the direct diffuse and specular highlights.
  45281. */
  45282. _this.directIntensity = 1.0;
  45283. /**
  45284. * Intensity of the emissive part of the material.
  45285. * This helps controlling the emissive effect without modifying the emissive color.
  45286. */
  45287. _this.emissiveIntensity = 1.0;
  45288. /**
  45289. * Intensity of the environment e.g. how much the environment will light the object
  45290. * either through harmonics for rough material or through the refelction for shiny ones.
  45291. */
  45292. _this.environmentIntensity = 1.0;
  45293. /**
  45294. * This is a special control allowing the reduction of the specular highlights coming from the
  45295. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45296. */
  45297. _this.specularIntensity = 1.0;
  45298. /**
  45299. * Debug Control allowing disabling the bump map on this material.
  45300. */
  45301. _this.disableBumpMap = false;
  45302. /**
  45303. * AKA Occlusion Texture Intensity in other nomenclature.
  45304. */
  45305. _this.ambientTextureStrength = 1.0;
  45306. /**
  45307. * Defines how much the AO map is occluding the analytical lights (point spot...).
  45308. * 1 means it completely occludes it
  45309. * 0 mean it has no impact
  45310. */
  45311. _this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  45312. /**
  45313. * The color of a material in ambient lighting.
  45314. */
  45315. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45316. /**
  45317. * AKA Diffuse Color in other nomenclature.
  45318. */
  45319. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45320. /**
  45321. * AKA Specular Color in other nomenclature.
  45322. */
  45323. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45324. /**
  45325. * The color reflected from the material.
  45326. */
  45327. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45328. /**
  45329. * The color emitted from the material.
  45330. */
  45331. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45332. /**
  45333. * AKA Glossiness in other nomenclature.
  45334. */
  45335. _this.microSurface = 1.0;
  45336. /**
  45337. * source material index of refraction (IOR)' / 'destination material IOR.
  45338. */
  45339. _this.indexOfRefraction = 0.66;
  45340. /**
  45341. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45342. */
  45343. _this.invertRefractionY = false;
  45344. /**
  45345. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45346. * Materials half opaque for instance using refraction could benefit from this control.
  45347. */
  45348. _this.linkRefractionWithTransparency = false;
  45349. _this.useLightmapAsShadowmap = false;
  45350. /**
  45351. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45352. */
  45353. _this.useAlphaFromAlbedoTexture = false;
  45354. /**
  45355. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45356. */
  45357. _this.forceAlphaTest = false;
  45358. /**
  45359. * Defines the alpha limits in alpha test mode.
  45360. */
  45361. _this.alphaCutOff = 0.4;
  45362. /**
  45363. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45364. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45365. */
  45366. _this.useSpecularOverAlpha = true;
  45367. /**
  45368. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45369. */
  45370. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45371. /**
  45372. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45373. */
  45374. _this.useRoughnessFromMetallicTextureAlpha = true;
  45375. /**
  45376. * Specifies if the metallic texture contains the roughness information in its green channel.
  45377. */
  45378. _this.useRoughnessFromMetallicTextureGreen = false;
  45379. /**
  45380. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45381. */
  45382. _this.useMetallnessFromMetallicTextureBlue = false;
  45383. /**
  45384. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45385. */
  45386. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45387. /**
  45388. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45389. */
  45390. _this.useAmbientInGrayScale = false;
  45391. /**
  45392. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45393. * The material will try to infer what glossiness each pixel should be.
  45394. */
  45395. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45396. /**
  45397. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45398. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45399. */
  45400. _this.useRadianceOverAlpha = true;
  45401. /**
  45402. * Allows using an object space normal map (instead of tangent space).
  45403. */
  45404. _this.useObjectSpaceNormalMap = false;
  45405. /**
  45406. * Allows using the bump map in parallax mode.
  45407. */
  45408. _this.useParallax = false;
  45409. /**
  45410. * Allows using the bump map in parallax occlusion mode.
  45411. */
  45412. _this.useParallaxOcclusion = false;
  45413. /**
  45414. * Controls the scale bias of the parallax mode.
  45415. */
  45416. _this.parallaxScaleBias = 0.05;
  45417. /**
  45418. * If sets to true, disables all the lights affecting the material.
  45419. */
  45420. _this.disableLighting = false;
  45421. /**
  45422. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45423. */
  45424. _this.forceIrradianceInFragment = false;
  45425. /**
  45426. * Number of Simultaneous lights allowed on the material.
  45427. */
  45428. _this.maxSimultaneousLights = 4;
  45429. /**
  45430. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45431. */
  45432. _this.invertNormalMapX = false;
  45433. /**
  45434. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45435. */
  45436. _this.invertNormalMapY = false;
  45437. /**
  45438. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45439. */
  45440. _this.twoSidedLighting = false;
  45441. /**
  45442. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45443. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45444. */
  45445. _this.useAlphaFresnel = false;
  45446. /**
  45447. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45448. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45449. */
  45450. _this.useLinearAlphaFresnel = false;
  45451. /**
  45452. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45453. * And/Or occlude the blended part.
  45454. */
  45455. _this.environmentBRDFTexture = null;
  45456. /**
  45457. * Force normal to face away from face.
  45458. */
  45459. _this.forceNormalForward = false;
  45460. /**
  45461. * Enables specular anti aliasing in the PBR shader.
  45462. * It will both interacts on the Geometry for analytical and IBL lighting.
  45463. * It also prefilter the roughness map based on the bump values.
  45464. */
  45465. _this.enableSpecularAntiAliasing = false;
  45466. /**
  45467. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45468. * makes the reflect vector face the model (under horizon).
  45469. */
  45470. _this.useHorizonOcclusion = true;
  45471. /**
  45472. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45473. * too much the area relying on ambient texture to define their ambient occlusion.
  45474. */
  45475. _this.useRadianceOcclusion = true;
  45476. /**
  45477. * If set to true, no lighting calculations will be applied.
  45478. */
  45479. _this.unlit = false;
  45480. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45481. return _this;
  45482. }
  45483. Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
  45484. /**
  45485. * BJS is using an harcoded light falloff based on a manually sets up range.
  45486. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45487. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45488. */
  45489. get: function () {
  45490. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45491. },
  45492. /**
  45493. * BJS is using an harcoded light falloff based on a manually sets up range.
  45494. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45495. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45496. */
  45497. set: function (value) {
  45498. if (value !== this.usePhysicalLightFalloff) {
  45499. // Ensure the effect will be rebuilt.
  45500. this._markAllSubMeshesAsTexturesDirty();
  45501. if (value) {
  45502. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45503. }
  45504. else {
  45505. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45506. }
  45507. }
  45508. },
  45509. enumerable: true,
  45510. configurable: true
  45511. });
  45512. Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
  45513. /**
  45514. * In order to support the falloff compatibility with gltf, a special mode has been added
  45515. * to reproduce the gltf light falloff.
  45516. */
  45517. get: function () {
  45518. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45519. },
  45520. /**
  45521. * In order to support the falloff compatibility with gltf, a special mode has been added
  45522. * to reproduce the gltf light falloff.
  45523. */
  45524. set: function (value) {
  45525. if (value !== this.useGLTFLightFalloff) {
  45526. // Ensure the effect will be rebuilt.
  45527. this._markAllSubMeshesAsTexturesDirty();
  45528. if (value) {
  45529. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45530. }
  45531. else {
  45532. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45533. }
  45534. }
  45535. },
  45536. enumerable: true,
  45537. configurable: true
  45538. });
  45539. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45540. /**
  45541. * Gets the image processing configuration used either in this material.
  45542. */
  45543. get: function () {
  45544. return this._imageProcessingConfiguration;
  45545. },
  45546. /**
  45547. * Sets the Default image processing configuration used either in the this material.
  45548. *
  45549. * If sets to null, the scene one is in use.
  45550. */
  45551. set: function (value) {
  45552. this._attachImageProcessingConfiguration(value);
  45553. // Ensure the effect will be rebuilt.
  45554. this._markAllSubMeshesAsTexturesDirty();
  45555. },
  45556. enumerable: true,
  45557. configurable: true
  45558. });
  45559. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45560. /**
  45561. * Gets wether the color curves effect is enabled.
  45562. */
  45563. get: function () {
  45564. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45565. },
  45566. /**
  45567. * Sets wether the color curves effect is enabled.
  45568. */
  45569. set: function (value) {
  45570. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45571. },
  45572. enumerable: true,
  45573. configurable: true
  45574. });
  45575. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45576. /**
  45577. * Gets wether the color grading effect is enabled.
  45578. */
  45579. get: function () {
  45580. return this.imageProcessingConfiguration.colorGradingEnabled;
  45581. },
  45582. /**
  45583. * Gets wether the color grading effect is enabled.
  45584. */
  45585. set: function (value) {
  45586. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45587. },
  45588. enumerable: true,
  45589. configurable: true
  45590. });
  45591. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45592. /**
  45593. * Gets wether tonemapping is enabled or not.
  45594. */
  45595. get: function () {
  45596. return this._imageProcessingConfiguration.toneMappingEnabled;
  45597. },
  45598. /**
  45599. * Sets wether tonemapping is enabled or not
  45600. */
  45601. set: function (value) {
  45602. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45603. },
  45604. enumerable: true,
  45605. configurable: true
  45606. });
  45607. ;
  45608. ;
  45609. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45610. /**
  45611. * The camera exposure used on this material.
  45612. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45613. * This corresponds to a photographic exposure.
  45614. */
  45615. get: function () {
  45616. return this._imageProcessingConfiguration.exposure;
  45617. },
  45618. /**
  45619. * The camera exposure used on this material.
  45620. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45621. * This corresponds to a photographic exposure.
  45622. */
  45623. set: function (value) {
  45624. this._imageProcessingConfiguration.exposure = value;
  45625. },
  45626. enumerable: true,
  45627. configurable: true
  45628. });
  45629. ;
  45630. ;
  45631. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45632. /**
  45633. * Gets The camera contrast used on this material.
  45634. */
  45635. get: function () {
  45636. return this._imageProcessingConfiguration.contrast;
  45637. },
  45638. /**
  45639. * Sets The camera contrast used on this material.
  45640. */
  45641. set: function (value) {
  45642. this._imageProcessingConfiguration.contrast = value;
  45643. },
  45644. enumerable: true,
  45645. configurable: true
  45646. });
  45647. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45648. /**
  45649. * Gets the Color Grading 2D Lookup Texture.
  45650. */
  45651. get: function () {
  45652. return this._imageProcessingConfiguration.colorGradingTexture;
  45653. },
  45654. /**
  45655. * Sets the Color Grading 2D Lookup Texture.
  45656. */
  45657. set: function (value) {
  45658. this._imageProcessingConfiguration.colorGradingTexture = value;
  45659. },
  45660. enumerable: true,
  45661. configurable: true
  45662. });
  45663. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45664. /**
  45665. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45666. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45667. * 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;
  45668. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45669. */
  45670. get: function () {
  45671. return this._imageProcessingConfiguration.colorCurves;
  45672. },
  45673. /**
  45674. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45675. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45676. * 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;
  45677. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45678. */
  45679. set: function (value) {
  45680. this._imageProcessingConfiguration.colorCurves = value;
  45681. },
  45682. enumerable: true,
  45683. configurable: true
  45684. });
  45685. /**
  45686. * Returns the name of this material class.
  45687. */
  45688. PBRMaterial.prototype.getClassName = function () {
  45689. return "PBRMaterial";
  45690. };
  45691. /**
  45692. * Returns an array of the actively used textures.
  45693. * @returns - Array of BaseTextures
  45694. */
  45695. PBRMaterial.prototype.getActiveTextures = function () {
  45696. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45697. if (this._albedoTexture) {
  45698. activeTextures.push(this._albedoTexture);
  45699. }
  45700. if (this._ambientTexture) {
  45701. activeTextures.push(this._ambientTexture);
  45702. }
  45703. if (this._opacityTexture) {
  45704. activeTextures.push(this._opacityTexture);
  45705. }
  45706. if (this._reflectionTexture) {
  45707. activeTextures.push(this._reflectionTexture);
  45708. }
  45709. if (this._emissiveTexture) {
  45710. activeTextures.push(this._emissiveTexture);
  45711. }
  45712. if (this._reflectivityTexture) {
  45713. activeTextures.push(this._reflectivityTexture);
  45714. }
  45715. if (this._metallicTexture) {
  45716. activeTextures.push(this._metallicTexture);
  45717. }
  45718. if (this._microSurfaceTexture) {
  45719. activeTextures.push(this._microSurfaceTexture);
  45720. }
  45721. if (this._bumpTexture) {
  45722. activeTextures.push(this._bumpTexture);
  45723. }
  45724. if (this._lightmapTexture) {
  45725. activeTextures.push(this._lightmapTexture);
  45726. }
  45727. if (this._refractionTexture) {
  45728. activeTextures.push(this._refractionTexture);
  45729. }
  45730. return activeTextures;
  45731. };
  45732. /**
  45733. * Checks to see if a texture is used in the material.
  45734. * @param texture - Base texture to use.
  45735. * @returns - Boolean specifying if a texture is used in the material.
  45736. */
  45737. PBRMaterial.prototype.hasTexture = function (texture) {
  45738. if (_super.prototype.hasTexture.call(this, texture)) {
  45739. return true;
  45740. }
  45741. if (this._albedoTexture === texture) {
  45742. return true;
  45743. }
  45744. if (this._ambientTexture === texture) {
  45745. return true;
  45746. }
  45747. if (this._opacityTexture === texture) {
  45748. return true;
  45749. }
  45750. if (this._reflectionTexture === texture) {
  45751. return true;
  45752. }
  45753. if (this._reflectivityTexture === texture) {
  45754. return true;
  45755. }
  45756. if (this._metallicTexture === texture) {
  45757. return true;
  45758. }
  45759. if (this._microSurfaceTexture === texture) {
  45760. return true;
  45761. }
  45762. if (this._bumpTexture === texture) {
  45763. return true;
  45764. }
  45765. if (this._lightmapTexture === texture) {
  45766. return true;
  45767. }
  45768. if (this._refractionTexture === texture) {
  45769. return true;
  45770. }
  45771. return false;
  45772. };
  45773. /**
  45774. * Makes a duplicate of the current material.
  45775. * @param name - name to use for the new material.
  45776. */
  45777. PBRMaterial.prototype.clone = function (name) {
  45778. var _this = this;
  45779. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45780. clone.id = name;
  45781. clone.name = name;
  45782. return clone;
  45783. };
  45784. /**
  45785. * Serializes this PBR Material.
  45786. * @returns - An object with the serialized material.
  45787. */
  45788. PBRMaterial.prototype.serialize = function () {
  45789. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45790. serializationObject.customType = "BABYLON.PBRMaterial";
  45791. return serializationObject;
  45792. };
  45793. // Statics
  45794. /**
  45795. * Parses a PBR Material from a serialized object.
  45796. * @param source - Serialized object.
  45797. * @param scene - BJS scene instance.
  45798. * @param rootUrl - url for the scene object
  45799. * @returns - PBRMaterial
  45800. */
  45801. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45802. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45803. };
  45804. /**
  45805. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45806. */
  45807. PBRMaterial.PBRMATERIAL_OPAQUE = 0;
  45808. /**
  45809. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45810. */
  45811. PBRMaterial.PBRMATERIAL_ALPHATEST = 1;
  45812. /**
  45813. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45814. */
  45815. PBRMaterial.PBRMATERIAL_ALPHABLEND = 2;
  45816. /**
  45817. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45818. * They are also discarded below the alpha cutoff threshold to improve performances.
  45819. */
  45820. PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45821. /**
  45822. * Defines the default value of how much AO map is occluding the analytical lights
  45823. * (point spot...).
  45824. */
  45825. PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 1;
  45826. __decorate([
  45827. BABYLON.serialize(),
  45828. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45829. ], PBRMaterial.prototype, "directIntensity", void 0);
  45830. __decorate([
  45831. BABYLON.serialize(),
  45832. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45833. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45834. __decorate([
  45835. BABYLON.serialize(),
  45836. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45837. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45838. __decorate([
  45839. BABYLON.serialize(),
  45840. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45841. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45842. __decorate([
  45843. BABYLON.serialize(),
  45844. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45845. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45846. __decorate([
  45847. BABYLON.serializeAsTexture(),
  45848. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45849. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45850. __decorate([
  45851. BABYLON.serializeAsTexture(),
  45852. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45853. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45854. __decorate([
  45855. BABYLON.serialize(),
  45856. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45857. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45858. __decorate([
  45859. BABYLON.serialize(),
  45860. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45861. ], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0);
  45862. __decorate([
  45863. BABYLON.serializeAsTexture(),
  45864. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45865. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45866. __decorate([
  45867. BABYLON.serializeAsTexture(),
  45868. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45869. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45870. __decorate([
  45871. BABYLON.serializeAsTexture(),
  45872. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45873. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45874. __decorate([
  45875. BABYLON.serializeAsTexture(),
  45876. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45877. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45878. __decorate([
  45879. BABYLON.serializeAsTexture(),
  45880. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45881. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45882. __decorate([
  45883. BABYLON.serialize(),
  45884. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45885. ], PBRMaterial.prototype, "metallic", void 0);
  45886. __decorate([
  45887. BABYLON.serialize(),
  45888. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45889. ], PBRMaterial.prototype, "roughness", void 0);
  45890. __decorate([
  45891. BABYLON.serializeAsTexture(),
  45892. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45893. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45894. __decorate([
  45895. BABYLON.serializeAsTexture(),
  45896. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45897. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45898. __decorate([
  45899. BABYLON.serializeAsTexture(),
  45900. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45901. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45902. __decorate([
  45903. BABYLON.serializeAsTexture(),
  45904. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45905. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45906. __decorate([
  45907. BABYLON.serializeAsColor3("ambient"),
  45908. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45909. ], PBRMaterial.prototype, "ambientColor", void 0);
  45910. __decorate([
  45911. BABYLON.serializeAsColor3("albedo"),
  45912. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45913. ], PBRMaterial.prototype, "albedoColor", void 0);
  45914. __decorate([
  45915. BABYLON.serializeAsColor3("reflectivity"),
  45916. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45917. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45918. __decorate([
  45919. BABYLON.serializeAsColor3("reflection"),
  45920. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45921. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45922. __decorate([
  45923. BABYLON.serializeAsColor3("emissive"),
  45924. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45925. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45926. __decorate([
  45927. BABYLON.serialize(),
  45928. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45929. ], PBRMaterial.prototype, "microSurface", void 0);
  45930. __decorate([
  45931. BABYLON.serialize(),
  45932. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45933. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45934. __decorate([
  45935. BABYLON.serialize(),
  45936. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45937. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45938. __decorate([
  45939. BABYLON.serialize(),
  45940. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45941. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45942. __decorate([
  45943. BABYLON.serialize(),
  45944. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45945. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45946. __decorate([
  45947. BABYLON.serialize(),
  45948. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45949. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45950. __decorate([
  45951. BABYLON.serialize(),
  45952. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45953. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45954. __decorate([
  45955. BABYLON.serialize(),
  45956. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45957. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45958. __decorate([
  45959. BABYLON.serialize(),
  45960. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45961. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45962. __decorate([
  45963. BABYLON.serialize(),
  45964. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45965. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45966. __decorate([
  45967. BABYLON.serialize(),
  45968. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45969. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45970. __decorate([
  45971. BABYLON.serialize(),
  45972. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45973. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45974. __decorate([
  45975. BABYLON.serialize(),
  45976. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45977. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45978. __decorate([
  45979. BABYLON.serialize(),
  45980. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45981. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45982. __decorate([
  45983. BABYLON.serialize(),
  45984. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45985. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45986. __decorate([
  45987. BABYLON.serialize(),
  45988. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45989. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45990. __decorate([
  45991. BABYLON.serialize()
  45992. ], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
  45993. __decorate([
  45994. BABYLON.serialize()
  45995. ], PBRMaterial.prototype, "useGLTFLightFalloff", null);
  45996. __decorate([
  45997. BABYLON.serialize(),
  45998. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45999. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46000. __decorate([
  46001. BABYLON.serialize(),
  46002. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46003. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  46004. __decorate([
  46005. BABYLON.serialize(),
  46006. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46007. ], PBRMaterial.prototype, "useParallax", void 0);
  46008. __decorate([
  46009. BABYLON.serialize(),
  46010. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46011. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46012. __decorate([
  46013. BABYLON.serialize(),
  46014. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46015. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46016. __decorate([
  46017. BABYLON.serialize(),
  46018. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46019. ], PBRMaterial.prototype, "disableLighting", void 0);
  46020. __decorate([
  46021. BABYLON.serialize(),
  46022. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46023. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  46024. __decorate([
  46025. BABYLON.serialize(),
  46026. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46027. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  46028. __decorate([
  46029. BABYLON.serialize(),
  46030. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46031. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  46032. __decorate([
  46033. BABYLON.serialize(),
  46034. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46035. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  46036. __decorate([
  46037. BABYLON.serialize(),
  46038. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46039. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  46040. __decorate([
  46041. BABYLON.serialize(),
  46042. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46043. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  46044. __decorate([
  46045. BABYLON.serialize(),
  46046. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46047. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  46048. __decorate([
  46049. BABYLON.serializeAsTexture(),
  46050. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46051. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  46052. __decorate([
  46053. BABYLON.serialize(),
  46054. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46055. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  46056. __decorate([
  46057. BABYLON.serialize(),
  46058. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46059. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  46060. __decorate([
  46061. BABYLON.serialize(),
  46062. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46063. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  46064. __decorate([
  46065. BABYLON.serialize(),
  46066. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46067. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  46068. __decorate([
  46069. BABYLON.serialize(),
  46070. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  46071. ], PBRMaterial.prototype, "unlit", void 0);
  46072. return PBRMaterial;
  46073. }(BABYLON.PBRBaseMaterial));
  46074. BABYLON.PBRMaterial = PBRMaterial;
  46075. })(BABYLON || (BABYLON = {}));
  46076. //# sourceMappingURL=babylon.pbrMaterial.js.map
  46077. var BABYLON;
  46078. (function (BABYLON) {
  46079. /**
  46080. * The PBR material of BJS following the metal roughness convention.
  46081. *
  46082. * This fits to the PBR convention in the GLTF definition:
  46083. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  46084. */
  46085. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  46086. __extends(PBRMetallicRoughnessMaterial, _super);
  46087. /**
  46088. * Instantiates a new PBRMetalRoughnessMaterial instance.
  46089. *
  46090. * @param name The material name
  46091. * @param scene The scene the material will be use in.
  46092. */
  46093. function PBRMetallicRoughnessMaterial(name, scene) {
  46094. var _this = _super.call(this, name, scene) || this;
  46095. _this._useRoughnessFromMetallicTextureAlpha = false;
  46096. _this._useRoughnessFromMetallicTextureGreen = true;
  46097. _this._useMetallnessFromMetallicTextureBlue = true;
  46098. _this.metallic = 1.0;
  46099. _this.roughness = 1.0;
  46100. return _this;
  46101. }
  46102. /**
  46103. * Return the currrent class name of the material.
  46104. */
  46105. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  46106. return "PBRMetallicRoughnessMaterial";
  46107. };
  46108. /**
  46109. * Return the active textures of the material.
  46110. */
  46111. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  46112. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46113. if (this.baseTexture) {
  46114. activeTextures.push(this.baseTexture);
  46115. }
  46116. if (this.metallicRoughnessTexture) {
  46117. activeTextures.push(this.metallicRoughnessTexture);
  46118. }
  46119. return activeTextures;
  46120. };
  46121. /**
  46122. * Checks to see if a texture is used in the material.
  46123. * @param texture - Base texture to use.
  46124. * @returns - Boolean specifying if a texture is used in the material.
  46125. */
  46126. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  46127. if (_super.prototype.hasTexture.call(this, texture)) {
  46128. return true;
  46129. }
  46130. if (this.baseTexture === texture) {
  46131. return true;
  46132. }
  46133. if (this.metallicRoughnessTexture === texture) {
  46134. return true;
  46135. }
  46136. return false;
  46137. };
  46138. /**
  46139. * Makes a duplicate of the current material.
  46140. * @param name - name to use for the new material.
  46141. */
  46142. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  46143. var _this = this;
  46144. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  46145. clone.id = name;
  46146. clone.name = name;
  46147. return clone;
  46148. };
  46149. /**
  46150. * Serialize the material to a parsable JSON object.
  46151. */
  46152. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  46153. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46154. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  46155. return serializationObject;
  46156. };
  46157. /**
  46158. * Parses a JSON object correponding to the serialize function.
  46159. */
  46160. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  46161. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  46162. };
  46163. __decorate([
  46164. BABYLON.serializeAsColor3(),
  46165. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46166. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  46167. __decorate([
  46168. BABYLON.serializeAsTexture(),
  46169. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46170. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  46171. __decorate([
  46172. BABYLON.serialize(),
  46173. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46174. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  46175. __decorate([
  46176. BABYLON.serialize(),
  46177. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46178. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  46179. __decorate([
  46180. BABYLON.serializeAsTexture(),
  46181. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  46182. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  46183. return PBRMetallicRoughnessMaterial;
  46184. }(BABYLON.PBRBaseSimpleMaterial));
  46185. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  46186. })(BABYLON || (BABYLON = {}));
  46187. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  46188. var BABYLON;
  46189. (function (BABYLON) {
  46190. /**
  46191. * The PBR material of BJS following the specular glossiness convention.
  46192. *
  46193. * This fits to the PBR convention in the GLTF definition:
  46194. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  46195. */
  46196. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  46197. __extends(PBRSpecularGlossinessMaterial, _super);
  46198. /**
  46199. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  46200. *
  46201. * @param name The material name
  46202. * @param scene The scene the material will be use in.
  46203. */
  46204. function PBRSpecularGlossinessMaterial(name, scene) {
  46205. var _this = _super.call(this, name, scene) || this;
  46206. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  46207. return _this;
  46208. }
  46209. /**
  46210. * Return the currrent class name of the material.
  46211. */
  46212. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  46213. return "PBRSpecularGlossinessMaterial";
  46214. };
  46215. /**
  46216. * Return the active textures of the material.
  46217. */
  46218. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  46219. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46220. if (this.diffuseTexture) {
  46221. activeTextures.push(this.diffuseTexture);
  46222. }
  46223. if (this.specularGlossinessTexture) {
  46224. activeTextures.push(this.specularGlossinessTexture);
  46225. }
  46226. return activeTextures;
  46227. };
  46228. /**
  46229. * Checks to see if a texture is used in the material.
  46230. * @param texture - Base texture to use.
  46231. * @returns - Boolean specifying if a texture is used in the material.
  46232. */
  46233. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  46234. if (_super.prototype.hasTexture.call(this, texture)) {
  46235. return true;
  46236. }
  46237. if (this.diffuseTexture === texture) {
  46238. return true;
  46239. }
  46240. if (this.specularGlossinessTexture === texture) {
  46241. return true;
  46242. }
  46243. return false;
  46244. };
  46245. /**
  46246. * Makes a duplicate of the current material.
  46247. * @param name - name to use for the new material.
  46248. */
  46249. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  46250. var _this = this;
  46251. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  46252. clone.id = name;
  46253. clone.name = name;
  46254. return clone;
  46255. };
  46256. /**
  46257. * Serialize the material to a parsable JSON object.
  46258. */
  46259. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  46260. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46261. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  46262. return serializationObject;
  46263. };
  46264. /**
  46265. * Parses a JSON object correponding to the serialize function.
  46266. */
  46267. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  46268. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  46269. };
  46270. __decorate([
  46271. BABYLON.serializeAsColor3("diffuse"),
  46272. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46273. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  46274. __decorate([
  46275. BABYLON.serializeAsTexture(),
  46276. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46277. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46278. __decorate([
  46279. BABYLON.serializeAsColor3("specular"),
  46280. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46281. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46282. __decorate([
  46283. BABYLON.serialize(),
  46284. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46285. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46286. __decorate([
  46287. BABYLON.serializeAsTexture(),
  46288. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46289. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46290. return PBRSpecularGlossinessMaterial;
  46291. }(BABYLON.PBRBaseSimpleMaterial));
  46292. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46293. })(BABYLON || (BABYLON = {}));
  46294. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46295. var BABYLON;
  46296. (function (BABYLON) {
  46297. BABYLON.CameraInputTypes = {};
  46298. var CameraInputsManager = /** @class */ (function () {
  46299. function CameraInputsManager(camera) {
  46300. this.attached = {};
  46301. this.camera = camera;
  46302. this.checkInputs = function () { };
  46303. }
  46304. /**
  46305. * Add an input method to a camera
  46306. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46307. * @param input camera input method
  46308. */
  46309. CameraInputsManager.prototype.add = function (input) {
  46310. var type = input.getSimpleName();
  46311. if (this.attached[type]) {
  46312. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46313. return;
  46314. }
  46315. this.attached[type] = input;
  46316. input.camera = this.camera;
  46317. //for checkInputs, we are dynamically creating a function
  46318. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46319. if (input.checkInputs) {
  46320. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46321. }
  46322. if (this.attachedElement) {
  46323. input.attachControl(this.attachedElement);
  46324. }
  46325. };
  46326. /**
  46327. * Remove a specific input method from a camera
  46328. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46329. * @param inputToRemove camera input method
  46330. */
  46331. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46332. for (var cam in this.attached) {
  46333. var input = this.attached[cam];
  46334. if (input === inputToRemove) {
  46335. input.detachControl(this.attachedElement);
  46336. input.camera = null;
  46337. delete this.attached[cam];
  46338. this.rebuildInputCheck();
  46339. }
  46340. }
  46341. };
  46342. CameraInputsManager.prototype.removeByType = function (inputType) {
  46343. for (var cam in this.attached) {
  46344. var input = this.attached[cam];
  46345. if (input.getClassName() === inputType) {
  46346. input.detachControl(this.attachedElement);
  46347. input.camera = null;
  46348. delete this.attached[cam];
  46349. this.rebuildInputCheck();
  46350. }
  46351. }
  46352. };
  46353. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46354. var current = this.checkInputs;
  46355. return function () {
  46356. current();
  46357. fn();
  46358. };
  46359. };
  46360. CameraInputsManager.prototype.attachInput = function (input) {
  46361. if (this.attachedElement) {
  46362. input.attachControl(this.attachedElement, this.noPreventDefault);
  46363. }
  46364. };
  46365. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46366. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46367. if (this.attachedElement) {
  46368. return;
  46369. }
  46370. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46371. this.attachedElement = element;
  46372. this.noPreventDefault = noPreventDefault;
  46373. for (var cam in this.attached) {
  46374. this.attached[cam].attachControl(element, noPreventDefault);
  46375. }
  46376. };
  46377. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46378. if (disconnect === void 0) { disconnect = false; }
  46379. if (this.attachedElement !== element) {
  46380. return;
  46381. }
  46382. for (var cam in this.attached) {
  46383. this.attached[cam].detachControl(element);
  46384. if (disconnect) {
  46385. this.attached[cam].camera = null;
  46386. }
  46387. }
  46388. this.attachedElement = null;
  46389. };
  46390. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46391. this.checkInputs = function () { };
  46392. for (var cam in this.attached) {
  46393. var input = this.attached[cam];
  46394. if (input.checkInputs) {
  46395. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46396. }
  46397. }
  46398. };
  46399. /**
  46400. * Remove all attached input methods from a camera
  46401. */
  46402. CameraInputsManager.prototype.clear = function () {
  46403. if (this.attachedElement) {
  46404. this.detachElement(this.attachedElement, true);
  46405. }
  46406. this.attached = {};
  46407. this.attachedElement = null;
  46408. this.checkInputs = function () { };
  46409. };
  46410. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46411. var inputs = {};
  46412. for (var cam in this.attached) {
  46413. var input = this.attached[cam];
  46414. var res = BABYLON.SerializationHelper.Serialize(input);
  46415. inputs[input.getClassName()] = res;
  46416. }
  46417. serializedCamera.inputsmgr = inputs;
  46418. };
  46419. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46420. var parsedInputs = parsedCamera.inputsmgr;
  46421. if (parsedInputs) {
  46422. this.clear();
  46423. for (var n in parsedInputs) {
  46424. var construct = BABYLON.CameraInputTypes[n];
  46425. if (construct) {
  46426. var parsedinput = parsedInputs[n];
  46427. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46428. this.add(input);
  46429. }
  46430. }
  46431. }
  46432. else {
  46433. //2016-03-08 this part is for managing backward compatibility
  46434. for (var n in this.attached) {
  46435. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46436. if (construct) {
  46437. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46438. this.remove(this.attached[n]);
  46439. this.add(input);
  46440. }
  46441. }
  46442. }
  46443. };
  46444. return CameraInputsManager;
  46445. }());
  46446. BABYLON.CameraInputsManager = CameraInputsManager;
  46447. })(BABYLON || (BABYLON = {}));
  46448. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46449. var BABYLON;
  46450. (function (BABYLON) {
  46451. var TargetCamera = /** @class */ (function (_super) {
  46452. __extends(TargetCamera, _super);
  46453. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46454. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46455. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46456. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46457. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46458. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46459. _this.speed = 2.0;
  46460. _this.noRotationConstraint = false;
  46461. _this.lockedTarget = null;
  46462. /** @hidden */
  46463. _this._currentTarget = BABYLON.Vector3.Zero();
  46464. /** @hidden */
  46465. _this._viewMatrix = BABYLON.Matrix.Zero();
  46466. /** @hidden */
  46467. _this._camMatrix = BABYLON.Matrix.Zero();
  46468. /** @hidden */
  46469. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46470. /** @hidden */
  46471. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46472. /** @hidden */
  46473. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46474. /** @hidden */
  46475. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46476. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46477. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46478. _this._defaultUp = BABYLON.Vector3.Up();
  46479. _this._cachedRotationZ = 0;
  46480. return _this;
  46481. }
  46482. TargetCamera.prototype.getFrontPosition = function (distance) {
  46483. this.getWorldMatrix();
  46484. var direction = this.getTarget().subtract(this.position);
  46485. direction.normalize();
  46486. direction.scaleInPlace(distance);
  46487. return this.globalPosition.add(direction);
  46488. };
  46489. /** @hidden */
  46490. TargetCamera.prototype._getLockedTargetPosition = function () {
  46491. if (!this.lockedTarget) {
  46492. return null;
  46493. }
  46494. if (this.lockedTarget.absolutePosition) {
  46495. this.lockedTarget.computeWorldMatrix();
  46496. }
  46497. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46498. };
  46499. TargetCamera.prototype.storeState = function () {
  46500. this._storedPosition = this.position.clone();
  46501. this._storedRotation = this.rotation.clone();
  46502. if (this.rotationQuaternion) {
  46503. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46504. }
  46505. return _super.prototype.storeState.call(this);
  46506. };
  46507. /**
  46508. * Restored camera state. You must call storeState() first
  46509. * @returns whether it was successful or not
  46510. * @hidden
  46511. */
  46512. TargetCamera.prototype._restoreStateValues = function () {
  46513. if (!_super.prototype._restoreStateValues.call(this)) {
  46514. return false;
  46515. }
  46516. this.position = this._storedPosition.clone();
  46517. this.rotation = this._storedRotation.clone();
  46518. if (this.rotationQuaternion) {
  46519. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46520. }
  46521. this.cameraDirection.copyFromFloats(0, 0, 0);
  46522. this.cameraRotation.copyFromFloats(0, 0);
  46523. return true;
  46524. };
  46525. // Cache
  46526. /** @hidden */
  46527. TargetCamera.prototype._initCache = function () {
  46528. _super.prototype._initCache.call(this);
  46529. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46530. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46531. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46532. };
  46533. /** @hidden */
  46534. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46535. if (!ignoreParentClass) {
  46536. _super.prototype._updateCache.call(this);
  46537. }
  46538. var lockedTargetPosition = this._getLockedTargetPosition();
  46539. if (!lockedTargetPosition) {
  46540. this._cache.lockedTarget = null;
  46541. }
  46542. else {
  46543. if (!this._cache.lockedTarget) {
  46544. this._cache.lockedTarget = lockedTargetPosition.clone();
  46545. }
  46546. else {
  46547. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46548. }
  46549. }
  46550. this._cache.rotation.copyFrom(this.rotation);
  46551. if (this.rotationQuaternion)
  46552. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46553. };
  46554. // Synchronized
  46555. /** @hidden */
  46556. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46557. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46558. return false;
  46559. }
  46560. var lockedTargetPosition = this._getLockedTargetPosition();
  46561. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46562. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46563. };
  46564. // Methods
  46565. /** @hidden */
  46566. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46567. var engine = this.getEngine();
  46568. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46569. };
  46570. // Target
  46571. /** @hidden */
  46572. TargetCamera.prototype.setTarget = function (target) {
  46573. this.upVector.normalize();
  46574. if (this.position.z === target.z) {
  46575. this.position.z += BABYLON.Epsilon;
  46576. }
  46577. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);
  46578. this._camMatrix.invert();
  46579. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46580. var vDir = target.subtract(this.position);
  46581. if (vDir.x >= 0.0) {
  46582. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46583. }
  46584. else {
  46585. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46586. }
  46587. this.rotation.z = 0;
  46588. if (isNaN(this.rotation.x)) {
  46589. this.rotation.x = 0;
  46590. }
  46591. if (isNaN(this.rotation.y)) {
  46592. this.rotation.y = 0;
  46593. }
  46594. if (isNaN(this.rotation.z)) {
  46595. this.rotation.z = 0;
  46596. }
  46597. if (this.rotationQuaternion) {
  46598. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46599. }
  46600. };
  46601. /**
  46602. * Return the current target position of the camera. This value is expressed in local space.
  46603. */
  46604. TargetCamera.prototype.getTarget = function () {
  46605. return this._currentTarget;
  46606. };
  46607. /** @hidden */
  46608. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46609. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46610. };
  46611. /** @hidden */
  46612. TargetCamera.prototype._updatePosition = function () {
  46613. if (this.parent) {
  46614. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46615. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46616. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46617. return;
  46618. }
  46619. this.position.addInPlace(this.cameraDirection);
  46620. };
  46621. /** @hidden */
  46622. TargetCamera.prototype._checkInputs = function () {
  46623. var needToMove = this._decideIfNeedsToMove();
  46624. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46625. // Move
  46626. if (needToMove) {
  46627. this._updatePosition();
  46628. }
  46629. // Rotate
  46630. if (needToRotate) {
  46631. this.rotation.x += this.cameraRotation.x;
  46632. this.rotation.y += this.cameraRotation.y;
  46633. //rotate, if quaternion is set and rotation was used
  46634. if (this.rotationQuaternion) {
  46635. var len = this.rotation.lengthSquared();
  46636. if (len) {
  46637. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46638. }
  46639. }
  46640. if (!this.noRotationConstraint) {
  46641. var limit = (Math.PI / 2) * 0.95;
  46642. if (this.rotation.x > limit)
  46643. this.rotation.x = limit;
  46644. if (this.rotation.x < -limit)
  46645. this.rotation.x = -limit;
  46646. }
  46647. }
  46648. // Inertia
  46649. if (needToMove) {
  46650. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46651. this.cameraDirection.x = 0;
  46652. }
  46653. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46654. this.cameraDirection.y = 0;
  46655. }
  46656. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46657. this.cameraDirection.z = 0;
  46658. }
  46659. this.cameraDirection.scaleInPlace(this.inertia);
  46660. }
  46661. if (needToRotate) {
  46662. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46663. this.cameraRotation.x = 0;
  46664. }
  46665. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46666. this.cameraRotation.y = 0;
  46667. }
  46668. this.cameraRotation.scaleInPlace(this.inertia);
  46669. }
  46670. _super.prototype._checkInputs.call(this);
  46671. };
  46672. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46673. if (this.rotationQuaternion) {
  46674. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46675. }
  46676. else {
  46677. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46678. }
  46679. };
  46680. /**
  46681. * Update the up vector to apply the rotation of the camera (So if you changed the camera rotation.z this will let you update the up vector as well)
  46682. * @returns the current camera
  46683. */
  46684. TargetCamera.prototype._rotateUpVectorWithCameraRotationMatrix = function () {
  46685. BABYLON.Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);
  46686. return this;
  46687. };
  46688. /** @hidden */
  46689. TargetCamera.prototype._getViewMatrix = function () {
  46690. if (this.lockedTarget) {
  46691. this.setTarget(this._getLockedTargetPosition());
  46692. }
  46693. // Compute
  46694. this._updateCameraRotationMatrix();
  46695. // Apply the changed rotation to the upVector.
  46696. if (this._cachedRotationZ != this.rotation.z) {
  46697. this._rotateUpVectorWithCameraRotationMatrix();
  46698. this._cachedRotationZ = this.rotation.z;
  46699. }
  46700. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46701. // Computing target and final matrix
  46702. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46703. this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
  46704. return this._viewMatrix;
  46705. };
  46706. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46707. if (this.parent) {
  46708. var parentWorldMatrix = this.parent.getWorldMatrix();
  46709. BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
  46710. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46711. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46712. this._markSyncedWithParent();
  46713. }
  46714. else {
  46715. this._globalPosition.copyFrom(position);
  46716. this._globalCurrentTarget.copyFrom(target);
  46717. this._globalCurrentUpVector.copyFrom(up);
  46718. }
  46719. if (this.getScene().useRightHandedSystem) {
  46720. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46721. }
  46722. else {
  46723. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46724. }
  46725. };
  46726. /**
  46727. * @override
  46728. * Override Camera.createRigCamera
  46729. */
  46730. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46731. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46732. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46733. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46734. if (!this.rotationQuaternion) {
  46735. this.rotationQuaternion = new BABYLON.Quaternion();
  46736. }
  46737. rigCamera._cameraRigParams = {};
  46738. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46739. }
  46740. return rigCamera;
  46741. }
  46742. return null;
  46743. };
  46744. /**
  46745. * @hidden
  46746. * @override
  46747. * Override Camera._updateRigCameras
  46748. */
  46749. TargetCamera.prototype._updateRigCameras = function () {
  46750. var camLeft = this._rigCameras[0];
  46751. var camRight = this._rigCameras[1];
  46752. switch (this.cameraRigMode) {
  46753. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46754. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46755. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46756. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46757. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46758. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46759. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46760. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46761. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46762. camLeft.setTarget(this.getTarget());
  46763. camRight.setTarget(this.getTarget());
  46764. break;
  46765. case BABYLON.Camera.RIG_MODE_VR:
  46766. if (camLeft.rotationQuaternion) {
  46767. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46768. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46769. }
  46770. else {
  46771. camLeft.rotation.copyFrom(this.rotation);
  46772. camRight.rotation.copyFrom(this.rotation);
  46773. }
  46774. camLeft.position.copyFrom(this.position);
  46775. camRight.position.copyFrom(this.position);
  46776. break;
  46777. }
  46778. _super.prototype._updateRigCameras.call(this);
  46779. };
  46780. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46781. if (!this._rigCamTransformMatrix) {
  46782. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46783. }
  46784. var target = this.getTarget();
  46785. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46786. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46787. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46788. };
  46789. TargetCamera.prototype.getClassName = function () {
  46790. return "TargetCamera";
  46791. };
  46792. __decorate([
  46793. BABYLON.serializeAsVector3()
  46794. ], TargetCamera.prototype, "rotation", void 0);
  46795. __decorate([
  46796. BABYLON.serialize()
  46797. ], TargetCamera.prototype, "speed", void 0);
  46798. __decorate([
  46799. BABYLON.serializeAsMeshReference("lockedTargetId")
  46800. ], TargetCamera.prototype, "lockedTarget", void 0);
  46801. return TargetCamera;
  46802. }(BABYLON.Camera));
  46803. BABYLON.TargetCamera = TargetCamera;
  46804. })(BABYLON || (BABYLON = {}));
  46805. //# sourceMappingURL=babylon.targetCamera.js.map
  46806. var BABYLON;
  46807. (function (BABYLON) {
  46808. var FreeCameraMouseInput = /** @class */ (function () {
  46809. function FreeCameraMouseInput(touchEnabled) {
  46810. if (touchEnabled === void 0) { touchEnabled = true; }
  46811. this.touchEnabled = touchEnabled;
  46812. this.buttons = [0, 1, 2];
  46813. this.angularSensibility = 2000.0;
  46814. this.previousPosition = null;
  46815. }
  46816. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46817. var _this = this;
  46818. var engine = this.camera.getEngine();
  46819. if (!this._pointerInput) {
  46820. this._pointerInput = function (p, s) {
  46821. var evt = p.event;
  46822. if (engine.isInVRExclusivePointerMode) {
  46823. return;
  46824. }
  46825. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46826. return;
  46827. }
  46828. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46829. return;
  46830. }
  46831. var srcElement = (evt.srcElement || evt.target);
  46832. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46833. try {
  46834. srcElement.setPointerCapture(evt.pointerId);
  46835. }
  46836. catch (e) {
  46837. //Nothing to do with the error. Execution will continue.
  46838. }
  46839. _this.previousPosition = {
  46840. x: evt.clientX,
  46841. y: evt.clientY
  46842. };
  46843. if (!noPreventDefault) {
  46844. evt.preventDefault();
  46845. element.focus();
  46846. }
  46847. }
  46848. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46849. try {
  46850. srcElement.releasePointerCapture(evt.pointerId);
  46851. }
  46852. catch (e) {
  46853. //Nothing to do with the error.
  46854. }
  46855. _this.previousPosition = null;
  46856. if (!noPreventDefault) {
  46857. evt.preventDefault();
  46858. }
  46859. }
  46860. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46861. if (!_this.previousPosition || engine.isPointerLock) {
  46862. return;
  46863. }
  46864. var offsetX = evt.clientX - _this.previousPosition.x;
  46865. if (_this.camera.getScene().useRightHandedSystem)
  46866. offsetX *= -1;
  46867. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46868. offsetX *= -1;
  46869. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46870. var offsetY = evt.clientY - _this.previousPosition.y;
  46871. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46872. _this.previousPosition = {
  46873. x: evt.clientX,
  46874. y: evt.clientY
  46875. };
  46876. if (!noPreventDefault) {
  46877. evt.preventDefault();
  46878. }
  46879. }
  46880. };
  46881. }
  46882. this._onMouseMove = function (evt) {
  46883. if (!engine.isPointerLock) {
  46884. return;
  46885. }
  46886. if (engine.isInVRExclusivePointerMode) {
  46887. return;
  46888. }
  46889. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46890. if (_this.camera.getScene().useRightHandedSystem)
  46891. offsetX *= -1;
  46892. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46893. offsetX *= -1;
  46894. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46895. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46896. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46897. _this.previousPosition = null;
  46898. if (!noPreventDefault) {
  46899. evt.preventDefault();
  46900. }
  46901. };
  46902. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46903. element.addEventListener("mousemove", this._onMouseMove, false);
  46904. };
  46905. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46906. if (this._observer && element) {
  46907. this.camera.getScene().onPointerObservable.remove(this._observer);
  46908. if (this._onMouseMove) {
  46909. element.removeEventListener("mousemove", this._onMouseMove);
  46910. }
  46911. this._observer = null;
  46912. this._onMouseMove = null;
  46913. this.previousPosition = null;
  46914. }
  46915. };
  46916. FreeCameraMouseInput.prototype.getClassName = function () {
  46917. return "FreeCameraMouseInput";
  46918. };
  46919. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46920. return "mouse";
  46921. };
  46922. __decorate([
  46923. BABYLON.serialize()
  46924. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46925. __decorate([
  46926. BABYLON.serialize()
  46927. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46928. return FreeCameraMouseInput;
  46929. }());
  46930. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46931. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46932. })(BABYLON || (BABYLON = {}));
  46933. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46934. var BABYLON;
  46935. (function (BABYLON) {
  46936. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46937. function FreeCameraKeyboardMoveInput() {
  46938. this._keys = new Array();
  46939. this.keysUp = [38];
  46940. this.keysDown = [40];
  46941. this.keysLeft = [37];
  46942. this.keysRight = [39];
  46943. }
  46944. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46945. var _this = this;
  46946. if (this._onCanvasBlurObserver) {
  46947. return;
  46948. }
  46949. this._scene = this.camera.getScene();
  46950. this._engine = this._scene.getEngine();
  46951. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46952. _this._keys = [];
  46953. });
  46954. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46955. var evt = info.event;
  46956. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46957. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46958. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46959. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46960. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46961. var index = _this._keys.indexOf(evt.keyCode);
  46962. if (index === -1) {
  46963. _this._keys.push(evt.keyCode);
  46964. }
  46965. if (!noPreventDefault) {
  46966. evt.preventDefault();
  46967. }
  46968. }
  46969. }
  46970. else {
  46971. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46972. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46973. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46974. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46975. var index = _this._keys.indexOf(evt.keyCode);
  46976. if (index >= 0) {
  46977. _this._keys.splice(index, 1);
  46978. }
  46979. if (!noPreventDefault) {
  46980. evt.preventDefault();
  46981. }
  46982. }
  46983. }
  46984. });
  46985. };
  46986. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46987. if (this._scene) {
  46988. if (this._onKeyboardObserver) {
  46989. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46990. }
  46991. if (this._onCanvasBlurObserver) {
  46992. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46993. }
  46994. this._onKeyboardObserver = null;
  46995. this._onCanvasBlurObserver = null;
  46996. }
  46997. this._keys = [];
  46998. };
  46999. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47000. if (this._onKeyboardObserver) {
  47001. var camera = this.camera;
  47002. // Keyboard
  47003. for (var index = 0; index < this._keys.length; index++) {
  47004. var keyCode = this._keys[index];
  47005. var speed = camera._computeLocalCameraSpeed();
  47006. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47007. camera._localDirection.copyFromFloats(-speed, 0, 0);
  47008. }
  47009. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47010. camera._localDirection.copyFromFloats(0, 0, speed);
  47011. }
  47012. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47013. camera._localDirection.copyFromFloats(speed, 0, 0);
  47014. }
  47015. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47016. camera._localDirection.copyFromFloats(0, 0, -speed);
  47017. }
  47018. if (camera.getScene().useRightHandedSystem) {
  47019. camera._localDirection.z *= -1;
  47020. }
  47021. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  47022. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  47023. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47024. }
  47025. }
  47026. };
  47027. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47028. return "FreeCameraKeyboardMoveInput";
  47029. };
  47030. /** @hidden */
  47031. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47032. this._keys = [];
  47033. };
  47034. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47035. return "keyboard";
  47036. };
  47037. __decorate([
  47038. BABYLON.serialize()
  47039. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47040. __decorate([
  47041. BABYLON.serialize()
  47042. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47043. __decorate([
  47044. BABYLON.serialize()
  47045. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47046. __decorate([
  47047. BABYLON.serialize()
  47048. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47049. return FreeCameraKeyboardMoveInput;
  47050. }());
  47051. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47052. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47053. })(BABYLON || (BABYLON = {}));
  47054. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47055. var BABYLON;
  47056. (function (BABYLON) {
  47057. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47058. __extends(FreeCameraInputsManager, _super);
  47059. function FreeCameraInputsManager(camera) {
  47060. return _super.call(this, camera) || this;
  47061. }
  47062. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47063. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47064. return this;
  47065. };
  47066. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47067. if (touchEnabled === void 0) { touchEnabled = true; }
  47068. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47069. return this;
  47070. };
  47071. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47072. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47073. return this;
  47074. };
  47075. FreeCameraInputsManager.prototype.addTouch = function () {
  47076. this.add(new BABYLON.FreeCameraTouchInput());
  47077. return this;
  47078. };
  47079. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47080. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47081. return this;
  47082. };
  47083. return FreeCameraInputsManager;
  47084. }(BABYLON.CameraInputsManager));
  47085. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47086. })(BABYLON || (BABYLON = {}));
  47087. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47088. var BABYLON;
  47089. (function (BABYLON) {
  47090. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  47091. // Forcing to use the Universal camera
  47092. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  47093. });
  47094. var FreeCamera = /** @class */ (function (_super) {
  47095. __extends(FreeCamera, _super);
  47096. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47097. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47098. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47099. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47100. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47101. _this.checkCollisions = false;
  47102. _this.applyGravity = false;
  47103. _this._needMoveForGravity = false;
  47104. _this._oldPosition = BABYLON.Vector3.Zero();
  47105. _this._diffPosition = BABYLON.Vector3.Zero();
  47106. _this._newPosition = BABYLON.Vector3.Zero();
  47107. // Collisions
  47108. _this._collisionMask = -1;
  47109. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47110. if (collidedMesh === void 0) { collidedMesh = null; }
  47111. //TODO move this to the collision coordinator!
  47112. if (_this.getScene().workerCollisions)
  47113. newPosition.multiplyInPlace(_this._collider._radius);
  47114. var updatePosition = function (newPos) {
  47115. _this._newPosition.copyFrom(newPos);
  47116. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  47117. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  47118. _this.position.addInPlace(_this._diffPosition);
  47119. if (_this.onCollide && collidedMesh) {
  47120. _this.onCollide(collidedMesh);
  47121. }
  47122. }
  47123. };
  47124. updatePosition(newPosition);
  47125. };
  47126. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47127. _this.inputs.addKeyboard().addMouse();
  47128. return _this;
  47129. }
  47130. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  47131. //-- begin properties for backward compatibility for inputs
  47132. /**
  47133. * Gets the input sensibility for a mouse input. (default is 2000.0)
  47134. * Higher values reduce sensitivity.
  47135. */
  47136. get: function () {
  47137. var mouse = this.inputs.attached["mouse"];
  47138. if (mouse)
  47139. return mouse.angularSensibility;
  47140. return 0;
  47141. },
  47142. /**
  47143. * Sets the input sensibility for a mouse input. (default is 2000.0)
  47144. * Higher values reduce sensitivity.
  47145. */
  47146. set: function (value) {
  47147. var mouse = this.inputs.attached["mouse"];
  47148. if (mouse)
  47149. mouse.angularSensibility = value;
  47150. },
  47151. enumerable: true,
  47152. configurable: true
  47153. });
  47154. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  47155. get: function () {
  47156. var keyboard = this.inputs.attached["keyboard"];
  47157. if (keyboard)
  47158. return keyboard.keysUp;
  47159. return [];
  47160. },
  47161. set: function (value) {
  47162. var keyboard = this.inputs.attached["keyboard"];
  47163. if (keyboard)
  47164. keyboard.keysUp = value;
  47165. },
  47166. enumerable: true,
  47167. configurable: true
  47168. });
  47169. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  47170. get: function () {
  47171. var keyboard = this.inputs.attached["keyboard"];
  47172. if (keyboard)
  47173. return keyboard.keysDown;
  47174. return [];
  47175. },
  47176. set: function (value) {
  47177. var keyboard = this.inputs.attached["keyboard"];
  47178. if (keyboard)
  47179. keyboard.keysDown = value;
  47180. },
  47181. enumerable: true,
  47182. configurable: true
  47183. });
  47184. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47185. get: function () {
  47186. var keyboard = this.inputs.attached["keyboard"];
  47187. if (keyboard)
  47188. return keyboard.keysLeft;
  47189. return [];
  47190. },
  47191. set: function (value) {
  47192. var keyboard = this.inputs.attached["keyboard"];
  47193. if (keyboard)
  47194. keyboard.keysLeft = value;
  47195. },
  47196. enumerable: true,
  47197. configurable: true
  47198. });
  47199. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  47200. get: function () {
  47201. var keyboard = this.inputs.attached["keyboard"];
  47202. if (keyboard)
  47203. return keyboard.keysRight;
  47204. return [];
  47205. },
  47206. set: function (value) {
  47207. var keyboard = this.inputs.attached["keyboard"];
  47208. if (keyboard)
  47209. keyboard.keysRight = value;
  47210. },
  47211. enumerable: true,
  47212. configurable: true
  47213. });
  47214. // Controls
  47215. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47216. this.inputs.attachElement(element, noPreventDefault);
  47217. };
  47218. FreeCamera.prototype.detachControl = function (element) {
  47219. this.inputs.detachElement(element);
  47220. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47221. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47222. };
  47223. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47224. get: function () {
  47225. return this._collisionMask;
  47226. },
  47227. set: function (mask) {
  47228. this._collisionMask = !isNaN(mask) ? mask : -1;
  47229. },
  47230. enumerable: true,
  47231. configurable: true
  47232. });
  47233. /** @hidden */
  47234. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47235. var globalPosition;
  47236. if (this.parent) {
  47237. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47238. }
  47239. else {
  47240. globalPosition = this.position;
  47241. }
  47242. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47243. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47244. if (!this._collider) {
  47245. this._collider = new BABYLON.Collider();
  47246. }
  47247. this._collider._radius = this.ellipsoid;
  47248. this._collider.collisionMask = this._collisionMask;
  47249. //no need for clone, as long as gravity is not on.
  47250. var actualDisplacement = displacement;
  47251. //add gravity to the direction to prevent the dual-collision checking
  47252. if (this.applyGravity) {
  47253. //this prevents mending with cameraDirection, a global variable of the free camera class.
  47254. actualDisplacement = displacement.add(this.getScene().gravity);
  47255. }
  47256. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47257. };
  47258. /** @hidden */
  47259. FreeCamera.prototype._checkInputs = function () {
  47260. if (!this._localDirection) {
  47261. this._localDirection = BABYLON.Vector3.Zero();
  47262. this._transformedDirection = BABYLON.Vector3.Zero();
  47263. }
  47264. this.inputs.checkInputs();
  47265. _super.prototype._checkInputs.call(this);
  47266. };
  47267. /** @hidden */
  47268. FreeCamera.prototype._decideIfNeedsToMove = function () {
  47269. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47270. };
  47271. /** @hidden */
  47272. FreeCamera.prototype._updatePosition = function () {
  47273. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  47274. this._collideWithWorld(this.cameraDirection);
  47275. }
  47276. else {
  47277. _super.prototype._updatePosition.call(this);
  47278. }
  47279. };
  47280. FreeCamera.prototype.dispose = function () {
  47281. this.inputs.clear();
  47282. _super.prototype.dispose.call(this);
  47283. };
  47284. FreeCamera.prototype.getClassName = function () {
  47285. return "FreeCamera";
  47286. };
  47287. __decorate([
  47288. BABYLON.serializeAsVector3()
  47289. ], FreeCamera.prototype, "ellipsoid", void 0);
  47290. __decorate([
  47291. BABYLON.serializeAsVector3()
  47292. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  47293. __decorate([
  47294. BABYLON.serialize()
  47295. ], FreeCamera.prototype, "checkCollisions", void 0);
  47296. __decorate([
  47297. BABYLON.serialize()
  47298. ], FreeCamera.prototype, "applyGravity", void 0);
  47299. return FreeCamera;
  47300. }(BABYLON.TargetCamera));
  47301. BABYLON.FreeCamera = FreeCamera;
  47302. })(BABYLON || (BABYLON = {}));
  47303. //# sourceMappingURL=babylon.freeCamera.js.map
  47304. var BABYLON;
  47305. (function (BABYLON) {
  47306. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47307. function ArcRotateCameraKeyboardMoveInput() {
  47308. this._keys = new Array();
  47309. this.keysUp = [38];
  47310. this.keysDown = [40];
  47311. this.keysLeft = [37];
  47312. this.keysRight = [39];
  47313. this.keysReset = [220];
  47314. this.panningSensibility = 50.0;
  47315. this.zoomingSensibility = 25.0;
  47316. this.useAltToZoom = true;
  47317. }
  47318. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47319. var _this = this;
  47320. if (this._onCanvasBlurObserver) {
  47321. return;
  47322. }
  47323. this._scene = this.camera.getScene();
  47324. this._engine = this._scene.getEngine();
  47325. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47326. _this._keys = [];
  47327. });
  47328. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47329. var evt = info.event;
  47330. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47331. _this._ctrlPressed = evt.ctrlKey;
  47332. _this._altPressed = evt.altKey;
  47333. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47334. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47335. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47336. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47337. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47338. var index = _this._keys.indexOf(evt.keyCode);
  47339. if (index === -1) {
  47340. _this._keys.push(evt.keyCode);
  47341. }
  47342. if (evt.preventDefault) {
  47343. if (!noPreventDefault) {
  47344. evt.preventDefault();
  47345. }
  47346. }
  47347. }
  47348. }
  47349. else {
  47350. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47351. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47352. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47353. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47354. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47355. var index = _this._keys.indexOf(evt.keyCode);
  47356. if (index >= 0) {
  47357. _this._keys.splice(index, 1);
  47358. }
  47359. if (evt.preventDefault) {
  47360. if (!noPreventDefault) {
  47361. evt.preventDefault();
  47362. }
  47363. }
  47364. }
  47365. }
  47366. });
  47367. };
  47368. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47369. if (this._scene) {
  47370. if (this._onKeyboardObserver) {
  47371. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47372. }
  47373. if (this._onCanvasBlurObserver) {
  47374. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47375. }
  47376. this._onKeyboardObserver = null;
  47377. this._onCanvasBlurObserver = null;
  47378. }
  47379. this._keys = [];
  47380. };
  47381. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47382. if (this._onKeyboardObserver) {
  47383. var camera = this.camera;
  47384. for (var index = 0; index < this._keys.length; index++) {
  47385. var keyCode = this._keys[index];
  47386. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47387. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47388. camera.inertialPanningX -= 1 / this.panningSensibility;
  47389. }
  47390. else {
  47391. camera.inertialAlphaOffset -= 0.01;
  47392. }
  47393. }
  47394. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47395. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47396. camera.inertialPanningY += 1 / this.panningSensibility;
  47397. }
  47398. else if (this._altPressed && this.useAltToZoom) {
  47399. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47400. }
  47401. else {
  47402. camera.inertialBetaOffset -= 0.01;
  47403. }
  47404. }
  47405. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47406. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47407. camera.inertialPanningX += 1 / this.panningSensibility;
  47408. }
  47409. else {
  47410. camera.inertialAlphaOffset += 0.01;
  47411. }
  47412. }
  47413. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47414. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47415. camera.inertialPanningY -= 1 / this.panningSensibility;
  47416. }
  47417. else if (this._altPressed && this.useAltToZoom) {
  47418. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47419. }
  47420. else {
  47421. camera.inertialBetaOffset += 0.01;
  47422. }
  47423. }
  47424. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47425. camera.restoreState();
  47426. }
  47427. }
  47428. }
  47429. };
  47430. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47431. return "ArcRotateCameraKeyboardMoveInput";
  47432. };
  47433. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47434. return "keyboard";
  47435. };
  47436. __decorate([
  47437. BABYLON.serialize()
  47438. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47439. __decorate([
  47440. BABYLON.serialize()
  47441. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47442. __decorate([
  47443. BABYLON.serialize()
  47444. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47445. __decorate([
  47446. BABYLON.serialize()
  47447. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47448. __decorate([
  47449. BABYLON.serialize()
  47450. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47451. __decorate([
  47452. BABYLON.serialize()
  47453. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47454. __decorate([
  47455. BABYLON.serialize()
  47456. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47457. __decorate([
  47458. BABYLON.serialize()
  47459. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47460. return ArcRotateCameraKeyboardMoveInput;
  47461. }());
  47462. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47463. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47464. })(BABYLON || (BABYLON = {}));
  47465. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47466. var BABYLON;
  47467. (function (BABYLON) {
  47468. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47469. function ArcRotateCameraMouseWheelInput() {
  47470. this.wheelPrecision = 3.0;
  47471. /**
  47472. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47473. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47474. */
  47475. this.wheelDeltaPercentage = 0;
  47476. }
  47477. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47478. var _this = this;
  47479. this._wheel = function (p, s) {
  47480. //sanity check - this should be a PointerWheel event.
  47481. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47482. return;
  47483. var event = p.event;
  47484. var delta = 0;
  47485. if (event.wheelDelta) {
  47486. if (_this.wheelDeltaPercentage) {
  47487. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47488. if (event.wheelDelta > 0) {
  47489. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47490. }
  47491. else {
  47492. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47493. }
  47494. }
  47495. else {
  47496. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47497. }
  47498. }
  47499. else if (event.detail) {
  47500. delta = -event.detail / _this.wheelPrecision;
  47501. }
  47502. if (delta)
  47503. _this.camera.inertialRadiusOffset += delta;
  47504. if (event.preventDefault) {
  47505. if (!noPreventDefault) {
  47506. event.preventDefault();
  47507. }
  47508. }
  47509. };
  47510. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47511. };
  47512. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47513. if (this._observer && element) {
  47514. this.camera.getScene().onPointerObservable.remove(this._observer);
  47515. this._observer = null;
  47516. this._wheel = null;
  47517. }
  47518. };
  47519. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47520. return "ArcRotateCameraMouseWheelInput";
  47521. };
  47522. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47523. return "mousewheel";
  47524. };
  47525. __decorate([
  47526. BABYLON.serialize()
  47527. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47528. __decorate([
  47529. BABYLON.serialize()
  47530. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47531. return ArcRotateCameraMouseWheelInput;
  47532. }());
  47533. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47534. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47535. })(BABYLON || (BABYLON = {}));
  47536. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47537. var BABYLON;
  47538. (function (BABYLON) {
  47539. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47540. function ArcRotateCameraPointersInput() {
  47541. this.buttons = [0, 1, 2];
  47542. this.angularSensibilityX = 1000.0;
  47543. this.angularSensibilityY = 1000.0;
  47544. this.pinchPrecision = 12.0;
  47545. /**
  47546. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47547. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47548. */
  47549. this.pinchDeltaPercentage = 0;
  47550. this.panningSensibility = 1000.0;
  47551. this.multiTouchPanning = true;
  47552. this.multiTouchPanAndZoom = true;
  47553. this._isPanClick = false;
  47554. this.pinchInwards = true;
  47555. }
  47556. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47557. var _this = this;
  47558. var engine = this.camera.getEngine();
  47559. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47560. var pointA = null;
  47561. var pointB = null;
  47562. var previousPinchSquaredDistance = 0;
  47563. var initialDistance = 0;
  47564. var twoFingerActivityCount = 0;
  47565. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47566. this._pointerInput = function (p, s) {
  47567. var evt = p.event;
  47568. var isTouch = p.event.pointerType === "touch";
  47569. if (engine.isInVRExclusivePointerMode) {
  47570. return;
  47571. }
  47572. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47573. return;
  47574. }
  47575. var srcElement = (evt.srcElement || evt.target);
  47576. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47577. try {
  47578. srcElement.setPointerCapture(evt.pointerId);
  47579. }
  47580. catch (e) {
  47581. //Nothing to do with the error. Execution will continue.
  47582. }
  47583. // Manage panning with pan button click
  47584. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47585. // manage pointers
  47586. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47587. if (pointA === null) {
  47588. pointA = cacheSoloPointer;
  47589. }
  47590. else if (pointB === null) {
  47591. pointB = cacheSoloPointer;
  47592. }
  47593. if (!noPreventDefault) {
  47594. evt.preventDefault();
  47595. element.focus();
  47596. }
  47597. }
  47598. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47599. _this.camera.restoreState();
  47600. }
  47601. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47602. try {
  47603. srcElement.releasePointerCapture(evt.pointerId);
  47604. }
  47605. catch (e) {
  47606. //Nothing to do with the error.
  47607. }
  47608. cacheSoloPointer = null;
  47609. previousPinchSquaredDistance = 0;
  47610. previousMultiTouchPanPosition.isPaning = false;
  47611. previousMultiTouchPanPosition.isPinching = false;
  47612. twoFingerActivityCount = 0;
  47613. initialDistance = 0;
  47614. if (!isTouch) {
  47615. pointB = null; // Mouse and pen are mono pointer
  47616. }
  47617. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47618. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47619. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47620. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47621. if (engine._badOS) {
  47622. pointA = pointB = null;
  47623. }
  47624. else {
  47625. //only remove the impacted pointer in case of multitouch allowing on most
  47626. //platforms switching from rotate to zoom and pan seamlessly.
  47627. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47628. pointA = pointB;
  47629. pointB = null;
  47630. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47631. }
  47632. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47633. pointB = null;
  47634. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47635. }
  47636. else {
  47637. pointA = pointB = null;
  47638. }
  47639. }
  47640. if (!noPreventDefault) {
  47641. evt.preventDefault();
  47642. }
  47643. }
  47644. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47645. if (!noPreventDefault) {
  47646. evt.preventDefault();
  47647. }
  47648. // One button down
  47649. if (pointA && pointB === null && cacheSoloPointer) {
  47650. if (_this.panningSensibility !== 0 &&
  47651. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47652. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47653. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47654. }
  47655. else {
  47656. var offsetX = evt.clientX - cacheSoloPointer.x;
  47657. var offsetY = evt.clientY - cacheSoloPointer.y;
  47658. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47659. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47660. }
  47661. cacheSoloPointer.x = evt.clientX;
  47662. cacheSoloPointer.y = evt.clientY;
  47663. }
  47664. // Two buttons down: pinch/pan
  47665. else if (pointA && pointB) {
  47666. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47667. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47668. ed.x = evt.clientX;
  47669. ed.y = evt.clientY;
  47670. var direction = _this.pinchInwards ? 1 : -1;
  47671. var distX = pointA.x - pointB.x;
  47672. var distY = pointA.y - pointB.y;
  47673. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47674. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47675. if (previousPinchSquaredDistance === 0) {
  47676. initialDistance = pinchDistance;
  47677. previousPinchSquaredDistance = pinchSquaredDistance;
  47678. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47679. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47680. return;
  47681. }
  47682. if (_this.multiTouchPanAndZoom) {
  47683. if (_this.pinchDeltaPercentage) {
  47684. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47685. }
  47686. else {
  47687. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47688. (_this.pinchPrecision *
  47689. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47690. direction);
  47691. }
  47692. if (_this.panningSensibility !== 0) {
  47693. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47694. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47695. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47696. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47697. previousMultiTouchPanPosition.x = pointersCenterX;
  47698. previousMultiTouchPanPosition.y = pointersCenterY;
  47699. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47700. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47701. }
  47702. }
  47703. else {
  47704. twoFingerActivityCount++;
  47705. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47706. if (_this.pinchDeltaPercentage) {
  47707. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47708. }
  47709. else {
  47710. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47711. (_this.pinchPrecision *
  47712. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47713. direction);
  47714. }
  47715. previousMultiTouchPanPosition.isPaning = false;
  47716. previousMultiTouchPanPosition.isPinching = true;
  47717. }
  47718. else {
  47719. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47720. if (!previousMultiTouchPanPosition.isPaning) {
  47721. previousMultiTouchPanPosition.isPaning = true;
  47722. previousMultiTouchPanPosition.isPinching = false;
  47723. previousMultiTouchPanPosition.x = ed.x;
  47724. previousMultiTouchPanPosition.y = ed.y;
  47725. return;
  47726. }
  47727. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47728. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47729. }
  47730. }
  47731. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47732. previousMultiTouchPanPosition.x = ed.x;
  47733. previousMultiTouchPanPosition.y = ed.y;
  47734. }
  47735. }
  47736. previousPinchSquaredDistance = pinchSquaredDistance;
  47737. }
  47738. }
  47739. };
  47740. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47741. this._onContextMenu = function (evt) {
  47742. evt.preventDefault();
  47743. };
  47744. if (!this.camera._useCtrlForPanning) {
  47745. element.addEventListener("contextmenu", this._onContextMenu, false);
  47746. }
  47747. this._onLostFocus = function () {
  47748. //this._keys = [];
  47749. pointA = pointB = null;
  47750. previousPinchSquaredDistance = 0;
  47751. previousMultiTouchPanPosition.isPaning = false;
  47752. previousMultiTouchPanPosition.isPinching = false;
  47753. twoFingerActivityCount = 0;
  47754. cacheSoloPointer = null;
  47755. initialDistance = 0;
  47756. };
  47757. this._onMouseMove = function (evt) {
  47758. if (!engine.isPointerLock) {
  47759. return;
  47760. }
  47761. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47762. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47763. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47764. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47765. if (!noPreventDefault) {
  47766. evt.preventDefault();
  47767. }
  47768. };
  47769. this._onGestureStart = function (e) {
  47770. if (window.MSGesture === undefined) {
  47771. return;
  47772. }
  47773. if (!_this._MSGestureHandler) {
  47774. _this._MSGestureHandler = new MSGesture();
  47775. _this._MSGestureHandler.target = element;
  47776. }
  47777. _this._MSGestureHandler.addPointer(e.pointerId);
  47778. };
  47779. this._onGesture = function (e) {
  47780. _this.camera.radius *= e.scale;
  47781. if (e.preventDefault) {
  47782. if (!noPreventDefault) {
  47783. e.stopPropagation();
  47784. e.preventDefault();
  47785. }
  47786. }
  47787. };
  47788. element.addEventListener("mousemove", this._onMouseMove, false);
  47789. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47790. element.addEventListener("MSGestureChange", this._onGesture, false);
  47791. BABYLON.Tools.RegisterTopRootEvents([
  47792. { name: "blur", handler: this._onLostFocus }
  47793. ]);
  47794. };
  47795. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47796. if (this._onLostFocus) {
  47797. BABYLON.Tools.UnregisterTopRootEvents([
  47798. { name: "blur", handler: this._onLostFocus }
  47799. ]);
  47800. }
  47801. if (element && this._observer) {
  47802. this.camera.getScene().onPointerObservable.remove(this._observer);
  47803. this._observer = null;
  47804. if (this._onContextMenu) {
  47805. element.removeEventListener("contextmenu", this._onContextMenu);
  47806. }
  47807. if (this._onMouseMove) {
  47808. element.removeEventListener("mousemove", this._onMouseMove);
  47809. }
  47810. if (this._onGestureStart) {
  47811. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47812. }
  47813. if (this._onGesture) {
  47814. element.removeEventListener("MSGestureChange", this._onGesture);
  47815. }
  47816. this._isPanClick = false;
  47817. this.pinchInwards = true;
  47818. this._onMouseMove = null;
  47819. this._onGestureStart = null;
  47820. this._onGesture = null;
  47821. this._MSGestureHandler = null;
  47822. this._onLostFocus = null;
  47823. this._onContextMenu = null;
  47824. }
  47825. };
  47826. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47827. return "ArcRotateCameraPointersInput";
  47828. };
  47829. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47830. return "pointers";
  47831. };
  47832. __decorate([
  47833. BABYLON.serialize()
  47834. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47835. __decorate([
  47836. BABYLON.serialize()
  47837. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47838. __decorate([
  47839. BABYLON.serialize()
  47840. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47841. __decorate([
  47842. BABYLON.serialize()
  47843. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47844. __decorate([
  47845. BABYLON.serialize()
  47846. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47847. __decorate([
  47848. BABYLON.serialize()
  47849. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47850. __decorate([
  47851. BABYLON.serialize()
  47852. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47853. __decorate([
  47854. BABYLON.serialize()
  47855. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47856. return ArcRotateCameraPointersInput;
  47857. }());
  47858. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47859. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47860. })(BABYLON || (BABYLON = {}));
  47861. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47862. var BABYLON;
  47863. (function (BABYLON) {
  47864. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47865. __extends(ArcRotateCameraInputsManager, _super);
  47866. function ArcRotateCameraInputsManager(camera) {
  47867. return _super.call(this, camera) || this;
  47868. }
  47869. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47870. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47871. return this;
  47872. };
  47873. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47874. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47875. return this;
  47876. };
  47877. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47878. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47879. return this;
  47880. };
  47881. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47882. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47883. return this;
  47884. };
  47885. return ArcRotateCameraInputsManager;
  47886. }(BABYLON.CameraInputsManager));
  47887. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47888. })(BABYLON || (BABYLON = {}));
  47889. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47890. var BABYLON;
  47891. (function (BABYLON) {
  47892. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  47893. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  47894. });
  47895. var ArcRotateCamera = /** @class */ (function (_super) {
  47896. __extends(ArcRotateCamera, _super);
  47897. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  47898. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47899. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  47900. _this.inertialAlphaOffset = 0;
  47901. _this.inertialBetaOffset = 0;
  47902. _this.inertialRadiusOffset = 0;
  47903. _this.lowerAlphaLimit = null;
  47904. _this.upperAlphaLimit = null;
  47905. _this.lowerBetaLimit = 0.01;
  47906. _this.upperBetaLimit = Math.PI;
  47907. _this.lowerRadiusLimit = null;
  47908. _this.upperRadiusLimit = null;
  47909. _this.inertialPanningX = 0;
  47910. _this.inertialPanningY = 0;
  47911. _this.pinchToPanMaxDistance = 20;
  47912. _this.panningDistanceLimit = null;
  47913. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47914. _this.panningInertia = 0.9;
  47915. //-- end properties for backward compatibility for inputs
  47916. _this.zoomOnFactor = 1;
  47917. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47918. _this.allowUpsideDown = true;
  47919. /** @hidden */
  47920. _this._viewMatrix = new BABYLON.Matrix();
  47921. // Panning
  47922. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47923. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47924. _this.checkCollisions = false;
  47925. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47926. _this._previousPosition = BABYLON.Vector3.Zero();
  47927. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47928. _this._newPosition = BABYLON.Vector3.Zero();
  47929. _this._computationVector = BABYLON.Vector3.Zero();
  47930. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47931. if (collidedMesh === void 0) { collidedMesh = null; }
  47932. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47933. newPosition.multiplyInPlace(_this._collider._radius);
  47934. }
  47935. if (!collidedMesh) {
  47936. _this._previousPosition.copyFrom(_this.position);
  47937. }
  47938. else {
  47939. _this.setPosition(newPosition);
  47940. if (_this.onCollide) {
  47941. _this.onCollide(collidedMesh);
  47942. }
  47943. }
  47944. // Recompute because of constraints
  47945. var cosa = Math.cos(_this.alpha);
  47946. var sina = Math.sin(_this.alpha);
  47947. var cosb = Math.cos(_this.beta);
  47948. var sinb = Math.sin(_this.beta);
  47949. if (sinb === 0) {
  47950. sinb = 0.0001;
  47951. }
  47952. var target = _this._getTargetPosition();
  47953. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47954. target.addToRef(_this._computationVector, _this._newPosition);
  47955. _this.position.copyFrom(_this._newPosition);
  47956. var up = _this.upVector;
  47957. if (_this.allowUpsideDown && _this.beta < 0) {
  47958. up = up.clone();
  47959. up = up.negate();
  47960. }
  47961. _this._computeViewMatrix(_this.position, target, up);
  47962. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47963. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47964. _this._collisionTriggered = false;
  47965. };
  47966. _this._target = BABYLON.Vector3.Zero();
  47967. if (target) {
  47968. _this.setTarget(target);
  47969. }
  47970. _this.alpha = alpha;
  47971. _this.beta = beta;
  47972. _this.radius = radius;
  47973. _this.getViewMatrix();
  47974. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47975. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47976. return _this;
  47977. }
  47978. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47979. get: function () {
  47980. return this._target;
  47981. },
  47982. set: function (value) {
  47983. this.setTarget(value);
  47984. },
  47985. enumerable: true,
  47986. configurable: true
  47987. });
  47988. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47989. //-- begin properties for backward compatibility for inputs
  47990. get: function () {
  47991. var pointers = this.inputs.attached["pointers"];
  47992. if (pointers)
  47993. return pointers.angularSensibilityX;
  47994. return 0;
  47995. },
  47996. set: function (value) {
  47997. var pointers = this.inputs.attached["pointers"];
  47998. if (pointers) {
  47999. pointers.angularSensibilityX = value;
  48000. }
  48001. },
  48002. enumerable: true,
  48003. configurable: true
  48004. });
  48005. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48006. get: function () {
  48007. var pointers = this.inputs.attached["pointers"];
  48008. if (pointers)
  48009. return pointers.angularSensibilityY;
  48010. return 0;
  48011. },
  48012. set: function (value) {
  48013. var pointers = this.inputs.attached["pointers"];
  48014. if (pointers) {
  48015. pointers.angularSensibilityY = value;
  48016. }
  48017. },
  48018. enumerable: true,
  48019. configurable: true
  48020. });
  48021. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48022. get: function () {
  48023. var pointers = this.inputs.attached["pointers"];
  48024. if (pointers)
  48025. return pointers.pinchPrecision;
  48026. return 0;
  48027. },
  48028. set: function (value) {
  48029. var pointers = this.inputs.attached["pointers"];
  48030. if (pointers) {
  48031. pointers.pinchPrecision = value;
  48032. }
  48033. },
  48034. enumerable: true,
  48035. configurable: true
  48036. });
  48037. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48038. get: function () {
  48039. var pointers = this.inputs.attached["pointers"];
  48040. if (pointers)
  48041. return pointers.pinchDeltaPercentage;
  48042. return 0;
  48043. },
  48044. set: function (value) {
  48045. var pointers = this.inputs.attached["pointers"];
  48046. if (pointers) {
  48047. pointers.pinchDeltaPercentage = value;
  48048. }
  48049. },
  48050. enumerable: true,
  48051. configurable: true
  48052. });
  48053. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48054. get: function () {
  48055. var pointers = this.inputs.attached["pointers"];
  48056. if (pointers)
  48057. return pointers.panningSensibility;
  48058. return 0;
  48059. },
  48060. set: function (value) {
  48061. var pointers = this.inputs.attached["pointers"];
  48062. if (pointers) {
  48063. pointers.panningSensibility = value;
  48064. }
  48065. },
  48066. enumerable: true,
  48067. configurable: true
  48068. });
  48069. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48070. get: function () {
  48071. var keyboard = this.inputs.attached["keyboard"];
  48072. if (keyboard)
  48073. return keyboard.keysUp;
  48074. return [];
  48075. },
  48076. set: function (value) {
  48077. var keyboard = this.inputs.attached["keyboard"];
  48078. if (keyboard)
  48079. keyboard.keysUp = value;
  48080. },
  48081. enumerable: true,
  48082. configurable: true
  48083. });
  48084. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48085. get: function () {
  48086. var keyboard = this.inputs.attached["keyboard"];
  48087. if (keyboard)
  48088. return keyboard.keysDown;
  48089. return [];
  48090. },
  48091. set: function (value) {
  48092. var keyboard = this.inputs.attached["keyboard"];
  48093. if (keyboard)
  48094. keyboard.keysDown = value;
  48095. },
  48096. enumerable: true,
  48097. configurable: true
  48098. });
  48099. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  48100. get: function () {
  48101. var keyboard = this.inputs.attached["keyboard"];
  48102. if (keyboard)
  48103. return keyboard.keysLeft;
  48104. return [];
  48105. },
  48106. set: function (value) {
  48107. var keyboard = this.inputs.attached["keyboard"];
  48108. if (keyboard)
  48109. keyboard.keysLeft = value;
  48110. },
  48111. enumerable: true,
  48112. configurable: true
  48113. });
  48114. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  48115. get: function () {
  48116. var keyboard = this.inputs.attached["keyboard"];
  48117. if (keyboard)
  48118. return keyboard.keysRight;
  48119. return [];
  48120. },
  48121. set: function (value) {
  48122. var keyboard = this.inputs.attached["keyboard"];
  48123. if (keyboard)
  48124. keyboard.keysRight = value;
  48125. },
  48126. enumerable: true,
  48127. configurable: true
  48128. });
  48129. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48130. get: function () {
  48131. var mousewheel = this.inputs.attached["mousewheel"];
  48132. if (mousewheel)
  48133. return mousewheel.wheelPrecision;
  48134. return 0;
  48135. },
  48136. set: function (value) {
  48137. var mousewheel = this.inputs.attached["mousewheel"];
  48138. if (mousewheel)
  48139. mousewheel.wheelPrecision = value;
  48140. },
  48141. enumerable: true,
  48142. configurable: true
  48143. });
  48144. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  48145. get: function () {
  48146. var mousewheel = this.inputs.attached["mousewheel"];
  48147. if (mousewheel)
  48148. return mousewheel.wheelDeltaPercentage;
  48149. return 0;
  48150. },
  48151. set: function (value) {
  48152. var mousewheel = this.inputs.attached["mousewheel"];
  48153. if (mousewheel)
  48154. mousewheel.wheelDeltaPercentage = value;
  48155. },
  48156. enumerable: true,
  48157. configurable: true
  48158. });
  48159. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  48160. get: function () {
  48161. return this._bouncingBehavior;
  48162. },
  48163. enumerable: true,
  48164. configurable: true
  48165. });
  48166. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  48167. get: function () {
  48168. return this._bouncingBehavior != null;
  48169. },
  48170. set: function (value) {
  48171. if (value === this.useBouncingBehavior) {
  48172. return;
  48173. }
  48174. if (value) {
  48175. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  48176. this.addBehavior(this._bouncingBehavior);
  48177. }
  48178. else if (this._bouncingBehavior) {
  48179. this.removeBehavior(this._bouncingBehavior);
  48180. this._bouncingBehavior = null;
  48181. }
  48182. },
  48183. enumerable: true,
  48184. configurable: true
  48185. });
  48186. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48187. get: function () {
  48188. return this._framingBehavior;
  48189. },
  48190. enumerable: true,
  48191. configurable: true
  48192. });
  48193. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48194. get: function () {
  48195. return this._framingBehavior != null;
  48196. },
  48197. set: function (value) {
  48198. if (value === this.useFramingBehavior) {
  48199. return;
  48200. }
  48201. if (value) {
  48202. this._framingBehavior = new BABYLON.FramingBehavior();
  48203. this.addBehavior(this._framingBehavior);
  48204. }
  48205. else if (this._framingBehavior) {
  48206. this.removeBehavior(this._framingBehavior);
  48207. this._framingBehavior = null;
  48208. }
  48209. },
  48210. enumerable: true,
  48211. configurable: true
  48212. });
  48213. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  48214. get: function () {
  48215. return this._autoRotationBehavior;
  48216. },
  48217. enumerable: true,
  48218. configurable: true
  48219. });
  48220. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48221. get: function () {
  48222. return this._autoRotationBehavior != null;
  48223. },
  48224. set: function (value) {
  48225. if (value === this.useAutoRotationBehavior) {
  48226. return;
  48227. }
  48228. if (value) {
  48229. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48230. this.addBehavior(this._autoRotationBehavior);
  48231. }
  48232. else if (this._autoRotationBehavior) {
  48233. this.removeBehavior(this._autoRotationBehavior);
  48234. this._autoRotationBehavior = null;
  48235. }
  48236. },
  48237. enumerable: true,
  48238. configurable: true
  48239. });
  48240. // Cache
  48241. /** @hidden */
  48242. ArcRotateCamera.prototype._initCache = function () {
  48243. _super.prototype._initCache.call(this);
  48244. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48245. this._cache.alpha = undefined;
  48246. this._cache.beta = undefined;
  48247. this._cache.radius = undefined;
  48248. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  48249. };
  48250. /** @hidden */
  48251. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  48252. if (!ignoreParentClass) {
  48253. _super.prototype._updateCache.call(this);
  48254. }
  48255. this._cache._target.copyFrom(this._getTargetPosition());
  48256. this._cache.alpha = this.alpha;
  48257. this._cache.beta = this.beta;
  48258. this._cache.radius = this.radius;
  48259. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  48260. };
  48261. ArcRotateCamera.prototype._getTargetPosition = function () {
  48262. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  48263. var pos = this._targetHost.getAbsolutePosition();
  48264. if (this._targetBoundingCenter) {
  48265. pos.addToRef(this._targetBoundingCenter, this._target);
  48266. }
  48267. else {
  48268. this._target.copyFrom(pos);
  48269. }
  48270. }
  48271. var lockedTargetPosition = this._getLockedTargetPosition();
  48272. if (lockedTargetPosition) {
  48273. return lockedTargetPosition;
  48274. }
  48275. return this._target;
  48276. };
  48277. ArcRotateCamera.prototype.storeState = function () {
  48278. this._storedAlpha = this.alpha;
  48279. this._storedBeta = this.beta;
  48280. this._storedRadius = this.radius;
  48281. this._storedTarget = this._getTargetPosition().clone();
  48282. return _super.prototype.storeState.call(this);
  48283. };
  48284. /**
  48285. * @hidden
  48286. * Restored camera state. You must call storeState() first
  48287. */
  48288. ArcRotateCamera.prototype._restoreStateValues = function () {
  48289. if (!_super.prototype._restoreStateValues.call(this)) {
  48290. return false;
  48291. }
  48292. this.alpha = this._storedAlpha;
  48293. this.beta = this._storedBeta;
  48294. this.radius = this._storedRadius;
  48295. this.setTarget(this._storedTarget.clone());
  48296. this.inertialAlphaOffset = 0;
  48297. this.inertialBetaOffset = 0;
  48298. this.inertialRadiusOffset = 0;
  48299. this.inertialPanningX = 0;
  48300. this.inertialPanningY = 0;
  48301. return true;
  48302. };
  48303. // Synchronized
  48304. /** @hidden */
  48305. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  48306. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  48307. return false;
  48308. return this._cache._target.equals(this._getTargetPosition())
  48309. && this._cache.alpha === this.alpha
  48310. && this._cache.beta === this.beta
  48311. && this._cache.radius === this.radius
  48312. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  48313. };
  48314. // Methods
  48315. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  48316. var _this = this;
  48317. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  48318. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  48319. this._useCtrlForPanning = useCtrlForPanning;
  48320. this._panningMouseButton = panningMouseButton;
  48321. this.inputs.attachElement(element, noPreventDefault);
  48322. this._reset = function () {
  48323. _this.inertialAlphaOffset = 0;
  48324. _this.inertialBetaOffset = 0;
  48325. _this.inertialRadiusOffset = 0;
  48326. _this.inertialPanningX = 0;
  48327. _this.inertialPanningY = 0;
  48328. };
  48329. };
  48330. ArcRotateCamera.prototype.detachControl = function (element) {
  48331. this.inputs.detachElement(element);
  48332. if (this._reset) {
  48333. this._reset();
  48334. }
  48335. };
  48336. /** @hidden */
  48337. ArcRotateCamera.prototype._checkInputs = function () {
  48338. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48339. if (this._collisionTriggered) {
  48340. return;
  48341. }
  48342. this.inputs.checkInputs();
  48343. // Inertia
  48344. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48345. var inertialAlphaOffset = this.inertialAlphaOffset;
  48346. if (this.beta <= 0)
  48347. inertialAlphaOffset *= -1;
  48348. if (this.getScene().useRightHandedSystem)
  48349. inertialAlphaOffset *= -1;
  48350. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  48351. inertialAlphaOffset *= -1;
  48352. this.alpha += inertialAlphaOffset;
  48353. this.beta += this.inertialBetaOffset;
  48354. this.radius -= this.inertialRadiusOffset;
  48355. this.inertialAlphaOffset *= this.inertia;
  48356. this.inertialBetaOffset *= this.inertia;
  48357. this.inertialRadiusOffset *= this.inertia;
  48358. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48359. this.inertialAlphaOffset = 0;
  48360. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48361. this.inertialBetaOffset = 0;
  48362. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48363. this.inertialRadiusOffset = 0;
  48364. }
  48365. // Panning inertia
  48366. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48367. if (!this._localDirection) {
  48368. this._localDirection = BABYLON.Vector3.Zero();
  48369. this._transformedDirection = BABYLON.Vector3.Zero();
  48370. }
  48371. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48372. this._localDirection.multiplyInPlace(this.panningAxis);
  48373. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48374. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48375. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48376. if (!this.panningAxis.y) {
  48377. this._transformedDirection.y = 0;
  48378. }
  48379. if (!this._targetHost) {
  48380. if (this.panningDistanceLimit) {
  48381. this._transformedDirection.addInPlace(this._target);
  48382. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48383. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48384. this._target.copyFrom(this._transformedDirection);
  48385. }
  48386. }
  48387. else {
  48388. this._target.addInPlace(this._transformedDirection);
  48389. }
  48390. }
  48391. this.inertialPanningX *= this.panningInertia;
  48392. this.inertialPanningY *= this.panningInertia;
  48393. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48394. this.inertialPanningX = 0;
  48395. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48396. this.inertialPanningY = 0;
  48397. }
  48398. // Limits
  48399. this._checkLimits();
  48400. _super.prototype._checkInputs.call(this);
  48401. };
  48402. ArcRotateCamera.prototype._checkLimits = function () {
  48403. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48404. if (this.allowUpsideDown && this.beta > Math.PI) {
  48405. this.beta = this.beta - (2 * Math.PI);
  48406. }
  48407. }
  48408. else {
  48409. if (this.beta < this.lowerBetaLimit) {
  48410. this.beta = this.lowerBetaLimit;
  48411. }
  48412. }
  48413. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48414. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48415. this.beta = this.beta + (2 * Math.PI);
  48416. }
  48417. }
  48418. else {
  48419. if (this.beta > this.upperBetaLimit) {
  48420. this.beta = this.upperBetaLimit;
  48421. }
  48422. }
  48423. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  48424. this.alpha = this.lowerAlphaLimit;
  48425. }
  48426. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  48427. this.alpha = this.upperAlphaLimit;
  48428. }
  48429. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  48430. this.radius = this.lowerRadiusLimit;
  48431. }
  48432. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  48433. this.radius = this.upperRadiusLimit;
  48434. }
  48435. };
  48436. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48437. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48438. this.radius = this._computationVector.length();
  48439. if (this.radius === 0) {
  48440. this.radius = 0.0001; // Just to avoid division by zero
  48441. }
  48442. // Alpha
  48443. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48444. if (this._computationVector.z < 0) {
  48445. this.alpha = 2 * Math.PI - this.alpha;
  48446. }
  48447. // Beta
  48448. this.beta = Math.acos(this._computationVector.y / this.radius);
  48449. this._checkLimits();
  48450. };
  48451. ArcRotateCamera.prototype.setPosition = function (position) {
  48452. if (this.position.equals(position)) {
  48453. return;
  48454. }
  48455. this.position.copyFrom(position);
  48456. this.rebuildAnglesAndRadius();
  48457. };
  48458. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48459. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48460. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48461. if (target.getBoundingInfo) {
  48462. if (toBoundingCenter) {
  48463. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48464. }
  48465. else {
  48466. this._targetBoundingCenter = null;
  48467. }
  48468. this._targetHost = target;
  48469. this._target = this._getTargetPosition();
  48470. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48471. }
  48472. else {
  48473. var newTarget = target;
  48474. var currentTarget = this._getTargetPosition();
  48475. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48476. return;
  48477. }
  48478. this._targetHost = null;
  48479. this._target = newTarget;
  48480. this._targetBoundingCenter = null;
  48481. this.onMeshTargetChangedObservable.notifyObservers(null);
  48482. }
  48483. this.rebuildAnglesAndRadius();
  48484. };
  48485. /** @hidden */
  48486. ArcRotateCamera.prototype._getViewMatrix = function () {
  48487. // Compute
  48488. var cosa = Math.cos(this.alpha);
  48489. var sina = Math.sin(this.alpha);
  48490. var cosb = Math.cos(this.beta);
  48491. var sinb = Math.sin(this.beta);
  48492. if (sinb === 0) {
  48493. sinb = 0.0001;
  48494. }
  48495. var target = this._getTargetPosition();
  48496. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48497. target.addToRef(this._computationVector, this._newPosition);
  48498. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48499. if (!this._collider) {
  48500. this._collider = new BABYLON.Collider();
  48501. }
  48502. this._collider._radius = this.collisionRadius;
  48503. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48504. this._collisionTriggered = true;
  48505. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48506. }
  48507. else {
  48508. this.position.copyFrom(this._newPosition);
  48509. var up = this.upVector;
  48510. if (this.allowUpsideDown && sinb < 0) {
  48511. up = up.clone();
  48512. up = up.negate();
  48513. }
  48514. this._computeViewMatrix(this.position, target, up);
  48515. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48516. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48517. }
  48518. this._currentTarget = target;
  48519. return this._viewMatrix;
  48520. };
  48521. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48522. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48523. meshes = meshes || this.getScene().meshes;
  48524. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48525. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48526. this.radius = distance * this.zoomOnFactor;
  48527. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48528. };
  48529. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48530. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48531. var meshesOrMinMaxVector;
  48532. var distance;
  48533. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48534. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48535. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48536. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48537. }
  48538. else { //minMaxVector and distance
  48539. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48540. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48541. distance = minMaxVectorAndDistance.distance;
  48542. }
  48543. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48544. if (!doNotUpdateMaxZ) {
  48545. this.maxZ = distance * 2;
  48546. }
  48547. };
  48548. /**
  48549. * @override
  48550. * Override Camera.createRigCamera
  48551. */
  48552. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48553. var alphaShift = 0;
  48554. switch (this.cameraRigMode) {
  48555. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48556. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48557. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48558. case BABYLON.Camera.RIG_MODE_VR:
  48559. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48560. break;
  48561. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48562. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48563. break;
  48564. }
  48565. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48566. rigCam._cameraRigParams = {};
  48567. return rigCam;
  48568. };
  48569. /**
  48570. * @hidden
  48571. * @override
  48572. * Override Camera._updateRigCameras
  48573. */
  48574. ArcRotateCamera.prototype._updateRigCameras = function () {
  48575. var camLeft = this._rigCameras[0];
  48576. var camRight = this._rigCameras[1];
  48577. camLeft.beta = camRight.beta = this.beta;
  48578. camLeft.radius = camRight.radius = this.radius;
  48579. switch (this.cameraRigMode) {
  48580. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48581. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48582. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48583. case BABYLON.Camera.RIG_MODE_VR:
  48584. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48585. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48586. break;
  48587. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48588. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48589. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48590. break;
  48591. }
  48592. _super.prototype._updateRigCameras.call(this);
  48593. };
  48594. ArcRotateCamera.prototype.dispose = function () {
  48595. this.inputs.clear();
  48596. _super.prototype.dispose.call(this);
  48597. };
  48598. ArcRotateCamera.prototype.getClassName = function () {
  48599. return "ArcRotateCamera";
  48600. };
  48601. __decorate([
  48602. BABYLON.serialize()
  48603. ], ArcRotateCamera.prototype, "alpha", void 0);
  48604. __decorate([
  48605. BABYLON.serialize()
  48606. ], ArcRotateCamera.prototype, "beta", void 0);
  48607. __decorate([
  48608. BABYLON.serialize()
  48609. ], ArcRotateCamera.prototype, "radius", void 0);
  48610. __decorate([
  48611. BABYLON.serializeAsVector3("target")
  48612. ], ArcRotateCamera.prototype, "_target", void 0);
  48613. __decorate([
  48614. BABYLON.serialize()
  48615. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48616. __decorate([
  48617. BABYLON.serialize()
  48618. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48619. __decorate([
  48620. BABYLON.serialize()
  48621. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48622. __decorate([
  48623. BABYLON.serialize()
  48624. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48625. __decorate([
  48626. BABYLON.serialize()
  48627. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48628. __decorate([
  48629. BABYLON.serialize()
  48630. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48631. __decorate([
  48632. BABYLON.serialize()
  48633. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48634. __decorate([
  48635. BABYLON.serialize()
  48636. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48637. __decorate([
  48638. BABYLON.serialize()
  48639. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48640. __decorate([
  48641. BABYLON.serialize()
  48642. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48643. __decorate([
  48644. BABYLON.serialize()
  48645. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48646. __decorate([
  48647. BABYLON.serialize()
  48648. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48649. __decorate([
  48650. BABYLON.serialize()
  48651. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48652. __decorate([
  48653. BABYLON.serializeAsVector3()
  48654. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48655. __decorate([
  48656. BABYLON.serialize()
  48657. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48658. __decorate([
  48659. BABYLON.serialize()
  48660. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48661. __decorate([
  48662. BABYLON.serialize()
  48663. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48664. return ArcRotateCamera;
  48665. }(BABYLON.TargetCamera));
  48666. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48667. })(BABYLON || (BABYLON = {}));
  48668. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48669. var BABYLON;
  48670. (function (BABYLON) {
  48671. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  48672. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  48673. });
  48674. /**
  48675. * The HemisphericLight simulates the ambient environment light,
  48676. * so the passed direction is the light reflection direction, not the incoming direction.
  48677. */
  48678. var HemisphericLight = /** @class */ (function (_super) {
  48679. __extends(HemisphericLight, _super);
  48680. /**
  48681. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48682. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48683. * The HemisphericLight can't cast shadows.
  48684. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48685. * @param name The friendly name of the light
  48686. * @param direction The direction of the light reflection
  48687. * @param scene The scene the light belongs to
  48688. */
  48689. function HemisphericLight(name, direction, scene) {
  48690. var _this = _super.call(this, name, scene) || this;
  48691. /**
  48692. * The groundColor is the light in the opposite direction to the one specified during creation.
  48693. * 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.
  48694. */
  48695. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48696. _this.direction = direction || BABYLON.Vector3.Up();
  48697. return _this;
  48698. }
  48699. HemisphericLight.prototype._buildUniformLayout = function () {
  48700. this._uniformBuffer.addUniform("vLightData", 4);
  48701. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48702. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48703. this._uniformBuffer.addUniform("vLightGround", 3);
  48704. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48705. this._uniformBuffer.addUniform("depthValues", 2);
  48706. this._uniformBuffer.create();
  48707. };
  48708. /**
  48709. * Returns the string "HemisphericLight".
  48710. * @return The class name
  48711. */
  48712. HemisphericLight.prototype.getClassName = function () {
  48713. return "HemisphericLight";
  48714. };
  48715. /**
  48716. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48717. * Returns the updated direction.
  48718. * @param target The target the direction should point to
  48719. * @return The computed direction
  48720. */
  48721. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48722. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48723. return this.direction;
  48724. };
  48725. /**
  48726. * Returns the shadow generator associated to the light.
  48727. * @returns Always null for hemispheric lights because it does not support shadows.
  48728. */
  48729. HemisphericLight.prototype.getShadowGenerator = function () {
  48730. return null;
  48731. };
  48732. /**
  48733. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48734. * @param effect The effect to update
  48735. * @param lightIndex The index of the light in the effect to update
  48736. * @returns The hemispheric light
  48737. */
  48738. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48739. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48740. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48741. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48742. return this;
  48743. };
  48744. /**
  48745. * @hidden internal use only.
  48746. */
  48747. HemisphericLight.prototype._getWorldMatrix = function () {
  48748. if (!this._worldMatrix) {
  48749. this._worldMatrix = BABYLON.Matrix.Identity();
  48750. }
  48751. return this._worldMatrix;
  48752. };
  48753. /**
  48754. * Returns the integer 3.
  48755. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48756. */
  48757. HemisphericLight.prototype.getTypeID = function () {
  48758. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48759. };
  48760. /**
  48761. * Prepares the list of defines specific to the light type.
  48762. * @param defines the list of defines
  48763. * @param lightIndex defines the index of the light for the effect
  48764. */
  48765. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48766. defines["HEMILIGHT" + lightIndex] = true;
  48767. };
  48768. __decorate([
  48769. BABYLON.serializeAsColor3()
  48770. ], HemisphericLight.prototype, "groundColor", void 0);
  48771. __decorate([
  48772. BABYLON.serializeAsVector3()
  48773. ], HemisphericLight.prototype, "direction", void 0);
  48774. return HemisphericLight;
  48775. }(BABYLON.Light));
  48776. BABYLON.HemisphericLight = HemisphericLight;
  48777. })(BABYLON || (BABYLON = {}));
  48778. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48779. var BABYLON;
  48780. (function (BABYLON) {
  48781. /**
  48782. * Base implementation IShadowLight
  48783. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48784. */
  48785. var ShadowLight = /** @class */ (function (_super) {
  48786. __extends(ShadowLight, _super);
  48787. function ShadowLight() {
  48788. var _this = _super !== null && _super.apply(this, arguments) || this;
  48789. _this._needProjectionMatrixCompute = true;
  48790. return _this;
  48791. }
  48792. ShadowLight.prototype._setPosition = function (value) {
  48793. this._position = value;
  48794. };
  48795. Object.defineProperty(ShadowLight.prototype, "position", {
  48796. /**
  48797. * Sets the position the shadow will be casted from. Also use as the light position for both
  48798. * point and spot lights.
  48799. */
  48800. get: function () {
  48801. return this._position;
  48802. },
  48803. /**
  48804. * Sets the position the shadow will be casted from. Also use as the light position for both
  48805. * point and spot lights.
  48806. */
  48807. set: function (value) {
  48808. this._setPosition(value);
  48809. },
  48810. enumerable: true,
  48811. configurable: true
  48812. });
  48813. ShadowLight.prototype._setDirection = function (value) {
  48814. this._direction = value;
  48815. };
  48816. Object.defineProperty(ShadowLight.prototype, "direction", {
  48817. /**
  48818. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48819. * Also use as the light direction on spot and directional lights.
  48820. */
  48821. get: function () {
  48822. return this._direction;
  48823. },
  48824. /**
  48825. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48826. * Also use as the light direction on spot and directional lights.
  48827. */
  48828. set: function (value) {
  48829. this._setDirection(value);
  48830. },
  48831. enumerable: true,
  48832. configurable: true
  48833. });
  48834. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48835. /**
  48836. * Gets the shadow projection clipping minimum z value.
  48837. */
  48838. get: function () {
  48839. return this._shadowMinZ;
  48840. },
  48841. /**
  48842. * Sets the shadow projection clipping minimum z value.
  48843. */
  48844. set: function (value) {
  48845. this._shadowMinZ = value;
  48846. this.forceProjectionMatrixCompute();
  48847. },
  48848. enumerable: true,
  48849. configurable: true
  48850. });
  48851. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48852. /**
  48853. * Sets the shadow projection clipping maximum z value.
  48854. */
  48855. get: function () {
  48856. return this._shadowMaxZ;
  48857. },
  48858. /**
  48859. * Gets the shadow projection clipping maximum z value.
  48860. */
  48861. set: function (value) {
  48862. this._shadowMaxZ = value;
  48863. this.forceProjectionMatrixCompute();
  48864. },
  48865. enumerable: true,
  48866. configurable: true
  48867. });
  48868. /**
  48869. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48870. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48871. */
  48872. ShadowLight.prototype.computeTransformedInformation = function () {
  48873. if (this.parent && this.parent.getWorldMatrix) {
  48874. if (!this.transformedPosition) {
  48875. this.transformedPosition = BABYLON.Vector3.Zero();
  48876. }
  48877. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48878. // In case the direction is present.
  48879. if (this.direction) {
  48880. if (!this.transformedDirection) {
  48881. this.transformedDirection = BABYLON.Vector3.Zero();
  48882. }
  48883. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48884. }
  48885. return true;
  48886. }
  48887. return false;
  48888. };
  48889. /**
  48890. * Return the depth scale used for the shadow map.
  48891. * @returns the depth scale.
  48892. */
  48893. ShadowLight.prototype.getDepthScale = function () {
  48894. return 50.0;
  48895. };
  48896. /**
  48897. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48898. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48899. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48900. */
  48901. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48902. return this.transformedDirection ? this.transformedDirection : this.direction;
  48903. };
  48904. /**
  48905. * Returns the ShadowLight absolute position in the World.
  48906. * @returns the position vector in world space
  48907. */
  48908. ShadowLight.prototype.getAbsolutePosition = function () {
  48909. return this.transformedPosition ? this.transformedPosition : this.position;
  48910. };
  48911. /**
  48912. * Sets the ShadowLight direction toward the passed target.
  48913. * @param target The point tot target in local space
  48914. * @returns the updated ShadowLight direction
  48915. */
  48916. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48917. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48918. return this.direction;
  48919. };
  48920. /**
  48921. * Returns the light rotation in euler definition.
  48922. * @returns the x y z rotation in local space.
  48923. */
  48924. ShadowLight.prototype.getRotation = function () {
  48925. this.direction.normalize();
  48926. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48927. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48928. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48929. };
  48930. /**
  48931. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48932. * @returns true if a cube texture needs to be use
  48933. */
  48934. ShadowLight.prototype.needCube = function () {
  48935. return false;
  48936. };
  48937. /**
  48938. * Detects if the projection matrix requires to be recomputed this frame.
  48939. * @returns true if it requires to be recomputed otherwise, false.
  48940. */
  48941. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48942. return this._needProjectionMatrixCompute;
  48943. };
  48944. /**
  48945. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48946. */
  48947. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48948. this._needProjectionMatrixCompute = true;
  48949. };
  48950. /**
  48951. * Get the world matrix of the sahdow lights.
  48952. * @hidden Internal Use Only
  48953. */
  48954. ShadowLight.prototype._getWorldMatrix = function () {
  48955. if (!this._worldMatrix) {
  48956. this._worldMatrix = BABYLON.Matrix.Identity();
  48957. }
  48958. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48959. return this._worldMatrix;
  48960. };
  48961. /**
  48962. * Gets the minZ used for shadow according to both the scene and the light.
  48963. * @param activeCamera The camera we are returning the min for
  48964. * @returns the depth min z
  48965. */
  48966. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48967. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48968. };
  48969. /**
  48970. * Gets the maxZ used for shadow according to both the scene and the light.
  48971. * @param activeCamera The camera we are returning the max for
  48972. * @returns the depth max z
  48973. */
  48974. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48975. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48976. };
  48977. /**
  48978. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48979. * @param matrix The materix to updated with the projection information
  48980. * @param viewMatrix The transform matrix of the light
  48981. * @param renderList The list of mesh to render in the map
  48982. * @returns The current light
  48983. */
  48984. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48985. if (this.customProjectionMatrixBuilder) {
  48986. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48987. }
  48988. else {
  48989. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48990. }
  48991. return this;
  48992. };
  48993. __decorate([
  48994. BABYLON.serializeAsVector3()
  48995. ], ShadowLight.prototype, "position", null);
  48996. __decorate([
  48997. BABYLON.serializeAsVector3()
  48998. ], ShadowLight.prototype, "direction", null);
  48999. __decorate([
  49000. BABYLON.serialize()
  49001. ], ShadowLight.prototype, "shadowMinZ", null);
  49002. __decorate([
  49003. BABYLON.serialize()
  49004. ], ShadowLight.prototype, "shadowMaxZ", null);
  49005. return ShadowLight;
  49006. }(BABYLON.Light));
  49007. BABYLON.ShadowLight = ShadowLight;
  49008. })(BABYLON || (BABYLON = {}));
  49009. //# sourceMappingURL=babylon.shadowLight.js.map
  49010. var BABYLON;
  49011. (function (BABYLON) {
  49012. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  49013. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  49014. });
  49015. /**
  49016. * A point light is a light defined by an unique point in world space.
  49017. * The light is emitted in every direction from this point.
  49018. * A good example of a point light is a standard light bulb.
  49019. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49020. */
  49021. var PointLight = /** @class */ (function (_super) {
  49022. __extends(PointLight, _super);
  49023. /**
  49024. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49025. * A PointLight emits the light in every direction.
  49026. * It can cast shadows.
  49027. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49028. * ```javascript
  49029. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49030. * ```
  49031. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49032. * @param name The light friendly name
  49033. * @param position The position of the point light in the scene
  49034. * @param scene The scene the lights belongs to
  49035. */
  49036. function PointLight(name, position, scene) {
  49037. var _this = _super.call(this, name, scene) || this;
  49038. _this._shadowAngle = Math.PI / 2;
  49039. _this.position = position;
  49040. return _this;
  49041. }
  49042. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49043. /**
  49044. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49045. * This specifies what angle the shadow will use to be created.
  49046. *
  49047. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49048. */
  49049. get: function () {
  49050. return this._shadowAngle;
  49051. },
  49052. /**
  49053. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49054. * This specifies what angle the shadow will use to be created.
  49055. *
  49056. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49057. */
  49058. set: function (value) {
  49059. this._shadowAngle = value;
  49060. this.forceProjectionMatrixCompute();
  49061. },
  49062. enumerable: true,
  49063. configurable: true
  49064. });
  49065. Object.defineProperty(PointLight.prototype, "direction", {
  49066. /**
  49067. * Gets the direction if it has been set.
  49068. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49069. */
  49070. get: function () {
  49071. return this._direction;
  49072. },
  49073. /**
  49074. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49075. */
  49076. set: function (value) {
  49077. var previousNeedCube = this.needCube();
  49078. this._direction = value;
  49079. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49080. this._shadowGenerator.recreateShadowMap();
  49081. }
  49082. },
  49083. enumerable: true,
  49084. configurable: true
  49085. });
  49086. /**
  49087. * Returns the string "PointLight"
  49088. * @returns the class name
  49089. */
  49090. PointLight.prototype.getClassName = function () {
  49091. return "PointLight";
  49092. };
  49093. /**
  49094. * Returns the integer 0.
  49095. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49096. */
  49097. PointLight.prototype.getTypeID = function () {
  49098. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49099. };
  49100. /**
  49101. * Specifies wether or not the shadowmap should be a cube texture.
  49102. * @returns true if the shadowmap needs to be a cube texture.
  49103. */
  49104. PointLight.prototype.needCube = function () {
  49105. return !this.direction;
  49106. };
  49107. /**
  49108. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49109. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49110. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49111. */
  49112. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49113. if (this.direction) {
  49114. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49115. }
  49116. else {
  49117. switch (faceIndex) {
  49118. case 0:
  49119. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49120. case 1:
  49121. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49122. case 2:
  49123. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  49124. case 3:
  49125. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  49126. case 4:
  49127. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  49128. case 5:
  49129. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  49130. }
  49131. }
  49132. return BABYLON.Vector3.Zero();
  49133. };
  49134. /**
  49135. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49136. * - fov = PI / 2
  49137. * - aspect ratio : 1.0
  49138. * - z-near and far equal to the active camera minZ and maxZ.
  49139. * Returns the PointLight.
  49140. */
  49141. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49142. var activeCamera = this.getScene().activeCamera;
  49143. if (!activeCamera) {
  49144. return;
  49145. }
  49146. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49147. };
  49148. PointLight.prototype._buildUniformLayout = function () {
  49149. this._uniformBuffer.addUniform("vLightData", 4);
  49150. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49151. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49152. this._uniformBuffer.addUniform("vLightFalloff", 4);
  49153. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49154. this._uniformBuffer.addUniform("depthValues", 2);
  49155. this._uniformBuffer.create();
  49156. };
  49157. /**
  49158. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  49159. * @param effect The effect to update
  49160. * @param lightIndex The index of the light in the effect to update
  49161. * @returns The point light
  49162. */
  49163. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  49164. if (this.computeTransformedInformation()) {
  49165. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  49166. }
  49167. else {
  49168. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  49169. }
  49170. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
  49171. return this;
  49172. };
  49173. /**
  49174. * Prepares the list of defines specific to the light type.
  49175. * @param defines the list of defines
  49176. * @param lightIndex defines the index of the light for the effect
  49177. */
  49178. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49179. defines["POINTLIGHT" + lightIndex] = true;
  49180. };
  49181. __decorate([
  49182. BABYLON.serialize()
  49183. ], PointLight.prototype, "shadowAngle", null);
  49184. return PointLight;
  49185. }(BABYLON.ShadowLight));
  49186. BABYLON.PointLight = PointLight;
  49187. })(BABYLON || (BABYLON = {}));
  49188. //# sourceMappingURL=babylon.pointLight.js.map
  49189. var BABYLON;
  49190. (function (BABYLON) {
  49191. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  49192. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  49193. });
  49194. /**
  49195. * A directional light is defined by a direction (what a surprise!).
  49196. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  49197. * 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.
  49198. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49199. */
  49200. var DirectionalLight = /** @class */ (function (_super) {
  49201. __extends(DirectionalLight, _super);
  49202. /**
  49203. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  49204. * The directional light is emitted from everywhere in the given direction.
  49205. * It can cast shawdows.
  49206. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49207. * @param name The friendly name of the light
  49208. * @param direction The direction of the light
  49209. * @param scene The scene the light belongs to
  49210. */
  49211. function DirectionalLight(name, direction, scene) {
  49212. var _this = _super.call(this, name, scene) || this;
  49213. _this._shadowFrustumSize = 0;
  49214. _this._shadowOrthoScale = 0.1;
  49215. /**
  49216. * Automatically compute the projection matrix to best fit (including all the casters)
  49217. * on each frame.
  49218. */
  49219. _this.autoUpdateExtends = true;
  49220. // Cache
  49221. _this._orthoLeft = Number.MAX_VALUE;
  49222. _this._orthoRight = Number.MIN_VALUE;
  49223. _this._orthoTop = Number.MIN_VALUE;
  49224. _this._orthoBottom = Number.MAX_VALUE;
  49225. _this.position = direction.scale(-1.0);
  49226. _this.direction = direction;
  49227. return _this;
  49228. }
  49229. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  49230. /**
  49231. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  49232. */
  49233. get: function () {
  49234. return this._shadowFrustumSize;
  49235. },
  49236. /**
  49237. * Specifies a fix frustum size for the shadow generation.
  49238. */
  49239. set: function (value) {
  49240. this._shadowFrustumSize = value;
  49241. this.forceProjectionMatrixCompute();
  49242. },
  49243. enumerable: true,
  49244. configurable: true
  49245. });
  49246. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  49247. /**
  49248. * Gets the shadow projection scale against the optimal computed one.
  49249. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49250. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49251. */
  49252. get: function () {
  49253. return this._shadowOrthoScale;
  49254. },
  49255. /**
  49256. * Sets the shadow projection scale against the optimal computed one.
  49257. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49258. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49259. */
  49260. set: function (value) {
  49261. this._shadowOrthoScale = value;
  49262. this.forceProjectionMatrixCompute();
  49263. },
  49264. enumerable: true,
  49265. configurable: true
  49266. });
  49267. /**
  49268. * Returns the string "DirectionalLight".
  49269. * @return The class name
  49270. */
  49271. DirectionalLight.prototype.getClassName = function () {
  49272. return "DirectionalLight";
  49273. };
  49274. /**
  49275. * Returns the integer 1.
  49276. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49277. */
  49278. DirectionalLight.prototype.getTypeID = function () {
  49279. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49280. };
  49281. /**
  49282. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49283. * Returns the DirectionalLight Shadow projection matrix.
  49284. */
  49285. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49286. if (this.shadowFrustumSize > 0) {
  49287. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49288. }
  49289. else {
  49290. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49291. }
  49292. };
  49293. /**
  49294. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49295. * Returns the DirectionalLight Shadow projection matrix.
  49296. */
  49297. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49298. var activeCamera = this.getScene().activeCamera;
  49299. if (!activeCamera) {
  49300. return;
  49301. }
  49302. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49303. };
  49304. /**
  49305. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49306. * Returns the DirectionalLight Shadow projection matrix.
  49307. */
  49308. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49309. var activeCamera = this.getScene().activeCamera;
  49310. if (!activeCamera) {
  49311. return;
  49312. }
  49313. // Check extends
  49314. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49315. var tempVector3 = BABYLON.Vector3.Zero();
  49316. this._orthoLeft = Number.MAX_VALUE;
  49317. this._orthoRight = Number.MIN_VALUE;
  49318. this._orthoTop = Number.MIN_VALUE;
  49319. this._orthoBottom = Number.MAX_VALUE;
  49320. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49321. var mesh = renderList[meshIndex];
  49322. if (!mesh) {
  49323. continue;
  49324. }
  49325. var boundingInfo = mesh.getBoundingInfo();
  49326. var boundingBox = boundingInfo.boundingBox;
  49327. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49328. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49329. if (tempVector3.x < this._orthoLeft)
  49330. this._orthoLeft = tempVector3.x;
  49331. if (tempVector3.y < this._orthoBottom)
  49332. this._orthoBottom = tempVector3.y;
  49333. if (tempVector3.x > this._orthoRight)
  49334. this._orthoRight = tempVector3.x;
  49335. if (tempVector3.y > this._orthoTop)
  49336. this._orthoTop = tempVector3.y;
  49337. }
  49338. }
  49339. }
  49340. var xOffset = this._orthoRight - this._orthoLeft;
  49341. var yOffset = this._orthoTop - this._orthoBottom;
  49342. 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);
  49343. };
  49344. DirectionalLight.prototype._buildUniformLayout = function () {
  49345. this._uniformBuffer.addUniform("vLightData", 4);
  49346. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49347. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49348. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49349. this._uniformBuffer.addUniform("depthValues", 2);
  49350. this._uniformBuffer.create();
  49351. };
  49352. /**
  49353. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49354. * @param effect The effect to update
  49355. * @param lightIndex The index of the light in the effect to update
  49356. * @returns The directional light
  49357. */
  49358. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49359. if (this.computeTransformedInformation()) {
  49360. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49361. return this;
  49362. }
  49363. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49364. return this;
  49365. };
  49366. /**
  49367. * Gets the minZ used for shadow according to both the scene and the light.
  49368. *
  49369. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49370. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49371. * @param activeCamera The camera we are returning the min for
  49372. * @returns the depth min z
  49373. */
  49374. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49375. return 1;
  49376. };
  49377. /**
  49378. * Gets the maxZ used for shadow according to both the scene and the light.
  49379. *
  49380. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49381. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49382. * @param activeCamera The camera we are returning the max for
  49383. * @returns the depth max z
  49384. */
  49385. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49386. return 1;
  49387. };
  49388. /**
  49389. * Prepares the list of defines specific to the light type.
  49390. * @param defines the list of defines
  49391. * @param lightIndex defines the index of the light for the effect
  49392. */
  49393. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49394. defines["DIRLIGHT" + lightIndex] = true;
  49395. };
  49396. __decorate([
  49397. BABYLON.serialize()
  49398. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49399. __decorate([
  49400. BABYLON.serialize()
  49401. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49402. __decorate([
  49403. BABYLON.serialize()
  49404. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49405. return DirectionalLight;
  49406. }(BABYLON.ShadowLight));
  49407. BABYLON.DirectionalLight = DirectionalLight;
  49408. })(BABYLON || (BABYLON = {}));
  49409. //# sourceMappingURL=babylon.directionalLight.js.map
  49410. var BABYLON;
  49411. (function (BABYLON) {
  49412. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  49413. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  49414. });
  49415. /**
  49416. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49417. * These values define a cone of light starting from the position, emitting toward the direction.
  49418. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49419. * and the exponent defines the speed of the decay of the light with distance (reach).
  49420. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49421. */
  49422. var SpotLight = /** @class */ (function (_super) {
  49423. __extends(SpotLight, _super);
  49424. /**
  49425. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49426. * It can cast shadows.
  49427. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49428. * @param name The light friendly name
  49429. * @param position The position of the spot light in the scene
  49430. * @param direction The direction of the light in the scene
  49431. * @param angle The cone angle of the light in Radians
  49432. * @param exponent The light decay speed with the distance from the emission spot
  49433. * @param scene The scene the lights belongs to
  49434. */
  49435. function SpotLight(name, position, direction, angle, exponent, scene) {
  49436. var _this = _super.call(this, name, scene) || this;
  49437. _this._innerAngle = 0;
  49438. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49439. _this._projectionTextureLightNear = 1e-6;
  49440. _this._projectionTextureLightFar = 1000.0;
  49441. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49442. _this._projectionTextureViewLightDirty = true;
  49443. _this._projectionTextureProjectionLightDirty = true;
  49444. _this._projectionTextureDirty = true;
  49445. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49446. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49447. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49448. _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);
  49449. _this.position = position;
  49450. _this.direction = direction;
  49451. _this.angle = angle;
  49452. _this.exponent = exponent;
  49453. return _this;
  49454. }
  49455. Object.defineProperty(SpotLight.prototype, "angle", {
  49456. /**
  49457. * Gets the cone angle of the spot light in Radians.
  49458. */
  49459. get: function () {
  49460. return this._angle;
  49461. },
  49462. /**
  49463. * Sets the cone angle of the spot light in Radians.
  49464. */
  49465. set: function (value) {
  49466. this._angle = value;
  49467. this._cosHalfAngle = Math.cos(value * 0.5);
  49468. this._projectionTextureProjectionLightDirty = true;
  49469. this.forceProjectionMatrixCompute();
  49470. this._computeAngleValues();
  49471. },
  49472. enumerable: true,
  49473. configurable: true
  49474. });
  49475. Object.defineProperty(SpotLight.prototype, "innerAngle", {
  49476. /**
  49477. * Only used in gltf falloff mode, this defines the angle where
  49478. * the directional falloff will start before cutting at angle which could be seen
  49479. * as outer angle.
  49480. */
  49481. get: function () {
  49482. return this._angle;
  49483. },
  49484. /**
  49485. * Only used in gltf falloff mode, this defines the angle where
  49486. * the directional falloff will start before cutting at angle which could be seen
  49487. * as outer angle.
  49488. */
  49489. set: function (value) {
  49490. this._innerAngle = value;
  49491. this._computeAngleValues();
  49492. },
  49493. enumerable: true,
  49494. configurable: true
  49495. });
  49496. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49497. /**
  49498. * Allows scaling the angle of the light for shadow generation only.
  49499. */
  49500. get: function () {
  49501. return this._shadowAngleScale;
  49502. },
  49503. /**
  49504. * Allows scaling the angle of the light for shadow generation only.
  49505. */
  49506. set: function (value) {
  49507. this._shadowAngleScale = value;
  49508. this.forceProjectionMatrixCompute();
  49509. },
  49510. enumerable: true,
  49511. configurable: true
  49512. });
  49513. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49514. /**
  49515. * Allows reading the projecton texture
  49516. */
  49517. get: function () {
  49518. return this._projectionTextureMatrix;
  49519. },
  49520. enumerable: true,
  49521. configurable: true
  49522. });
  49523. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49524. /**
  49525. * Gets the near clip of the Spotlight for texture projection.
  49526. */
  49527. get: function () {
  49528. return this._projectionTextureLightNear;
  49529. },
  49530. /**
  49531. * Sets the near clip of the Spotlight for texture projection.
  49532. */
  49533. set: function (value) {
  49534. this._projectionTextureLightNear = value;
  49535. this._projectionTextureProjectionLightDirty = true;
  49536. },
  49537. enumerable: true,
  49538. configurable: true
  49539. });
  49540. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49541. /**
  49542. * Gets the far clip of the Spotlight for texture projection.
  49543. */
  49544. get: function () {
  49545. return this._projectionTextureLightFar;
  49546. },
  49547. /**
  49548. * Sets the far clip of the Spotlight for texture projection.
  49549. */
  49550. set: function (value) {
  49551. this._projectionTextureLightFar = value;
  49552. this._projectionTextureProjectionLightDirty = true;
  49553. },
  49554. enumerable: true,
  49555. configurable: true
  49556. });
  49557. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49558. /**
  49559. * Gets the Up vector of the Spotlight for texture projection.
  49560. */
  49561. get: function () {
  49562. return this._projectionTextureUpDirection;
  49563. },
  49564. /**
  49565. * Sets the Up vector of the Spotlight for texture projection.
  49566. */
  49567. set: function (value) {
  49568. this._projectionTextureUpDirection = value;
  49569. this._projectionTextureProjectionLightDirty = true;
  49570. },
  49571. enumerable: true,
  49572. configurable: true
  49573. });
  49574. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49575. /**
  49576. * Gets the projection texture of the light.
  49577. */
  49578. get: function () {
  49579. return this._projectionTexture;
  49580. },
  49581. /**
  49582. * Sets the projection texture of the light.
  49583. */
  49584. set: function (value) {
  49585. this._projectionTexture = value;
  49586. this._projectionTextureDirty = true;
  49587. },
  49588. enumerable: true,
  49589. configurable: true
  49590. });
  49591. /**
  49592. * Returns the string "SpotLight".
  49593. * @returns the class name
  49594. */
  49595. SpotLight.prototype.getClassName = function () {
  49596. return "SpotLight";
  49597. };
  49598. /**
  49599. * Returns the integer 2.
  49600. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49601. */
  49602. SpotLight.prototype.getTypeID = function () {
  49603. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49604. };
  49605. /**
  49606. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49607. */
  49608. SpotLight.prototype._setDirection = function (value) {
  49609. _super.prototype._setDirection.call(this, value);
  49610. this._projectionTextureViewLightDirty = true;
  49611. };
  49612. /**
  49613. * Overrides the position setter to recompute the projection texture view light Matrix.
  49614. */
  49615. SpotLight.prototype._setPosition = function (value) {
  49616. _super.prototype._setPosition.call(this, value);
  49617. this._projectionTextureViewLightDirty = true;
  49618. };
  49619. /**
  49620. * 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.
  49621. * Returns the SpotLight.
  49622. */
  49623. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49624. var activeCamera = this.getScene().activeCamera;
  49625. if (!activeCamera) {
  49626. return;
  49627. }
  49628. this._shadowAngleScale = this._shadowAngleScale || 1;
  49629. var angle = this._shadowAngleScale * this._angle;
  49630. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49631. };
  49632. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49633. this._projectionTextureViewLightDirty = false;
  49634. this._projectionTextureDirty = true;
  49635. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49636. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49637. };
  49638. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49639. this._projectionTextureProjectionLightDirty = false;
  49640. this._projectionTextureDirty = true;
  49641. var light_far = this.projectionTextureLightFar;
  49642. var light_near = this.projectionTextureLightNear;
  49643. var P = light_far / (light_far - light_near);
  49644. var Q = -P * light_near;
  49645. var S = 1.0 / Math.tan(this._angle / 2.0);
  49646. var A = 1.0;
  49647. 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);
  49648. };
  49649. /**
  49650. * Main function for light texture projection matrix computing.
  49651. */
  49652. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49653. this._projectionTextureDirty = false;
  49654. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49655. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49656. };
  49657. SpotLight.prototype._buildUniformLayout = function () {
  49658. this._uniformBuffer.addUniform("vLightData", 4);
  49659. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49660. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49661. this._uniformBuffer.addUniform("vLightDirection", 3);
  49662. this._uniformBuffer.addUniform("vLightFalloff", 4);
  49663. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49664. this._uniformBuffer.addUniform("depthValues", 2);
  49665. this._uniformBuffer.create();
  49666. };
  49667. SpotLight.prototype._computeAngleValues = function () {
  49668. this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
  49669. this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
  49670. };
  49671. /**
  49672. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49673. * @param effect The effect to update
  49674. * @param lightIndex The index of the light in the effect to update
  49675. * @returns The spot light
  49676. */
  49677. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49678. var normalizeDirection;
  49679. if (this.computeTransformedInformation()) {
  49680. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49681. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49682. }
  49683. else {
  49684. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49685. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49686. }
  49687. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
  49688. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
  49689. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49690. if (this._projectionTextureViewLightDirty) {
  49691. this._computeProjectionTextureViewLightMatrix();
  49692. }
  49693. if (this._projectionTextureProjectionLightDirty) {
  49694. this._computeProjectionTextureProjectionLightMatrix();
  49695. }
  49696. if (this._projectionTextureDirty) {
  49697. this._computeProjectionTextureMatrix();
  49698. }
  49699. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49700. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49701. }
  49702. return this;
  49703. };
  49704. /**
  49705. * Disposes the light and the associated resources.
  49706. */
  49707. SpotLight.prototype.dispose = function () {
  49708. _super.prototype.dispose.call(this);
  49709. if (this._projectionTexture) {
  49710. this._projectionTexture.dispose();
  49711. }
  49712. };
  49713. /**
  49714. * Prepares the list of defines specific to the light type.
  49715. * @param defines the list of defines
  49716. * @param lightIndex defines the index of the light for the effect
  49717. */
  49718. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49719. defines["SPOTLIGHT" + lightIndex] = true;
  49720. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  49721. };
  49722. __decorate([
  49723. BABYLON.serialize()
  49724. ], SpotLight.prototype, "angle", null);
  49725. __decorate([
  49726. BABYLON.serialize()
  49727. ], SpotLight.prototype, "innerAngle", null);
  49728. __decorate([
  49729. BABYLON.serialize()
  49730. ], SpotLight.prototype, "shadowAngleScale", null);
  49731. __decorate([
  49732. BABYLON.serialize()
  49733. ], SpotLight.prototype, "exponent", void 0);
  49734. __decorate([
  49735. BABYLON.serialize()
  49736. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49737. __decorate([
  49738. BABYLON.serialize()
  49739. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49740. __decorate([
  49741. BABYLON.serialize()
  49742. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49743. __decorate([
  49744. BABYLON.serializeAsTexture("projectedLightTexture")
  49745. ], SpotLight.prototype, "_projectionTexture", void 0);
  49746. return SpotLight;
  49747. }(BABYLON.ShadowLight));
  49748. BABYLON.SpotLight = SpotLight;
  49749. })(BABYLON || (BABYLON = {}));
  49750. //# sourceMappingURL=babylon.spotLight.js.map
  49751. var BABYLON;
  49752. (function (BABYLON) {
  49753. /**
  49754. * Class used to override all child animations of a given target
  49755. */
  49756. var AnimationPropertiesOverride = /** @class */ (function () {
  49757. function AnimationPropertiesOverride() {
  49758. /**
  49759. * Gets or sets a value indicating if animation blending must be used
  49760. */
  49761. this.enableBlending = false;
  49762. /**
  49763. * Gets or sets the blending speed to use when enableBlending is true
  49764. */
  49765. this.blendingSpeed = 0.01;
  49766. /**
  49767. * Gets or sets the default loop mode to use
  49768. */
  49769. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49770. }
  49771. return AnimationPropertiesOverride;
  49772. }());
  49773. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49774. })(BABYLON || (BABYLON = {}));
  49775. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49776. var BABYLON;
  49777. (function (BABYLON) {
  49778. /**
  49779. * Represents the range of an animation
  49780. */
  49781. var AnimationRange = /** @class */ (function () {
  49782. /**
  49783. * Initializes the range of an animation
  49784. * @param name The name of the animation range
  49785. * @param from The starting frame of the animation
  49786. * @param to The ending frame of the animation
  49787. */
  49788. function AnimationRange(
  49789. /**The name of the animation range**/
  49790. name,
  49791. /**The starting frame of the animation */
  49792. from,
  49793. /**The ending frame of the animation*/
  49794. to) {
  49795. this.name = name;
  49796. this.from = from;
  49797. this.to = to;
  49798. }
  49799. /**
  49800. * Makes a copy of the animation range
  49801. * @returns A copy of the animation range
  49802. */
  49803. AnimationRange.prototype.clone = function () {
  49804. return new AnimationRange(this.name, this.from, this.to);
  49805. };
  49806. return AnimationRange;
  49807. }());
  49808. BABYLON.AnimationRange = AnimationRange;
  49809. /**
  49810. * Composed of a frame, and an action function
  49811. */
  49812. var AnimationEvent = /** @class */ (function () {
  49813. /**
  49814. * Initializes the animation event
  49815. * @param frame The frame for which the event is triggered
  49816. * @param action The event to perform when triggered
  49817. * @param onlyOnce Specifies if the event should be triggered only once
  49818. */
  49819. function AnimationEvent(
  49820. /** The frame for which the event is triggered **/
  49821. frame,
  49822. /** The event to perform when triggered **/
  49823. action,
  49824. /** Specifies if the event should be triggered only once**/
  49825. onlyOnce) {
  49826. this.frame = frame;
  49827. this.action = action;
  49828. this.onlyOnce = onlyOnce;
  49829. /**
  49830. * Specifies if the animation event is done
  49831. */
  49832. this.isDone = false;
  49833. }
  49834. /** @hidden */
  49835. AnimationEvent.prototype._clone = function () {
  49836. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  49837. };
  49838. return AnimationEvent;
  49839. }());
  49840. BABYLON.AnimationEvent = AnimationEvent;
  49841. /**
  49842. * A cursor which tracks a point on a path
  49843. */
  49844. var PathCursor = /** @class */ (function () {
  49845. /**
  49846. * Initializes the path cursor
  49847. * @param path The path to track
  49848. */
  49849. function PathCursor(path) {
  49850. this.path = path;
  49851. /**
  49852. * Stores path cursor callbacks for when an onchange event is triggered
  49853. */
  49854. this._onchange = new Array();
  49855. /**
  49856. * The value of the path cursor
  49857. */
  49858. this.value = 0;
  49859. /**
  49860. * The animation array of the path cursor
  49861. */
  49862. this.animations = new Array();
  49863. }
  49864. /**
  49865. * Gets the cursor point on the path
  49866. * @returns A point on the path cursor at the cursor location
  49867. */
  49868. PathCursor.prototype.getPoint = function () {
  49869. var point = this.path.getPointAtLengthPosition(this.value);
  49870. return new BABYLON.Vector3(point.x, 0, point.y);
  49871. };
  49872. /**
  49873. * Moves the cursor ahead by the step amount
  49874. * @param step The amount to move the cursor forward
  49875. * @returns This path cursor
  49876. */
  49877. PathCursor.prototype.moveAhead = function (step) {
  49878. if (step === void 0) { step = 0.002; }
  49879. this.move(step);
  49880. return this;
  49881. };
  49882. /**
  49883. * Moves the cursor behind by the step amount
  49884. * @param step The amount to move the cursor back
  49885. * @returns This path cursor
  49886. */
  49887. PathCursor.prototype.moveBack = function (step) {
  49888. if (step === void 0) { step = 0.002; }
  49889. this.move(-step);
  49890. return this;
  49891. };
  49892. /**
  49893. * Moves the cursor by the step amount
  49894. * If the step amount is greater than one, an exception is thrown
  49895. * @param step The amount to move the cursor
  49896. * @returns This path cursor
  49897. */
  49898. PathCursor.prototype.move = function (step) {
  49899. if (Math.abs(step) > 1) {
  49900. throw "step size should be less than 1.";
  49901. }
  49902. this.value += step;
  49903. this.ensureLimits();
  49904. this.raiseOnChange();
  49905. return this;
  49906. };
  49907. /**
  49908. * Ensures that the value is limited between zero and one
  49909. * @returns This path cursor
  49910. */
  49911. PathCursor.prototype.ensureLimits = function () {
  49912. while (this.value > 1) {
  49913. this.value -= 1;
  49914. }
  49915. while (this.value < 0) {
  49916. this.value += 1;
  49917. }
  49918. return this;
  49919. };
  49920. /**
  49921. * Runs onchange callbacks on change (used by the animation engine)
  49922. * @returns This path cursor
  49923. */
  49924. PathCursor.prototype.raiseOnChange = function () {
  49925. var _this = this;
  49926. this._onchange.forEach(function (f) { return f(_this); });
  49927. return this;
  49928. };
  49929. /**
  49930. * Executes a function on change
  49931. * @param f A path cursor onchange callback
  49932. * @returns This path cursor
  49933. */
  49934. PathCursor.prototype.onchange = function (f) {
  49935. this._onchange.push(f);
  49936. return this;
  49937. };
  49938. return PathCursor;
  49939. }());
  49940. BABYLON.PathCursor = PathCursor;
  49941. /**
  49942. * Enum for the animation key frame interpolation type
  49943. */
  49944. var AnimationKeyInterpolation;
  49945. (function (AnimationKeyInterpolation) {
  49946. /**
  49947. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49948. */
  49949. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49950. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49951. /**
  49952. * Class used to store any kind of animation
  49953. */
  49954. var Animation = /** @class */ (function () {
  49955. /**
  49956. * Initializes the animation
  49957. * @param name Name of the animation
  49958. * @param targetProperty Property to animate
  49959. * @param framePerSecond The frames per second of the animation
  49960. * @param dataType The data type of the animation
  49961. * @param loopMode The loop mode of the animation
  49962. * @param enableBlendings Specifies if blending should be enabled
  49963. */
  49964. function Animation(
  49965. /**Name of the animation */
  49966. name,
  49967. /**Property to animate */
  49968. targetProperty,
  49969. /**The frames per second of the animation */
  49970. framePerSecond,
  49971. /**The data type of the animation */
  49972. dataType,
  49973. /**The loop mode of the animation */
  49974. loopMode,
  49975. /**Specifies if blending should be enabled */
  49976. enableBlending) {
  49977. this.name = name;
  49978. this.targetProperty = targetProperty;
  49979. this.framePerSecond = framePerSecond;
  49980. this.dataType = dataType;
  49981. this.loopMode = loopMode;
  49982. this.enableBlending = enableBlending;
  49983. /**
  49984. * @hidden Internal use only
  49985. */
  49986. this._runtimeAnimations = new Array();
  49987. /**
  49988. * The set of event that will be linked to this animation
  49989. */
  49990. this._events = new Array();
  49991. /**
  49992. * Stores the blending speed of the animation
  49993. */
  49994. this.blendingSpeed = 0.01;
  49995. /**
  49996. * Stores the animation ranges for the animation
  49997. */
  49998. this._ranges = {};
  49999. this.targetPropertyPath = targetProperty.split(".");
  50000. this.dataType = dataType;
  50001. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  50002. }
  50003. /**
  50004. * @hidden Internal use
  50005. */
  50006. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  50007. var dataType = undefined;
  50008. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  50009. dataType = Animation.ANIMATIONTYPE_FLOAT;
  50010. }
  50011. else if (from instanceof BABYLON.Quaternion) {
  50012. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  50013. }
  50014. else if (from instanceof BABYLON.Vector3) {
  50015. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  50016. }
  50017. else if (from instanceof BABYLON.Vector2) {
  50018. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  50019. }
  50020. else if (from instanceof BABYLON.Color3) {
  50021. dataType = Animation.ANIMATIONTYPE_COLOR3;
  50022. }
  50023. else if (from instanceof BABYLON.Size) {
  50024. dataType = Animation.ANIMATIONTYPE_SIZE;
  50025. }
  50026. if (dataType == undefined) {
  50027. return null;
  50028. }
  50029. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50030. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50031. animation.setKeys(keys);
  50032. if (easingFunction !== undefined) {
  50033. animation.setEasingFunction(easingFunction);
  50034. }
  50035. return animation;
  50036. };
  50037. /**
  50038. * Sets up an animation
  50039. * @param property The property to animate
  50040. * @param animationType The animation type to apply
  50041. * @param framePerSecond The frames per second of the animation
  50042. * @param easingFunction The easing function used in the animation
  50043. * @returns The created animation
  50044. */
  50045. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50046. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50047. animation.setEasingFunction(easingFunction);
  50048. return animation;
  50049. };
  50050. /**
  50051. * Create and start an animation on a node
  50052. * @param name defines the name of the global animation that will be run on all nodes
  50053. * @param node defines the root node where the animation will take place
  50054. * @param targetProperty defines property to animate
  50055. * @param framePerSecond defines the number of frame per second yo use
  50056. * @param totalFrame defines the number of frames in total
  50057. * @param from defines the initial value
  50058. * @param to defines the final value
  50059. * @param loopMode defines which loop mode you want to use (off by default)
  50060. * @param easingFunction defines the easing function to use (linear by default)
  50061. * @param onAnimationEnd defines the callback to call when animation end
  50062. * @returns the animatable created for this animation
  50063. */
  50064. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50065. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50066. if (!animation) {
  50067. return null;
  50068. }
  50069. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50070. };
  50071. /**
  50072. * Create and start an animation on a node and its descendants
  50073. * @param name defines the name of the global animation that will be run on all nodes
  50074. * @param node defines the root node where the animation will take place
  50075. * @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
  50076. * @param targetProperty defines property to animate
  50077. * @param framePerSecond defines the number of frame per second to use
  50078. * @param totalFrame defines the number of frames in total
  50079. * @param from defines the initial value
  50080. * @param to defines the final value
  50081. * @param loopMode defines which loop mode you want to use (off by default)
  50082. * @param easingFunction defines the easing function to use (linear by default)
  50083. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50084. * @returns the list of animatables created for all nodes
  50085. * @example https://www.babylonjs-playground.com/#MH0VLI
  50086. */
  50087. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50088. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50089. if (!animation) {
  50090. return null;
  50091. }
  50092. var scene = node.getScene();
  50093. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50094. };
  50095. /**
  50096. * Creates a new animation, merges it with the existing animations and starts it
  50097. * @param name Name of the animation
  50098. * @param node Node which contains the scene that begins the animations
  50099. * @param targetProperty Specifies which property to animate
  50100. * @param framePerSecond The frames per second of the animation
  50101. * @param totalFrame The total number of frames
  50102. * @param from The frame at the beginning of the animation
  50103. * @param to The frame at the end of the animation
  50104. * @param loopMode Specifies the loop mode of the animation
  50105. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50106. * @param onAnimationEnd Callback to run once the animation is complete
  50107. * @returns Nullable animation
  50108. */
  50109. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50110. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50111. if (!animation) {
  50112. return null;
  50113. }
  50114. node.animations.push(animation);
  50115. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50116. };
  50117. /**
  50118. * Transition property of an host to the target Value
  50119. * @param property The property to transition
  50120. * @param targetValue The target Value of the property
  50121. * @param host The object where the property to animate belongs
  50122. * @param scene Scene used to run the animation
  50123. * @param frameRate Framerate (in frame/s) to use
  50124. * @param transition The transition type we want to use
  50125. * @param duration The duration of the animation, in milliseconds
  50126. * @param onAnimationEnd Callback trigger at the end of the animation
  50127. * @returns Nullable animation
  50128. */
  50129. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50130. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50131. if (duration <= 0) {
  50132. host[property] = targetValue;
  50133. if (onAnimationEnd) {
  50134. onAnimationEnd();
  50135. }
  50136. return null;
  50137. }
  50138. var endFrame = frameRate * (duration / 1000);
  50139. transition.setKeys([{
  50140. frame: 0,
  50141. value: host[property].clone ? host[property].clone() : host[property]
  50142. },
  50143. {
  50144. frame: endFrame,
  50145. value: targetValue
  50146. }]);
  50147. if (!host.animations) {
  50148. host.animations = [];
  50149. }
  50150. host.animations.push(transition);
  50151. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50152. animation.onAnimationEnd = onAnimationEnd;
  50153. return animation;
  50154. };
  50155. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50156. /**
  50157. * Return the array of runtime animations currently using this animation
  50158. */
  50159. get: function () {
  50160. return this._runtimeAnimations;
  50161. },
  50162. enumerable: true,
  50163. configurable: true
  50164. });
  50165. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  50166. /**
  50167. * Specifies if any of the runtime animations are currently running
  50168. */
  50169. get: function () {
  50170. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  50171. var runtimeAnimation = _a[_i];
  50172. if (!runtimeAnimation.isStopped) {
  50173. return true;
  50174. }
  50175. }
  50176. return false;
  50177. },
  50178. enumerable: true,
  50179. configurable: true
  50180. });
  50181. // Methods
  50182. /**
  50183. * Converts the animation to a string
  50184. * @param fullDetails support for multiple levels of logging within scene loading
  50185. * @returns String form of the animation
  50186. */
  50187. Animation.prototype.toString = function (fullDetails) {
  50188. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  50189. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  50190. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  50191. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50192. if (fullDetails) {
  50193. ret += ", Ranges: {";
  50194. var first = true;
  50195. for (var name in this._ranges) {
  50196. if (first) {
  50197. ret += ", ";
  50198. first = false;
  50199. }
  50200. ret += name;
  50201. }
  50202. ret += "}";
  50203. }
  50204. return ret;
  50205. };
  50206. /**
  50207. * Add an event to this animation
  50208. * @param event Event to add
  50209. */
  50210. Animation.prototype.addEvent = function (event) {
  50211. this._events.push(event);
  50212. };
  50213. /**
  50214. * Remove all events found at the given frame
  50215. * @param frame The frame to remove events from
  50216. */
  50217. Animation.prototype.removeEvents = function (frame) {
  50218. for (var index = 0; index < this._events.length; index++) {
  50219. if (this._events[index].frame === frame) {
  50220. this._events.splice(index, 1);
  50221. index--;
  50222. }
  50223. }
  50224. };
  50225. /**
  50226. * Retrieves all the events from the animation
  50227. * @returns Events from the animation
  50228. */
  50229. Animation.prototype.getEvents = function () {
  50230. return this._events;
  50231. };
  50232. /**
  50233. * Creates an animation range
  50234. * @param name Name of the animation range
  50235. * @param from Starting frame of the animation range
  50236. * @param to Ending frame of the animation
  50237. */
  50238. Animation.prototype.createRange = function (name, from, to) {
  50239. // check name not already in use; could happen for bones after serialized
  50240. if (!this._ranges[name]) {
  50241. this._ranges[name] = new AnimationRange(name, from, to);
  50242. }
  50243. };
  50244. /**
  50245. * Deletes an animation range by name
  50246. * @param name Name of the animation range to delete
  50247. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  50248. */
  50249. Animation.prototype.deleteRange = function (name, deleteFrames) {
  50250. if (deleteFrames === void 0) { deleteFrames = true; }
  50251. var range = this._ranges[name];
  50252. if (!range) {
  50253. return;
  50254. }
  50255. if (deleteFrames) {
  50256. var from = range.from;
  50257. var to = range.to;
  50258. // this loop MUST go high to low for multiple splices to work
  50259. for (var key = this._keys.length - 1; key >= 0; key--) {
  50260. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  50261. this._keys.splice(key, 1);
  50262. }
  50263. }
  50264. }
  50265. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  50266. };
  50267. /**
  50268. * Gets the animation range by name, or null if not defined
  50269. * @param name Name of the animation range
  50270. * @returns Nullable animation range
  50271. */
  50272. Animation.prototype.getRange = function (name) {
  50273. return this._ranges[name];
  50274. };
  50275. /**
  50276. * Gets the key frames from the animation
  50277. * @returns The key frames of the animation
  50278. */
  50279. Animation.prototype.getKeys = function () {
  50280. return this._keys;
  50281. };
  50282. /**
  50283. * Gets the highest frame rate of the animation
  50284. * @returns Highest frame rate of the animation
  50285. */
  50286. Animation.prototype.getHighestFrame = function () {
  50287. var ret = 0;
  50288. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  50289. if (ret < this._keys[key].frame) {
  50290. ret = this._keys[key].frame;
  50291. }
  50292. }
  50293. return ret;
  50294. };
  50295. /**
  50296. * Gets the easing function of the animation
  50297. * @returns Easing function of the animation
  50298. */
  50299. Animation.prototype.getEasingFunction = function () {
  50300. return this._easingFunction;
  50301. };
  50302. /**
  50303. * Sets the easing function of the animation
  50304. * @param easingFunction A custom mathematical formula for animation
  50305. */
  50306. Animation.prototype.setEasingFunction = function (easingFunction) {
  50307. this._easingFunction = easingFunction;
  50308. };
  50309. /**
  50310. * Interpolates a scalar linearly
  50311. * @param startValue Start value of the animation curve
  50312. * @param endValue End value of the animation curve
  50313. * @param gradient Scalar amount to interpolate
  50314. * @returns Interpolated scalar value
  50315. */
  50316. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50317. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50318. };
  50319. /**
  50320. * Interpolates a scalar cubically
  50321. * @param startValue Start value of the animation curve
  50322. * @param outTangent End tangent of the animation
  50323. * @param endValue End value of the animation curve
  50324. * @param inTangent Start tangent of the animation curve
  50325. * @param gradient Scalar amount to interpolate
  50326. * @returns Interpolated scalar value
  50327. */
  50328. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50329. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50330. };
  50331. /**
  50332. * Interpolates a quaternion using a spherical linear interpolation
  50333. * @param startValue Start value of the animation curve
  50334. * @param endValue End value of the animation curve
  50335. * @param gradient Scalar amount to interpolate
  50336. * @returns Interpolated quaternion value
  50337. */
  50338. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50339. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50340. };
  50341. /**
  50342. * Interpolates a quaternion cubically
  50343. * @param startValue Start value of the animation curve
  50344. * @param outTangent End tangent of the animation curve
  50345. * @param endValue End value of the animation curve
  50346. * @param inTangent Start tangent of the animation curve
  50347. * @param gradient Scalar amount to interpolate
  50348. * @returns Interpolated quaternion value
  50349. */
  50350. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50351. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50352. };
  50353. /**
  50354. * Interpolates a Vector3 linearl
  50355. * @param startValue Start value of the animation curve
  50356. * @param endValue End value of the animation curve
  50357. * @param gradient Scalar amount to interpolate
  50358. * @returns Interpolated scalar value
  50359. */
  50360. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50361. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50362. };
  50363. /**
  50364. * Interpolates a Vector3 cubically
  50365. * @param startValue Start value of the animation curve
  50366. * @param outTangent End tangent of the animation
  50367. * @param endValue End value of the animation curve
  50368. * @param inTangent Start tangent of the animation curve
  50369. * @param gradient Scalar amount to interpolate
  50370. * @returns InterpolatedVector3 value
  50371. */
  50372. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50373. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50374. };
  50375. /**
  50376. * Interpolates a Vector2 linearly
  50377. * @param startValue Start value of the animation curve
  50378. * @param endValue End value of the animation curve
  50379. * @param gradient Scalar amount to interpolate
  50380. * @returns Interpolated Vector2 value
  50381. */
  50382. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50383. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50384. };
  50385. /**
  50386. * Interpolates a Vector2 cubically
  50387. * @param startValue Start value of the animation curve
  50388. * @param outTangent End tangent of the animation
  50389. * @param endValue End value of the animation curve
  50390. * @param inTangent Start tangent of the animation curve
  50391. * @param gradient Scalar amount to interpolate
  50392. * @returns Interpolated Vector2 value
  50393. */
  50394. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50395. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50396. };
  50397. /**
  50398. * Interpolates a size linearly
  50399. * @param startValue Start value of the animation curve
  50400. * @param endValue End value of the animation curve
  50401. * @param gradient Scalar amount to interpolate
  50402. * @returns Interpolated Size value
  50403. */
  50404. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50405. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50406. };
  50407. /**
  50408. * Interpolates a Color3 linearly
  50409. * @param startValue Start value of the animation curve
  50410. * @param endValue End value of the animation curve
  50411. * @param gradient Scalar amount to interpolate
  50412. * @returns Interpolated Color3 value
  50413. */
  50414. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50415. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50416. };
  50417. /**
  50418. * @hidden Internal use only
  50419. */
  50420. Animation.prototype._getKeyValue = function (value) {
  50421. if (typeof value === "function") {
  50422. return value();
  50423. }
  50424. return value;
  50425. };
  50426. /**
  50427. * @hidden Internal use only
  50428. */
  50429. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  50430. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50431. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50432. }
  50433. var keys = this.getKeys();
  50434. // Try to get a hash to find the right key
  50435. 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));
  50436. if (keys[startKeyIndex].frame >= currentFrame) {
  50437. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50438. startKeyIndex--;
  50439. }
  50440. }
  50441. for (var key = startKeyIndex; key < keys.length; key++) {
  50442. var endKey = keys[key + 1];
  50443. if (endKey.frame >= currentFrame) {
  50444. var startKey = keys[key];
  50445. var startValue = this._getKeyValue(startKey.value);
  50446. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  50447. return startValue;
  50448. }
  50449. var endValue = this._getKeyValue(endKey.value);
  50450. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50451. var frameDelta = endKey.frame - startKey.frame;
  50452. // gradient : percent of currentFrame between the frame inf and the frame sup
  50453. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50454. // check for easingFunction and correction of gradient
  50455. var easingFunction = this.getEasingFunction();
  50456. if (easingFunction != null) {
  50457. gradient = easingFunction.ease(gradient);
  50458. }
  50459. switch (this.dataType) {
  50460. // Float
  50461. case Animation.ANIMATIONTYPE_FLOAT:
  50462. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  50463. switch (loopMode) {
  50464. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50465. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50466. return floatValue;
  50467. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50468. return offsetValue * repeatCount + floatValue;
  50469. }
  50470. break;
  50471. // Quaternion
  50472. case Animation.ANIMATIONTYPE_QUATERNION:
  50473. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  50474. switch (loopMode) {
  50475. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50476. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50477. return quatValue;
  50478. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50479. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50480. }
  50481. return quatValue;
  50482. // Vector3
  50483. case Animation.ANIMATIONTYPE_VECTOR3:
  50484. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  50485. switch (loopMode) {
  50486. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50487. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50488. return vec3Value;
  50489. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50490. return vec3Value.add(offsetValue.scale(repeatCount));
  50491. }
  50492. // Vector2
  50493. case Animation.ANIMATIONTYPE_VECTOR2:
  50494. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  50495. switch (loopMode) {
  50496. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50497. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50498. return vec2Value;
  50499. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50500. return vec2Value.add(offsetValue.scale(repeatCount));
  50501. }
  50502. // Size
  50503. case Animation.ANIMATIONTYPE_SIZE:
  50504. switch (loopMode) {
  50505. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50506. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50507. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  50508. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50509. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50510. }
  50511. // Color3
  50512. case Animation.ANIMATIONTYPE_COLOR3:
  50513. switch (loopMode) {
  50514. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50515. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50516. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50517. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50518. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50519. }
  50520. // Matrix
  50521. case Animation.ANIMATIONTYPE_MATRIX:
  50522. switch (loopMode) {
  50523. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50524. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50525. if (Animation.AllowMatricesInterpolation) {
  50526. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50527. }
  50528. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50529. return startValue;
  50530. }
  50531. default:
  50532. break;
  50533. }
  50534. break;
  50535. }
  50536. }
  50537. return this._getKeyValue(keys[keys.length - 1].value);
  50538. };
  50539. /**
  50540. * Defines the function to use to interpolate matrices
  50541. * @param startValue defines the start matrix
  50542. * @param endValue defines the end matrix
  50543. * @param gradient defines the gradient between both matrices
  50544. * @param result defines an optional target matrix where to store the interpolation
  50545. * @returns the interpolated matrix
  50546. */
  50547. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50548. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50549. if (result) {
  50550. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50551. return result;
  50552. }
  50553. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50554. }
  50555. if (result) {
  50556. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50557. return result;
  50558. }
  50559. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50560. };
  50561. /**
  50562. * Makes a copy of the animation
  50563. * @returns Cloned animation
  50564. */
  50565. Animation.prototype.clone = function () {
  50566. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50567. clone.enableBlending = this.enableBlending;
  50568. clone.blendingSpeed = this.blendingSpeed;
  50569. if (this._keys) {
  50570. clone.setKeys(this._keys);
  50571. }
  50572. if (this._ranges) {
  50573. clone._ranges = {};
  50574. for (var name in this._ranges) {
  50575. var range = this._ranges[name];
  50576. if (!range) {
  50577. continue;
  50578. }
  50579. clone._ranges[name] = range.clone();
  50580. }
  50581. }
  50582. return clone;
  50583. };
  50584. /**
  50585. * Sets the key frames of the animation
  50586. * @param values The animation key frames to set
  50587. */
  50588. Animation.prototype.setKeys = function (values) {
  50589. this._keys = values.slice(0);
  50590. };
  50591. /**
  50592. * Serializes the animation to an object
  50593. * @returns Serialized object
  50594. */
  50595. Animation.prototype.serialize = function () {
  50596. var serializationObject = {};
  50597. serializationObject.name = this.name;
  50598. serializationObject.property = this.targetProperty;
  50599. serializationObject.framePerSecond = this.framePerSecond;
  50600. serializationObject.dataType = this.dataType;
  50601. serializationObject.loopBehavior = this.loopMode;
  50602. serializationObject.enableBlending = this.enableBlending;
  50603. serializationObject.blendingSpeed = this.blendingSpeed;
  50604. var dataType = this.dataType;
  50605. serializationObject.keys = [];
  50606. var keys = this.getKeys();
  50607. for (var index = 0; index < keys.length; index++) {
  50608. var animationKey = keys[index];
  50609. var key = {};
  50610. key.frame = animationKey.frame;
  50611. switch (dataType) {
  50612. case Animation.ANIMATIONTYPE_FLOAT:
  50613. key.values = [animationKey.value];
  50614. break;
  50615. case Animation.ANIMATIONTYPE_QUATERNION:
  50616. case Animation.ANIMATIONTYPE_MATRIX:
  50617. case Animation.ANIMATIONTYPE_VECTOR3:
  50618. case Animation.ANIMATIONTYPE_COLOR3:
  50619. key.values = animationKey.value.asArray();
  50620. break;
  50621. }
  50622. serializationObject.keys.push(key);
  50623. }
  50624. serializationObject.ranges = [];
  50625. for (var name in this._ranges) {
  50626. var source = this._ranges[name];
  50627. if (!source) {
  50628. continue;
  50629. }
  50630. var range = {};
  50631. range.name = name;
  50632. range.from = source.from;
  50633. range.to = source.to;
  50634. serializationObject.ranges.push(range);
  50635. }
  50636. return serializationObject;
  50637. };
  50638. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50639. /**
  50640. * Get the float animation type
  50641. */
  50642. get: function () {
  50643. return Animation._ANIMATIONTYPE_FLOAT;
  50644. },
  50645. enumerable: true,
  50646. configurable: true
  50647. });
  50648. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50649. /**
  50650. * Get the Vector3 animation type
  50651. */
  50652. get: function () {
  50653. return Animation._ANIMATIONTYPE_VECTOR3;
  50654. },
  50655. enumerable: true,
  50656. configurable: true
  50657. });
  50658. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50659. /**
  50660. * Get the Vector2 animation type
  50661. */
  50662. get: function () {
  50663. return Animation._ANIMATIONTYPE_VECTOR2;
  50664. },
  50665. enumerable: true,
  50666. configurable: true
  50667. });
  50668. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50669. /**
  50670. * Get the Size animation type
  50671. */
  50672. get: function () {
  50673. return Animation._ANIMATIONTYPE_SIZE;
  50674. },
  50675. enumerable: true,
  50676. configurable: true
  50677. });
  50678. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50679. /**
  50680. * Get the Quaternion animation type
  50681. */
  50682. get: function () {
  50683. return Animation._ANIMATIONTYPE_QUATERNION;
  50684. },
  50685. enumerable: true,
  50686. configurable: true
  50687. });
  50688. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50689. /**
  50690. * Get the Matrix animation type
  50691. */
  50692. get: function () {
  50693. return Animation._ANIMATIONTYPE_MATRIX;
  50694. },
  50695. enumerable: true,
  50696. configurable: true
  50697. });
  50698. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50699. /**
  50700. * Get the Color3 animation type
  50701. */
  50702. get: function () {
  50703. return Animation._ANIMATIONTYPE_COLOR3;
  50704. },
  50705. enumerable: true,
  50706. configurable: true
  50707. });
  50708. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50709. /**
  50710. * Get the Relative Loop Mode
  50711. */
  50712. get: function () {
  50713. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50714. },
  50715. enumerable: true,
  50716. configurable: true
  50717. });
  50718. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50719. /**
  50720. * Get the Cycle Loop Mode
  50721. */
  50722. get: function () {
  50723. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50724. },
  50725. enumerable: true,
  50726. configurable: true
  50727. });
  50728. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50729. /**
  50730. * Get the Constant Loop Mode
  50731. */
  50732. get: function () {
  50733. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50734. },
  50735. enumerable: true,
  50736. configurable: true
  50737. });
  50738. /** @hidden */
  50739. Animation._UniversalLerp = function (left, right, amount) {
  50740. var constructor = left.constructor;
  50741. if (constructor.Lerp) { // Lerp supported
  50742. return constructor.Lerp(left, right, amount);
  50743. }
  50744. else if (constructor.Slerp) { // Slerp supported
  50745. return constructor.Slerp(left, right, amount);
  50746. }
  50747. else if (left.toFixed) { // Number
  50748. return left * (1.0 - amount) + amount * right;
  50749. }
  50750. else { // Blending not supported
  50751. return right;
  50752. }
  50753. };
  50754. /**
  50755. * Parses an animation object and creates an animation
  50756. * @param parsedAnimation Parsed animation object
  50757. * @returns Animation object
  50758. */
  50759. Animation.Parse = function (parsedAnimation) {
  50760. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50761. var dataType = parsedAnimation.dataType;
  50762. var keys = [];
  50763. var data;
  50764. var index;
  50765. if (parsedAnimation.enableBlending) {
  50766. animation.enableBlending = parsedAnimation.enableBlending;
  50767. }
  50768. if (parsedAnimation.blendingSpeed) {
  50769. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50770. }
  50771. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50772. var key = parsedAnimation.keys[index];
  50773. var inTangent;
  50774. var outTangent;
  50775. switch (dataType) {
  50776. case Animation.ANIMATIONTYPE_FLOAT:
  50777. data = key.values[0];
  50778. if (key.values.length >= 1) {
  50779. inTangent = key.values[1];
  50780. }
  50781. if (key.values.length >= 2) {
  50782. outTangent = key.values[2];
  50783. }
  50784. break;
  50785. case Animation.ANIMATIONTYPE_QUATERNION:
  50786. data = BABYLON.Quaternion.FromArray(key.values);
  50787. if (key.values.length >= 8) {
  50788. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50789. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50790. inTangent = _inTangent;
  50791. }
  50792. }
  50793. if (key.values.length >= 12) {
  50794. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50795. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50796. outTangent = _outTangent;
  50797. }
  50798. }
  50799. break;
  50800. case Animation.ANIMATIONTYPE_MATRIX:
  50801. data = BABYLON.Matrix.FromArray(key.values);
  50802. break;
  50803. case Animation.ANIMATIONTYPE_COLOR3:
  50804. data = BABYLON.Color3.FromArray(key.values);
  50805. break;
  50806. case Animation.ANIMATIONTYPE_VECTOR3:
  50807. default:
  50808. data = BABYLON.Vector3.FromArray(key.values);
  50809. break;
  50810. }
  50811. var keyData = {};
  50812. keyData.frame = key.frame;
  50813. keyData.value = data;
  50814. if (inTangent != undefined) {
  50815. keyData.inTangent = inTangent;
  50816. }
  50817. if (outTangent != undefined) {
  50818. keyData.outTangent = outTangent;
  50819. }
  50820. keys.push(keyData);
  50821. }
  50822. animation.setKeys(keys);
  50823. if (parsedAnimation.ranges) {
  50824. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50825. data = parsedAnimation.ranges[index];
  50826. animation.createRange(data.name, data.from, data.to);
  50827. }
  50828. }
  50829. return animation;
  50830. };
  50831. /**
  50832. * Appends the serialized animations from the source animations
  50833. * @param source Source containing the animations
  50834. * @param destination Target to store the animations
  50835. */
  50836. Animation.AppendSerializedAnimations = function (source, destination) {
  50837. if (source.animations) {
  50838. destination.animations = [];
  50839. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50840. var animation = source.animations[animationIndex];
  50841. destination.animations.push(animation.serialize());
  50842. }
  50843. }
  50844. };
  50845. /**
  50846. * Use matrix interpolation instead of using direct key value when animating matrices
  50847. */
  50848. Animation.AllowMatricesInterpolation = false;
  50849. /**
  50850. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50851. */
  50852. Animation.AllowMatrixDecomposeForInterpolation = true;
  50853. // Statics
  50854. /**
  50855. * Float animation type
  50856. */
  50857. Animation._ANIMATIONTYPE_FLOAT = 0;
  50858. /**
  50859. * Vector3 animation type
  50860. */
  50861. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50862. /**
  50863. * Quaternion animation type
  50864. */
  50865. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50866. /**
  50867. * Matrix animation type
  50868. */
  50869. Animation._ANIMATIONTYPE_MATRIX = 3;
  50870. /**
  50871. * Color3 animation type
  50872. */
  50873. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50874. /**
  50875. * Vector2 animation type
  50876. */
  50877. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50878. /**
  50879. * Size animation type
  50880. */
  50881. Animation._ANIMATIONTYPE_SIZE = 6;
  50882. /**
  50883. * Relative Loop Mode
  50884. */
  50885. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50886. /**
  50887. * Cycle Loop Mode
  50888. */
  50889. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50890. /**
  50891. * Constant Loop Mode
  50892. */
  50893. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50894. return Animation;
  50895. }());
  50896. BABYLON.Animation = Animation;
  50897. })(BABYLON || (BABYLON = {}));
  50898. //# sourceMappingURL=babylon.animation.js.map
  50899. var BABYLON;
  50900. (function (BABYLON) {
  50901. /**
  50902. * This class defines the direct association between an animation and a target
  50903. */
  50904. var TargetedAnimation = /** @class */ (function () {
  50905. function TargetedAnimation() {
  50906. }
  50907. return TargetedAnimation;
  50908. }());
  50909. BABYLON.TargetedAnimation = TargetedAnimation;
  50910. /**
  50911. * Use this class to create coordinated animations on multiple targets
  50912. */
  50913. var AnimationGroup = /** @class */ (function () {
  50914. function AnimationGroup(name, scene) {
  50915. if (scene === void 0) { scene = null; }
  50916. this.name = name;
  50917. this._targetedAnimations = new Array();
  50918. this._animatables = new Array();
  50919. this._from = Number.MAX_VALUE;
  50920. this._to = -Number.MAX_VALUE;
  50921. this._speedRatio = 1;
  50922. this.onAnimationEndObservable = new BABYLON.Observable();
  50923. /**
  50924. * This observable will notify when all animations have ended.
  50925. */
  50926. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  50927. /**
  50928. * This observable will notify when all animations have paused.
  50929. */
  50930. this.onAnimationGroupPauseObservable = new BABYLON.Observable();
  50931. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50932. this._scene.animationGroups.push(this);
  50933. }
  50934. Object.defineProperty(AnimationGroup.prototype, "from", {
  50935. /**
  50936. * Gets the first frame
  50937. */
  50938. get: function () {
  50939. return this._from;
  50940. },
  50941. enumerable: true,
  50942. configurable: true
  50943. });
  50944. Object.defineProperty(AnimationGroup.prototype, "to", {
  50945. /**
  50946. * Gets the last frame
  50947. */
  50948. get: function () {
  50949. return this._to;
  50950. },
  50951. enumerable: true,
  50952. configurable: true
  50953. });
  50954. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50955. /**
  50956. * Define if the animations are started
  50957. */
  50958. get: function () {
  50959. return this._isStarted;
  50960. },
  50961. enumerable: true,
  50962. configurable: true
  50963. });
  50964. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50965. /**
  50966. * Gets or sets the speed ratio to use for all animations
  50967. */
  50968. get: function () {
  50969. return this._speedRatio;
  50970. },
  50971. /**
  50972. * Gets or sets the speed ratio to use for all animations
  50973. */
  50974. set: function (value) {
  50975. if (this._speedRatio === value) {
  50976. return;
  50977. }
  50978. this._speedRatio = value;
  50979. for (var index = 0; index < this._animatables.length; index++) {
  50980. var animatable = this._animatables[index];
  50981. animatable.speedRatio = this._speedRatio;
  50982. }
  50983. },
  50984. enumerable: true,
  50985. configurable: true
  50986. });
  50987. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50988. /**
  50989. * Gets the targeted animations for this animation group
  50990. */
  50991. get: function () {
  50992. return this._targetedAnimations;
  50993. },
  50994. enumerable: true,
  50995. configurable: true
  50996. });
  50997. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50998. /**
  50999. * returning the list of animatables controlled by this animation group.
  51000. */
  51001. get: function () {
  51002. return this._animatables;
  51003. },
  51004. enumerable: true,
  51005. configurable: true
  51006. });
  51007. /**
  51008. * Add an animation (with its target) in the group
  51009. * @param animation defines the animation we want to add
  51010. * @param target defines the target of the animation
  51011. * @returns the {BABYLON.TargetedAnimation} object
  51012. */
  51013. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  51014. var targetedAnimation = {
  51015. animation: animation,
  51016. target: target
  51017. };
  51018. var keys = animation.getKeys();
  51019. if (this._from > keys[0].frame) {
  51020. this._from = keys[0].frame;
  51021. }
  51022. if (this._to < keys[keys.length - 1].frame) {
  51023. this._to = keys[keys.length - 1].frame;
  51024. }
  51025. this._targetedAnimations.push(targetedAnimation);
  51026. return targetedAnimation;
  51027. };
  51028. /**
  51029. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  51030. * It can add constant keys at begin or end
  51031. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  51032. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  51033. */
  51034. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  51035. if (beginFrame === void 0) { beginFrame = null; }
  51036. if (endFrame === void 0) { endFrame = null; }
  51037. if (beginFrame == null)
  51038. beginFrame = this._from;
  51039. if (endFrame == null)
  51040. endFrame = this._to;
  51041. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51042. var targetedAnimation = this._targetedAnimations[index];
  51043. var keys = targetedAnimation.animation.getKeys();
  51044. var startKey = keys[0];
  51045. var endKey = keys[keys.length - 1];
  51046. if (startKey.frame > beginFrame) {
  51047. var newKey = {
  51048. frame: beginFrame,
  51049. value: startKey.value,
  51050. inTangent: startKey.inTangent,
  51051. outTangent: startKey.outTangent,
  51052. interpolation: startKey.interpolation
  51053. };
  51054. keys.splice(0, 0, newKey);
  51055. }
  51056. if (endKey.frame < endFrame) {
  51057. var newKey = {
  51058. frame: endFrame,
  51059. value: endKey.value,
  51060. inTangent: endKey.outTangent,
  51061. outTangent: endKey.outTangent,
  51062. interpolation: endKey.interpolation
  51063. };
  51064. keys.push(newKey);
  51065. }
  51066. }
  51067. this._from = beginFrame;
  51068. this._to = endFrame;
  51069. return this;
  51070. };
  51071. /**
  51072. * Start all animations on given targets
  51073. * @param loop defines if animations must loop
  51074. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51075. * @param from defines the from key (optional)
  51076. * @param to defines the to key (optional)
  51077. * @returns the current animation group
  51078. */
  51079. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51080. var _this = this;
  51081. if (loop === void 0) { loop = false; }
  51082. if (speedRatio === void 0) { speedRatio = 1; }
  51083. if (this._isStarted || this._targetedAnimations.length === 0) {
  51084. return this;
  51085. }
  51086. var _loop_1 = function (targetedAnimation) {
  51087. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  51088. animatable.onAnimationEnd = function () {
  51089. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51090. _this._checkAnimationGroupEnded(animatable);
  51091. };
  51092. this_1._animatables.push(animatable);
  51093. };
  51094. var this_1 = this;
  51095. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51096. var targetedAnimation = _a[_i];
  51097. _loop_1(targetedAnimation);
  51098. }
  51099. this._speedRatio = speedRatio;
  51100. this._isStarted = true;
  51101. return this;
  51102. };
  51103. /**
  51104. * Pause all animations
  51105. */
  51106. AnimationGroup.prototype.pause = function () {
  51107. if (!this._isStarted) {
  51108. return this;
  51109. }
  51110. for (var index = 0; index < this._animatables.length; index++) {
  51111. var animatable = this._animatables[index];
  51112. animatable.pause();
  51113. }
  51114. this.onAnimationGroupPauseObservable.notifyObservers(this);
  51115. return this;
  51116. };
  51117. /**
  51118. * Play all animations to initial state
  51119. * This function will start() the animations if they were not started or will restart() them if they were paused
  51120. * @param loop defines if animations must loop
  51121. */
  51122. AnimationGroup.prototype.play = function (loop) {
  51123. // only if all animatables are ready and exist
  51124. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  51125. if (loop !== undefined) {
  51126. for (var index = 0; index < this._animatables.length; index++) {
  51127. var animatable = this._animatables[index];
  51128. animatable.loopAnimation = loop;
  51129. }
  51130. }
  51131. this.restart();
  51132. }
  51133. else {
  51134. this.stop();
  51135. this.start(loop, this._speedRatio);
  51136. }
  51137. return this;
  51138. };
  51139. /**
  51140. * Reset all animations to initial state
  51141. */
  51142. AnimationGroup.prototype.reset = function () {
  51143. if (!this._isStarted) {
  51144. return this;
  51145. }
  51146. for (var index = 0; index < this._animatables.length; index++) {
  51147. var animatable = this._animatables[index];
  51148. animatable.reset();
  51149. }
  51150. return this;
  51151. };
  51152. /**
  51153. * Restart animations from key 0
  51154. */
  51155. AnimationGroup.prototype.restart = function () {
  51156. if (!this._isStarted) {
  51157. return this;
  51158. }
  51159. for (var index = 0; index < this._animatables.length; index++) {
  51160. var animatable = this._animatables[index];
  51161. animatable.restart();
  51162. }
  51163. return this;
  51164. };
  51165. /**
  51166. * Stop all animations
  51167. */
  51168. AnimationGroup.prototype.stop = function () {
  51169. if (!this._isStarted) {
  51170. return this;
  51171. }
  51172. var list = this._animatables.slice();
  51173. for (var index = 0; index < list.length; index++) {
  51174. list[index].stop();
  51175. }
  51176. this._isStarted = false;
  51177. return this;
  51178. };
  51179. /**
  51180. * Set animation weight for all animatables
  51181. * @param weight defines the weight to use
  51182. * @return the animationGroup
  51183. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51184. */
  51185. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  51186. for (var index = 0; index < this._animatables.length; index++) {
  51187. var animatable = this._animatables[index];
  51188. animatable.weight = weight;
  51189. }
  51190. return this;
  51191. };
  51192. /**
  51193. * Synchronize and normalize all animatables with a source animatable
  51194. * @param root defines the root animatable to synchronize with
  51195. * @return the animationGroup
  51196. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51197. */
  51198. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  51199. for (var index = 0; index < this._animatables.length; index++) {
  51200. var animatable = this._animatables[index];
  51201. animatable.syncWith(root);
  51202. }
  51203. return this;
  51204. };
  51205. /**
  51206. * Goes to a specific frame in this animation group
  51207. * @param frame the frame number to go to
  51208. * @return the animationGroup
  51209. */
  51210. AnimationGroup.prototype.goToFrame = function (frame) {
  51211. if (!this._isStarted) {
  51212. return this;
  51213. }
  51214. for (var index = 0; index < this._animatables.length; index++) {
  51215. var animatable = this._animatables[index];
  51216. animatable.goToFrame(frame);
  51217. }
  51218. return this;
  51219. };
  51220. /**
  51221. * Dispose all associated resources
  51222. */
  51223. AnimationGroup.prototype.dispose = function () {
  51224. this._targetedAnimations = [];
  51225. this._animatables = [];
  51226. var index = this._scene.animationGroups.indexOf(this);
  51227. if (index > -1) {
  51228. this._scene.animationGroups.splice(index, 1);
  51229. }
  51230. };
  51231. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  51232. // animatable should be taken out of the array
  51233. var idx = this._animatables.indexOf(animatable);
  51234. if (idx > -1) {
  51235. this._animatables.splice(idx, 1);
  51236. }
  51237. // all animatables were removed? animation group ended!
  51238. if (this._animatables.length === 0) {
  51239. this._isStarted = false;
  51240. this.onAnimationGroupEndObservable.notifyObservers(this);
  51241. }
  51242. };
  51243. return AnimationGroup;
  51244. }());
  51245. BABYLON.AnimationGroup = AnimationGroup;
  51246. })(BABYLON || (BABYLON = {}));
  51247. //# sourceMappingURL=babylon.animationGroup.js.map
  51248. var BABYLON;
  51249. (function (BABYLON) {
  51250. // Static values to help the garbage collector
  51251. // Quaternion
  51252. var _staticOffsetValueQuaternion = Object.freeze(new BABYLON.Quaternion(0, 0, 0, 0));
  51253. // Vector3
  51254. var _staticOffsetValueVector3 = Object.freeze(BABYLON.Vector3.Zero());
  51255. // Vector2
  51256. var _staticOffsetValueVector2 = Object.freeze(BABYLON.Vector2.Zero());
  51257. // Size
  51258. var _staticOffsetValueSize = Object.freeze(BABYLON.Size.Zero());
  51259. // Color3
  51260. var _staticOffsetValueColor3 = Object.freeze(BABYLON.Color3.Black());
  51261. /**
  51262. * Defines a runtime animation
  51263. */
  51264. var RuntimeAnimation = /** @class */ (function () {
  51265. /**
  51266. * Create a new RuntimeAnimation object
  51267. * @param target defines the target of the animation
  51268. * @param animation defines the source animation object
  51269. * @param scene defines the hosting scene
  51270. * @param host defines the initiating Animatable
  51271. */
  51272. function RuntimeAnimation(target, animation, scene, host) {
  51273. var _this = this;
  51274. this._events = new Array();
  51275. /**
  51276. * The current frame of the runtime animation
  51277. */
  51278. this._currentFrame = 0;
  51279. /**
  51280. * The original value of the runtime animation
  51281. */
  51282. this._originalValue = new Array();
  51283. /**
  51284. * The offsets cache of the runtime animation
  51285. */
  51286. this._offsetsCache = {};
  51287. /**
  51288. * The high limits cache of the runtime animation
  51289. */
  51290. this._highLimitsCache = {};
  51291. /**
  51292. * Specifies if the runtime animation has been stopped
  51293. */
  51294. this._stopped = false;
  51295. /**
  51296. * The blending factor of the runtime animation
  51297. */
  51298. this._blendingFactor = 0;
  51299. /**
  51300. * The target path of the runtime animation
  51301. */
  51302. this._targetPath = "";
  51303. /**
  51304. * The weight of the runtime animation
  51305. */
  51306. this._weight = 1.0;
  51307. /**
  51308. * The ratio offset of the runtime animation
  51309. */
  51310. this._ratioOffset = 0;
  51311. /**
  51312. * The previous delay of the runtime animation
  51313. */
  51314. this._previousDelay = 0;
  51315. /**
  51316. * The previous ratio of the runtime animation
  51317. */
  51318. this._previousRatio = 0;
  51319. this._animation = animation;
  51320. this._target = target;
  51321. this._scene = scene;
  51322. this._host = host;
  51323. animation._runtimeAnimations.push(this);
  51324. // Cloning events locally
  51325. var events = animation.getEvents();
  51326. if (events && events.length > 0) {
  51327. events.forEach(function (e) {
  51328. _this._events.push(e._clone());
  51329. });
  51330. }
  51331. }
  51332. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51333. /**
  51334. * Gets the current frame of the runtime animation
  51335. */
  51336. get: function () {
  51337. return this._currentFrame;
  51338. },
  51339. enumerable: true,
  51340. configurable: true
  51341. });
  51342. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51343. /**
  51344. * Gets the weight of the runtime animation
  51345. */
  51346. get: function () {
  51347. return this._weight;
  51348. },
  51349. enumerable: true,
  51350. configurable: true
  51351. });
  51352. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  51353. /**
  51354. * Gets the current value of the runtime animation
  51355. */
  51356. get: function () {
  51357. return this._currentValue;
  51358. },
  51359. enumerable: true,
  51360. configurable: true
  51361. });
  51362. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  51363. /**
  51364. * Gets the target path of the runtime animation
  51365. */
  51366. get: function () {
  51367. return this._targetPath;
  51368. },
  51369. enumerable: true,
  51370. configurable: true
  51371. });
  51372. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  51373. /**
  51374. * Gets the actual target of the runtime animation
  51375. */
  51376. get: function () {
  51377. return this._activeTarget;
  51378. },
  51379. enumerable: true,
  51380. configurable: true
  51381. });
  51382. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  51383. /**
  51384. * Gets the animation from the runtime animation
  51385. */
  51386. get: function () {
  51387. return this._animation;
  51388. },
  51389. enumerable: true,
  51390. configurable: true
  51391. });
  51392. /**
  51393. * Resets the runtime animation to the beginning
  51394. * @param restoreOriginal defines whether to restore the target property to the original value
  51395. */
  51396. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  51397. if (restoreOriginal === void 0) { restoreOriginal = false; }
  51398. if (restoreOriginal) {
  51399. if (this._target instanceof Array) {
  51400. var index = 0;
  51401. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51402. var target = _a[_i];
  51403. if (this._originalValue[index] !== undefined) {
  51404. this._setValue(target, this._originalValue[index], -1);
  51405. }
  51406. index++;
  51407. }
  51408. }
  51409. else {
  51410. if (this._originalValue[0] !== undefined) {
  51411. this._setValue(this._target, this._originalValue[0], -1);
  51412. }
  51413. }
  51414. }
  51415. this._offsetsCache = {};
  51416. this._highLimitsCache = {};
  51417. this._currentFrame = 0;
  51418. this._blendingFactor = 0;
  51419. this._originalValue = new Array();
  51420. // Events
  51421. for (var index = 0; index < this._events.length; index++) {
  51422. this._events[index].isDone = false;
  51423. }
  51424. };
  51425. /**
  51426. * Specifies if the runtime animation is stopped
  51427. * @returns Boolean specifying if the runtime animation is stopped
  51428. */
  51429. RuntimeAnimation.prototype.isStopped = function () {
  51430. return this._stopped;
  51431. };
  51432. /**
  51433. * Disposes of the runtime animation
  51434. */
  51435. RuntimeAnimation.prototype.dispose = function () {
  51436. var index = this._animation.runtimeAnimations.indexOf(this);
  51437. if (index > -1) {
  51438. this._animation.runtimeAnimations.splice(index, 1);
  51439. }
  51440. };
  51441. /**
  51442. * Interpolates the animation from the current frame
  51443. * @param currentFrame The frame to interpolate the animation to
  51444. * @param repeatCount The number of times that the animation should loop
  51445. * @param loopMode The type of looping mode to use
  51446. * @param offsetValue Animation offset value
  51447. * @param highLimitValue The high limit value
  51448. * @returns The interpolated value
  51449. */
  51450. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  51451. this._currentFrame = currentFrame;
  51452. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  51453. this._workValue = BABYLON.Matrix.Zero();
  51454. }
  51455. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  51456. };
  51457. /**
  51458. * Apply the interpolated value to the target
  51459. * @param currentValue defines the value computed by the animation
  51460. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  51461. */
  51462. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  51463. if (weight === void 0) { weight = 1.0; }
  51464. if (this._target instanceof Array) {
  51465. var index = 0;
  51466. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51467. var target = _a[_i];
  51468. this._setValue(target, currentValue, weight, index);
  51469. index++;
  51470. }
  51471. }
  51472. else {
  51473. this._setValue(this._target, currentValue, weight);
  51474. }
  51475. };
  51476. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  51477. if (targetIndex === void 0) { targetIndex = 0; }
  51478. // Set value
  51479. var path;
  51480. var destination;
  51481. var targetPropertyPath = this._animation.targetPropertyPath;
  51482. if (targetPropertyPath.length > 1) {
  51483. var property = target[targetPropertyPath[0]];
  51484. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51485. property = property[targetPropertyPath[index]];
  51486. }
  51487. path = targetPropertyPath[targetPropertyPath.length - 1];
  51488. destination = property;
  51489. }
  51490. else {
  51491. path = targetPropertyPath[0];
  51492. destination = target;
  51493. }
  51494. this._targetPath = path;
  51495. this._activeTarget = destination;
  51496. this._weight = weight;
  51497. if (this._originalValue[targetIndex] === undefined) {
  51498. var originalValue = void 0;
  51499. if (destination.getRestPose && path === "_matrix") { // For bones
  51500. originalValue = destination.getRestPose();
  51501. }
  51502. else {
  51503. originalValue = destination[path];
  51504. }
  51505. if (originalValue && originalValue.clone) {
  51506. this._originalValue[targetIndex] = originalValue.clone();
  51507. }
  51508. else {
  51509. this._originalValue[targetIndex] = originalValue;
  51510. }
  51511. }
  51512. // Blending
  51513. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51514. if (enableBlending && this._blendingFactor <= 1.0) {
  51515. if (!this._originalBlendValue) {
  51516. var originalValue = destination[path];
  51517. if (originalValue.clone) {
  51518. this._originalBlendValue = originalValue.clone();
  51519. }
  51520. else {
  51521. this._originalBlendValue = originalValue;
  51522. }
  51523. }
  51524. if (this._originalBlendValue.m) { // Matrix
  51525. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51526. if (this._currentValue) {
  51527. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51528. }
  51529. else {
  51530. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51531. }
  51532. }
  51533. else {
  51534. if (this._currentValue) {
  51535. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51536. }
  51537. else {
  51538. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51539. }
  51540. }
  51541. }
  51542. else {
  51543. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51544. }
  51545. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51546. this._blendingFactor += blendingSpeed;
  51547. }
  51548. else {
  51549. this._currentValue = currentValue;
  51550. }
  51551. if (weight !== -1.0) {
  51552. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  51553. }
  51554. else {
  51555. destination[path] = this._currentValue;
  51556. }
  51557. if (target.markAsDirty) {
  51558. target.markAsDirty(this._animation.targetProperty);
  51559. }
  51560. };
  51561. /**
  51562. * Gets the loop pmode of the runtime animation
  51563. * @returns Loop Mode
  51564. */
  51565. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51566. if (this._target && this._target.animationPropertiesOverride) {
  51567. return this._target.animationPropertiesOverride.loopMode;
  51568. }
  51569. return this._animation.loopMode;
  51570. };
  51571. /**
  51572. * Move the current animation to a given frame
  51573. * @param frame defines the frame to move to
  51574. */
  51575. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51576. var keys = this._animation.getKeys();
  51577. if (frame < keys[0].frame) {
  51578. frame = keys[0].frame;
  51579. }
  51580. else if (frame > keys[keys.length - 1].frame) {
  51581. frame = keys[keys.length - 1].frame;
  51582. }
  51583. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51584. this.setValue(currentValue, -1);
  51585. };
  51586. /**
  51587. * @hidden Internal use only
  51588. */
  51589. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51590. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51591. this._ratioOffset = this._previousRatio - newRatio;
  51592. };
  51593. /**
  51594. * Execute the current animation
  51595. * @param delay defines the delay to add to the current frame
  51596. * @param from defines the lower bound of the animation range
  51597. * @param to defines the upper bound of the animation range
  51598. * @param loop defines if the current animation must loop
  51599. * @param speedRatio defines the current speed ratio
  51600. * @param weight defines the weight of the animation (default is -1 so no weight)
  51601. * @returns a boolean indicating if the animation is running
  51602. */
  51603. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51604. if (weight === void 0) { weight = -1.0; }
  51605. var targetPropertyPath = this._animation.targetPropertyPath;
  51606. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51607. this._stopped = true;
  51608. return false;
  51609. }
  51610. var returnValue = true;
  51611. var keys = this._animation.getKeys();
  51612. // Adding a start key at frame 0 if missing
  51613. if (keys[0].frame !== 0) {
  51614. var newKey = { frame: 0, value: keys[0].value };
  51615. keys.splice(0, 0, newKey);
  51616. }
  51617. // Adding a duplicate key when there is only one key at frame zero
  51618. else if (keys.length === 1) {
  51619. var newKey = { frame: 0.001, value: keys[0].value };
  51620. keys.push(newKey);
  51621. }
  51622. // Check limits
  51623. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51624. from = keys[0].frame;
  51625. }
  51626. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51627. to = keys[keys.length - 1].frame;
  51628. }
  51629. //to and from cannot be the same key
  51630. if (from === to) {
  51631. if (from > keys[0].frame) {
  51632. from--;
  51633. }
  51634. else if (to < keys[keys.length - 1].frame) {
  51635. to++;
  51636. }
  51637. }
  51638. // Compute ratio
  51639. var range = to - from;
  51640. var offsetValue;
  51641. // ratio represents the frame delta between from and to
  51642. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51643. var highLimitValue = 0;
  51644. this._previousDelay = delay;
  51645. this._previousRatio = ratio;
  51646. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  51647. returnValue = false;
  51648. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51649. }
  51650. else {
  51651. // Get max value if required
  51652. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51653. var keyOffset = to.toString() + from.toString();
  51654. if (!this._offsetsCache[keyOffset]) {
  51655. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51656. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51657. switch (this._animation.dataType) {
  51658. // Float
  51659. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51660. this._offsetsCache[keyOffset] = toValue - fromValue;
  51661. break;
  51662. // Quaternion
  51663. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51664. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51665. break;
  51666. // Vector3
  51667. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51668. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51669. // Vector2
  51670. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51671. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51672. // Size
  51673. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51674. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51675. // Color3
  51676. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51677. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51678. default:
  51679. break;
  51680. }
  51681. this._highLimitsCache[keyOffset] = toValue;
  51682. }
  51683. highLimitValue = this._highLimitsCache[keyOffset];
  51684. offsetValue = this._offsetsCache[keyOffset];
  51685. }
  51686. }
  51687. if (offsetValue === undefined) {
  51688. switch (this._animation.dataType) {
  51689. // Float
  51690. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51691. offsetValue = 0;
  51692. break;
  51693. // Quaternion
  51694. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51695. offsetValue = _staticOffsetValueQuaternion;
  51696. break;
  51697. // Vector3
  51698. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51699. offsetValue = _staticOffsetValueVector3;
  51700. break;
  51701. // Vector2
  51702. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51703. offsetValue = _staticOffsetValueVector2;
  51704. break;
  51705. // Size
  51706. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51707. offsetValue = _staticOffsetValueSize;
  51708. break;
  51709. // Color3
  51710. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51711. offsetValue = _staticOffsetValueColor3;
  51712. }
  51713. }
  51714. // Compute value
  51715. var repeatCount = (ratio / range) >> 0;
  51716. var currentFrame = returnValue ? from + ratio % range : to;
  51717. // Need to normalize?
  51718. if (this._host && this._host.syncRoot) {
  51719. var syncRoot = this._host.syncRoot;
  51720. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51721. currentFrame = from + (to - from) * hostNormalizedFrame;
  51722. }
  51723. // Reset events if looping
  51724. var events = this._events;
  51725. if (range > 0 && this.currentFrame > currentFrame ||
  51726. range < 0 && this.currentFrame < currentFrame) {
  51727. // Need to reset animation events
  51728. for (var index = 0; index < events.length; index++) {
  51729. if (!events[index].onlyOnce) {
  51730. // reset event, the animation is looping
  51731. events[index].isDone = false;
  51732. }
  51733. }
  51734. }
  51735. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51736. // Set value
  51737. this.setValue(currentValue, weight);
  51738. // Check events
  51739. for (var index = 0; index < events.length; index++) {
  51740. // Make sure current frame has passed event frame and that event frame is within the current range
  51741. // Also, handle both forward and reverse animations
  51742. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51743. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51744. var event = events[index];
  51745. if (!event.isDone) {
  51746. // If event should be done only once, remove it.
  51747. if (event.onlyOnce) {
  51748. events.splice(index, 1);
  51749. index--;
  51750. }
  51751. event.isDone = true;
  51752. event.action(currentFrame);
  51753. } // Don't do anything if the event has already be done.
  51754. }
  51755. }
  51756. if (!returnValue) {
  51757. this._stopped = true;
  51758. }
  51759. return returnValue;
  51760. };
  51761. return RuntimeAnimation;
  51762. }());
  51763. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51764. })(BABYLON || (BABYLON = {}));
  51765. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51766. var BABYLON;
  51767. (function (BABYLON) {
  51768. /**
  51769. * Class used to store an actual running animation
  51770. */
  51771. var Animatable = /** @class */ (function () {
  51772. /**
  51773. * Creates a new Animatable
  51774. * @param scene defines the hosting scene
  51775. * @param target defines the target object
  51776. * @param fromFrame defines the starting frame number (default is 0)
  51777. * @param toFrame defines the ending frame number (default is 100)
  51778. * @param loopAnimation defines if the animation must loop (default is false)
  51779. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  51780. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  51781. * @param animations defines a group of animation to add to the new Animatable
  51782. */
  51783. function Animatable(scene,
  51784. /** defines the target object */
  51785. target,
  51786. /** defines the starting frame number (default is 0) */
  51787. fromFrame,
  51788. /** defines the ending frame number (default is 100) */
  51789. toFrame,
  51790. /** defines if the animation must loop (default is false) */
  51791. loopAnimation, speedRatio,
  51792. /** defines a callback to call when animation ends if it is not looping */
  51793. onAnimationEnd, animations) {
  51794. if (fromFrame === void 0) { fromFrame = 0; }
  51795. if (toFrame === void 0) { toFrame = 100; }
  51796. if (loopAnimation === void 0) { loopAnimation = false; }
  51797. if (speedRatio === void 0) { speedRatio = 1.0; }
  51798. this.target = target;
  51799. this.fromFrame = fromFrame;
  51800. this.toFrame = toFrame;
  51801. this.loopAnimation = loopAnimation;
  51802. this.onAnimationEnd = onAnimationEnd;
  51803. this._localDelayOffset = null;
  51804. this._pausedDelay = null;
  51805. this._runtimeAnimations = new Array();
  51806. this._paused = false;
  51807. this._speedRatio = 1;
  51808. this._weight = -1.0;
  51809. /**
  51810. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  51811. * This will only apply for non looping animation (default is true)
  51812. */
  51813. this.disposeOnEnd = true;
  51814. /**
  51815. * Gets a boolean indicating if the animation has started
  51816. */
  51817. this.animationStarted = false;
  51818. /**
  51819. * Observer raised when the animation ends
  51820. */
  51821. this.onAnimationEndObservable = new BABYLON.Observable();
  51822. this._scene = scene;
  51823. if (animations) {
  51824. this.appendAnimations(target, animations);
  51825. }
  51826. this._speedRatio = speedRatio;
  51827. scene._activeAnimatables.push(this);
  51828. }
  51829. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51830. /**
  51831. * Gets the root Animatable used to synchronize and normalize animations
  51832. */
  51833. get: function () {
  51834. return this._syncRoot;
  51835. },
  51836. enumerable: true,
  51837. configurable: true
  51838. });
  51839. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51840. /**
  51841. * Gets the current frame of the first RuntimeAnimation
  51842. * Used to synchronize Animatables
  51843. */
  51844. get: function () {
  51845. if (this._runtimeAnimations.length === 0) {
  51846. return 0;
  51847. }
  51848. return this._runtimeAnimations[0].currentFrame;
  51849. },
  51850. enumerable: true,
  51851. configurable: true
  51852. });
  51853. Object.defineProperty(Animatable.prototype, "weight", {
  51854. /**
  51855. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51856. */
  51857. get: function () {
  51858. return this._weight;
  51859. },
  51860. set: function (value) {
  51861. if (value === -1) { // -1 is ok and means no weight
  51862. this._weight = -1;
  51863. return;
  51864. }
  51865. // Else weight must be in [0, 1] range
  51866. this._weight = Math.min(Math.max(value, 0), 1.0);
  51867. },
  51868. enumerable: true,
  51869. configurable: true
  51870. });
  51871. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51872. /**
  51873. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51874. */
  51875. get: function () {
  51876. return this._speedRatio;
  51877. },
  51878. set: function (value) {
  51879. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51880. var animation = this._runtimeAnimations[index];
  51881. animation._prepareForSpeedRatioChange(value);
  51882. }
  51883. this._speedRatio = value;
  51884. },
  51885. enumerable: true,
  51886. configurable: true
  51887. });
  51888. // Methods
  51889. /**
  51890. * Synchronize and normalize current Animatable with a source Animatable
  51891. * This is useful when using animation weights and when animations are not of the same length
  51892. * @param root defines the root Animatable to synchronize with
  51893. * @returns the current Animatable
  51894. */
  51895. Animatable.prototype.syncWith = function (root) {
  51896. this._syncRoot = root;
  51897. if (root) {
  51898. // Make sure this animatable will animate after the root
  51899. var index = this._scene._activeAnimatables.indexOf(this);
  51900. if (index > -1) {
  51901. this._scene._activeAnimatables.splice(index, 1);
  51902. this._scene._activeAnimatables.push(this);
  51903. }
  51904. }
  51905. return this;
  51906. };
  51907. /**
  51908. * Gets the list of runtime animations
  51909. * @returns an array of RuntimeAnimation
  51910. */
  51911. Animatable.prototype.getAnimations = function () {
  51912. return this._runtimeAnimations;
  51913. };
  51914. /**
  51915. * Adds more animations to the current animatable
  51916. * @param target defines the target of the animations
  51917. * @param animations defines the new animations to add
  51918. */
  51919. Animatable.prototype.appendAnimations = function (target, animations) {
  51920. for (var index = 0; index < animations.length; index++) {
  51921. var animation = animations[index];
  51922. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51923. }
  51924. };
  51925. /**
  51926. * Gets the source animation for a specific property
  51927. * @param property defines the propertyu to look for
  51928. * @returns null or the source animation for the given property
  51929. */
  51930. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51931. var runtimeAnimations = this._runtimeAnimations;
  51932. for (var index = 0; index < runtimeAnimations.length; index++) {
  51933. if (runtimeAnimations[index].animation.targetProperty === property) {
  51934. return runtimeAnimations[index].animation;
  51935. }
  51936. }
  51937. return null;
  51938. };
  51939. /**
  51940. * Gets the runtime animation for a specific property
  51941. * @param property defines the propertyu to look for
  51942. * @returns null or the runtime animation for the given property
  51943. */
  51944. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51945. var runtimeAnimations = this._runtimeAnimations;
  51946. for (var index = 0; index < runtimeAnimations.length; index++) {
  51947. if (runtimeAnimations[index].animation.targetProperty === property) {
  51948. return runtimeAnimations[index];
  51949. }
  51950. }
  51951. return null;
  51952. };
  51953. /**
  51954. * Resets the animatable to its original state
  51955. */
  51956. Animatable.prototype.reset = function () {
  51957. var runtimeAnimations = this._runtimeAnimations;
  51958. for (var index = 0; index < runtimeAnimations.length; index++) {
  51959. runtimeAnimations[index].reset(true);
  51960. }
  51961. this._localDelayOffset = null;
  51962. this._pausedDelay = null;
  51963. };
  51964. /**
  51965. * Allows the animatable to blend with current running animations
  51966. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51967. * @param blendingSpeed defines the blending speed to use
  51968. */
  51969. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51970. var runtimeAnimations = this._runtimeAnimations;
  51971. for (var index = 0; index < runtimeAnimations.length; index++) {
  51972. runtimeAnimations[index].animation.enableBlending = true;
  51973. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51974. }
  51975. };
  51976. /**
  51977. * Disable animation blending
  51978. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51979. */
  51980. Animatable.prototype.disableBlending = function () {
  51981. var runtimeAnimations = this._runtimeAnimations;
  51982. for (var index = 0; index < runtimeAnimations.length; index++) {
  51983. runtimeAnimations[index].animation.enableBlending = false;
  51984. }
  51985. };
  51986. /**
  51987. * Jump directly to a given frame
  51988. * @param frame defines the frame to jump to
  51989. */
  51990. Animatable.prototype.goToFrame = function (frame) {
  51991. var runtimeAnimations = this._runtimeAnimations;
  51992. if (runtimeAnimations[0]) {
  51993. var fps = runtimeAnimations[0].animation.framePerSecond;
  51994. var currentFrame = runtimeAnimations[0].currentFrame;
  51995. var adjustTime = frame - currentFrame;
  51996. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51997. if (this._localDelayOffset === null) {
  51998. this._localDelayOffset = 0;
  51999. }
  52000. this._localDelayOffset -= delay;
  52001. }
  52002. for (var index = 0; index < runtimeAnimations.length; index++) {
  52003. runtimeAnimations[index].goToFrame(frame);
  52004. }
  52005. };
  52006. /**
  52007. * Pause the animation
  52008. */
  52009. Animatable.prototype.pause = function () {
  52010. if (this._paused) {
  52011. return;
  52012. }
  52013. this._paused = true;
  52014. };
  52015. /**
  52016. * Restart the animation
  52017. */
  52018. Animatable.prototype.restart = function () {
  52019. this._paused = false;
  52020. };
  52021. Animatable.prototype._raiseOnAnimationEnd = function () {
  52022. if (this.onAnimationEnd) {
  52023. this.onAnimationEnd();
  52024. }
  52025. this.onAnimationEndObservable.notifyObservers(this);
  52026. };
  52027. /**
  52028. * Stop and delete the current animation
  52029. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  52030. * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty)
  52031. */
  52032. Animatable.prototype.stop = function (animationName, targetMask) {
  52033. if (animationName || targetMask) {
  52034. var idx = this._scene._activeAnimatables.indexOf(this);
  52035. if (idx > -1) {
  52036. var runtimeAnimations = this._runtimeAnimations;
  52037. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  52038. var runtimeAnimation = runtimeAnimations[index];
  52039. if (animationName && runtimeAnimation.animation.name != animationName) {
  52040. continue;
  52041. }
  52042. if (targetMask && !targetMask(runtimeAnimation.target)) {
  52043. continue;
  52044. }
  52045. runtimeAnimation.dispose();
  52046. runtimeAnimations.splice(index, 1);
  52047. }
  52048. if (runtimeAnimations.length == 0) {
  52049. this._scene._activeAnimatables.splice(idx, 1);
  52050. this._raiseOnAnimationEnd();
  52051. }
  52052. }
  52053. }
  52054. else {
  52055. var index = this._scene._activeAnimatables.indexOf(this);
  52056. if (index > -1) {
  52057. this._scene._activeAnimatables.splice(index, 1);
  52058. var runtimeAnimations = this._runtimeAnimations;
  52059. for (var index = 0; index < runtimeAnimations.length; index++) {
  52060. runtimeAnimations[index].dispose();
  52061. }
  52062. this._raiseOnAnimationEnd();
  52063. }
  52064. }
  52065. };
  52066. /**
  52067. * Wait asynchronously for the animation to end
  52068. * @returns a promise which will be fullfilled when the animation ends
  52069. */
  52070. Animatable.prototype.waitAsync = function () {
  52071. var _this = this;
  52072. return new Promise(function (resolve, reject) {
  52073. _this.onAnimationEndObservable.add(function () {
  52074. resolve(_this);
  52075. }, undefined, undefined, _this, true);
  52076. });
  52077. };
  52078. /** @hidden */
  52079. Animatable.prototype._animate = function (delay) {
  52080. if (this._paused) {
  52081. this.animationStarted = false;
  52082. if (this._pausedDelay === null) {
  52083. this._pausedDelay = delay;
  52084. }
  52085. return true;
  52086. }
  52087. if (this._localDelayOffset === null) {
  52088. this._localDelayOffset = delay;
  52089. this._pausedDelay = null;
  52090. }
  52091. else if (this._pausedDelay !== null) {
  52092. this._localDelayOffset += delay - this._pausedDelay;
  52093. this._pausedDelay = null;
  52094. }
  52095. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  52096. return true;
  52097. }
  52098. // Animating
  52099. var running = false;
  52100. var runtimeAnimations = this._runtimeAnimations;
  52101. var index;
  52102. for (index = 0; index < runtimeAnimations.length; index++) {
  52103. var animation = runtimeAnimations[index];
  52104. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  52105. running = running || isRunning;
  52106. }
  52107. this.animationStarted = running;
  52108. if (!running) {
  52109. if (this.disposeOnEnd) {
  52110. // Remove from active animatables
  52111. index = this._scene._activeAnimatables.indexOf(this);
  52112. this._scene._activeAnimatables.splice(index, 1);
  52113. // Dispose all runtime animations
  52114. for (index = 0; index < runtimeAnimations.length; index++) {
  52115. runtimeAnimations[index].dispose();
  52116. }
  52117. }
  52118. this._raiseOnAnimationEnd();
  52119. if (this.disposeOnEnd) {
  52120. this.onAnimationEnd = null;
  52121. this.onAnimationEndObservable.clear();
  52122. }
  52123. }
  52124. return running;
  52125. };
  52126. return Animatable;
  52127. }());
  52128. BABYLON.Animatable = Animatable;
  52129. })(BABYLON || (BABYLON = {}));
  52130. //# sourceMappingURL=babylon.animatable.js.map
  52131. var BABYLON;
  52132. (function (BABYLON) {
  52133. var EasingFunction = /** @class */ (function () {
  52134. function EasingFunction() {
  52135. // Properties
  52136. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  52137. }
  52138. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  52139. get: function () {
  52140. return EasingFunction._EASINGMODE_EASEIN;
  52141. },
  52142. enumerable: true,
  52143. configurable: true
  52144. });
  52145. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  52146. get: function () {
  52147. return EasingFunction._EASINGMODE_EASEOUT;
  52148. },
  52149. enumerable: true,
  52150. configurable: true
  52151. });
  52152. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  52153. get: function () {
  52154. return EasingFunction._EASINGMODE_EASEINOUT;
  52155. },
  52156. enumerable: true,
  52157. configurable: true
  52158. });
  52159. EasingFunction.prototype.setEasingMode = function (easingMode) {
  52160. var n = Math.min(Math.max(easingMode, 0), 2);
  52161. this._easingMode = n;
  52162. };
  52163. EasingFunction.prototype.getEasingMode = function () {
  52164. return this._easingMode;
  52165. };
  52166. EasingFunction.prototype.easeInCore = function (gradient) {
  52167. throw new Error('You must implement this method');
  52168. };
  52169. EasingFunction.prototype.ease = function (gradient) {
  52170. switch (this._easingMode) {
  52171. case EasingFunction.EASINGMODE_EASEIN:
  52172. return this.easeInCore(gradient);
  52173. case EasingFunction.EASINGMODE_EASEOUT:
  52174. return (1 - this.easeInCore(1 - gradient));
  52175. }
  52176. if (gradient >= 0.5) {
  52177. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  52178. }
  52179. return (this.easeInCore(gradient * 2) * 0.5);
  52180. };
  52181. //Statics
  52182. EasingFunction._EASINGMODE_EASEIN = 0;
  52183. EasingFunction._EASINGMODE_EASEOUT = 1;
  52184. EasingFunction._EASINGMODE_EASEINOUT = 2;
  52185. return EasingFunction;
  52186. }());
  52187. BABYLON.EasingFunction = EasingFunction;
  52188. var CircleEase = /** @class */ (function (_super) {
  52189. __extends(CircleEase, _super);
  52190. function CircleEase() {
  52191. return _super !== null && _super.apply(this, arguments) || this;
  52192. }
  52193. CircleEase.prototype.easeInCore = function (gradient) {
  52194. gradient = Math.max(0, Math.min(1, gradient));
  52195. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  52196. };
  52197. return CircleEase;
  52198. }(EasingFunction));
  52199. BABYLON.CircleEase = CircleEase;
  52200. var BackEase = /** @class */ (function (_super) {
  52201. __extends(BackEase, _super);
  52202. function BackEase(amplitude) {
  52203. if (amplitude === void 0) { amplitude = 1; }
  52204. var _this = _super.call(this) || this;
  52205. _this.amplitude = amplitude;
  52206. return _this;
  52207. }
  52208. BackEase.prototype.easeInCore = function (gradient) {
  52209. var num = Math.max(0, this.amplitude);
  52210. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52211. };
  52212. return BackEase;
  52213. }(EasingFunction));
  52214. BABYLON.BackEase = BackEase;
  52215. var BounceEase = /** @class */ (function (_super) {
  52216. __extends(BounceEase, _super);
  52217. function BounceEase(bounces, bounciness) {
  52218. if (bounces === void 0) { bounces = 3; }
  52219. if (bounciness === void 0) { bounciness = 2; }
  52220. var _this = _super.call(this) || this;
  52221. _this.bounces = bounces;
  52222. _this.bounciness = bounciness;
  52223. return _this;
  52224. }
  52225. BounceEase.prototype.easeInCore = function (gradient) {
  52226. var y = Math.max(0.0, this.bounces);
  52227. var bounciness = this.bounciness;
  52228. if (bounciness <= 1.0) {
  52229. bounciness = 1.001;
  52230. }
  52231. var num9 = Math.pow(bounciness, y);
  52232. var num5 = 1.0 - bounciness;
  52233. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52234. var num15 = gradient * num4;
  52235. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52236. var num3 = Math.floor(num65);
  52237. var num13 = num3 + 1.0;
  52238. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52239. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52240. var num7 = (num8 + num12) * 0.5;
  52241. var num6 = gradient - num7;
  52242. var num2 = num7 - num8;
  52243. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52244. };
  52245. return BounceEase;
  52246. }(EasingFunction));
  52247. BABYLON.BounceEase = BounceEase;
  52248. var CubicEase = /** @class */ (function (_super) {
  52249. __extends(CubicEase, _super);
  52250. function CubicEase() {
  52251. return _super !== null && _super.apply(this, arguments) || this;
  52252. }
  52253. CubicEase.prototype.easeInCore = function (gradient) {
  52254. return (gradient * gradient * gradient);
  52255. };
  52256. return CubicEase;
  52257. }(EasingFunction));
  52258. BABYLON.CubicEase = CubicEase;
  52259. var ElasticEase = /** @class */ (function (_super) {
  52260. __extends(ElasticEase, _super);
  52261. function ElasticEase(oscillations, springiness) {
  52262. if (oscillations === void 0) { oscillations = 3; }
  52263. if (springiness === void 0) { springiness = 3; }
  52264. var _this = _super.call(this) || this;
  52265. _this.oscillations = oscillations;
  52266. _this.springiness = springiness;
  52267. return _this;
  52268. }
  52269. ElasticEase.prototype.easeInCore = function (gradient) {
  52270. var num2;
  52271. var num3 = Math.max(0.0, this.oscillations);
  52272. var num = Math.max(0.0, this.springiness);
  52273. if (num == 0) {
  52274. num2 = gradient;
  52275. }
  52276. else {
  52277. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52278. }
  52279. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52280. };
  52281. return ElasticEase;
  52282. }(EasingFunction));
  52283. BABYLON.ElasticEase = ElasticEase;
  52284. var ExponentialEase = /** @class */ (function (_super) {
  52285. __extends(ExponentialEase, _super);
  52286. function ExponentialEase(exponent) {
  52287. if (exponent === void 0) { exponent = 2; }
  52288. var _this = _super.call(this) || this;
  52289. _this.exponent = exponent;
  52290. return _this;
  52291. }
  52292. ExponentialEase.prototype.easeInCore = function (gradient) {
  52293. if (this.exponent <= 0) {
  52294. return gradient;
  52295. }
  52296. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  52297. };
  52298. return ExponentialEase;
  52299. }(EasingFunction));
  52300. BABYLON.ExponentialEase = ExponentialEase;
  52301. var PowerEase = /** @class */ (function (_super) {
  52302. __extends(PowerEase, _super);
  52303. function PowerEase(power) {
  52304. if (power === void 0) { power = 2; }
  52305. var _this = _super.call(this) || this;
  52306. _this.power = power;
  52307. return _this;
  52308. }
  52309. PowerEase.prototype.easeInCore = function (gradient) {
  52310. var y = Math.max(0.0, this.power);
  52311. return Math.pow(gradient, y);
  52312. };
  52313. return PowerEase;
  52314. }(EasingFunction));
  52315. BABYLON.PowerEase = PowerEase;
  52316. var QuadraticEase = /** @class */ (function (_super) {
  52317. __extends(QuadraticEase, _super);
  52318. function QuadraticEase() {
  52319. return _super !== null && _super.apply(this, arguments) || this;
  52320. }
  52321. QuadraticEase.prototype.easeInCore = function (gradient) {
  52322. return (gradient * gradient);
  52323. };
  52324. return QuadraticEase;
  52325. }(EasingFunction));
  52326. BABYLON.QuadraticEase = QuadraticEase;
  52327. var QuarticEase = /** @class */ (function (_super) {
  52328. __extends(QuarticEase, _super);
  52329. function QuarticEase() {
  52330. return _super !== null && _super.apply(this, arguments) || this;
  52331. }
  52332. QuarticEase.prototype.easeInCore = function (gradient) {
  52333. return (gradient * gradient * gradient * gradient);
  52334. };
  52335. return QuarticEase;
  52336. }(EasingFunction));
  52337. BABYLON.QuarticEase = QuarticEase;
  52338. var QuinticEase = /** @class */ (function (_super) {
  52339. __extends(QuinticEase, _super);
  52340. function QuinticEase() {
  52341. return _super !== null && _super.apply(this, arguments) || this;
  52342. }
  52343. QuinticEase.prototype.easeInCore = function (gradient) {
  52344. return (gradient * gradient * gradient * gradient * gradient);
  52345. };
  52346. return QuinticEase;
  52347. }(EasingFunction));
  52348. BABYLON.QuinticEase = QuinticEase;
  52349. var SineEase = /** @class */ (function (_super) {
  52350. __extends(SineEase, _super);
  52351. function SineEase() {
  52352. return _super !== null && _super.apply(this, arguments) || this;
  52353. }
  52354. SineEase.prototype.easeInCore = function (gradient) {
  52355. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  52356. };
  52357. return SineEase;
  52358. }(EasingFunction));
  52359. BABYLON.SineEase = SineEase;
  52360. var BezierCurveEase = /** @class */ (function (_super) {
  52361. __extends(BezierCurveEase, _super);
  52362. function BezierCurveEase(x1, y1, x2, y2) {
  52363. if (x1 === void 0) { x1 = 0; }
  52364. if (y1 === void 0) { y1 = 0; }
  52365. if (x2 === void 0) { x2 = 1; }
  52366. if (y2 === void 0) { y2 = 1; }
  52367. var _this = _super.call(this) || this;
  52368. _this.x1 = x1;
  52369. _this.y1 = y1;
  52370. _this.x2 = x2;
  52371. _this.y2 = y2;
  52372. return _this;
  52373. }
  52374. BezierCurveEase.prototype.easeInCore = function (gradient) {
  52375. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  52376. };
  52377. return BezierCurveEase;
  52378. }(EasingFunction));
  52379. BABYLON.BezierCurveEase = BezierCurveEase;
  52380. })(BABYLON || (BABYLON = {}));
  52381. //# sourceMappingURL=babylon.easing.js.map
  52382. var BABYLON;
  52383. (function (BABYLON) {
  52384. /**
  52385. * A Condition applied to an Action
  52386. */
  52387. var Condition = /** @class */ (function () {
  52388. /**
  52389. * Creates a new Condition
  52390. * @param actionManager the manager of the action the condition is applied to
  52391. */
  52392. function Condition(actionManager) {
  52393. this._actionManager = actionManager;
  52394. }
  52395. /**
  52396. * Check if the current condition is valid
  52397. * @returns a boolean
  52398. */
  52399. Condition.prototype.isValid = function () {
  52400. return true;
  52401. };
  52402. /**
  52403. * Internal only
  52404. * @hidden
  52405. */
  52406. Condition.prototype._getProperty = function (propertyPath) {
  52407. return this._actionManager._getProperty(propertyPath);
  52408. };
  52409. /**
  52410. * Internal only
  52411. * @hidden
  52412. */
  52413. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  52414. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52415. };
  52416. /**
  52417. * Serialize placeholder for child classes
  52418. * @returns the serialized object
  52419. */
  52420. Condition.prototype.serialize = function () {
  52421. };
  52422. /**
  52423. * Internal only
  52424. * @hidden
  52425. */
  52426. Condition.prototype._serialize = function (serializedCondition) {
  52427. return {
  52428. type: 2,
  52429. children: [],
  52430. name: serializedCondition.name,
  52431. properties: serializedCondition.properties
  52432. };
  52433. };
  52434. return Condition;
  52435. }());
  52436. BABYLON.Condition = Condition;
  52437. /**
  52438. * Defines specific conditional operators as extensions of Condition
  52439. */
  52440. var ValueCondition = /** @class */ (function (_super) {
  52441. __extends(ValueCondition, _super);
  52442. /**
  52443. * Creates a new ValueCondition
  52444. * @param actionManager manager for the action the condition applies to
  52445. * @param target for the action
  52446. * @param propertyPath path to specify the property of the target the conditional operator uses
  52447. * @param value the value compared by the conditional operator against the current value of the property
  52448. * @param operator the conditional operator, default ValueCondition.IsEqual
  52449. */
  52450. function ValueCondition(actionManager, target,
  52451. /** path to specify the property of the target the conditional operator uses */
  52452. propertyPath,
  52453. /** the value compared by the conditional operator against the current value of the property */
  52454. value,
  52455. /** the conditional operator, default ValueCondition.IsEqual */
  52456. operator) {
  52457. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  52458. var _this = _super.call(this, actionManager) || this;
  52459. _this.propertyPath = propertyPath;
  52460. _this.value = value;
  52461. _this.operator = operator;
  52462. _this._target = target;
  52463. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  52464. _this._property = _this._getProperty(_this.propertyPath);
  52465. return _this;
  52466. }
  52467. Object.defineProperty(ValueCondition, "IsEqual", {
  52468. /**
  52469. * returns the number for IsEqual
  52470. */
  52471. get: function () {
  52472. return ValueCondition._IsEqual;
  52473. },
  52474. enumerable: true,
  52475. configurable: true
  52476. });
  52477. Object.defineProperty(ValueCondition, "IsDifferent", {
  52478. /**
  52479. * Returns the number for IsDifferent
  52480. */
  52481. get: function () {
  52482. return ValueCondition._IsDifferent;
  52483. },
  52484. enumerable: true,
  52485. configurable: true
  52486. });
  52487. Object.defineProperty(ValueCondition, "IsGreater", {
  52488. /**
  52489. * Returns the number for IsGreater
  52490. */
  52491. get: function () {
  52492. return ValueCondition._IsGreater;
  52493. },
  52494. enumerable: true,
  52495. configurable: true
  52496. });
  52497. Object.defineProperty(ValueCondition, "IsLesser", {
  52498. /**
  52499. * Returns the number for IsLesser
  52500. */
  52501. get: function () {
  52502. return ValueCondition._IsLesser;
  52503. },
  52504. enumerable: true,
  52505. configurable: true
  52506. });
  52507. /**
  52508. * Compares the given value with the property value for the specified conditional operator
  52509. * @returns the result of the comparison
  52510. */
  52511. ValueCondition.prototype.isValid = function () {
  52512. switch (this.operator) {
  52513. case ValueCondition.IsGreater:
  52514. return this._effectiveTarget[this._property] > this.value;
  52515. case ValueCondition.IsLesser:
  52516. return this._effectiveTarget[this._property] < this.value;
  52517. case ValueCondition.IsEqual:
  52518. case ValueCondition.IsDifferent:
  52519. var check;
  52520. if (this.value.equals) {
  52521. check = this.value.equals(this._effectiveTarget[this._property]);
  52522. }
  52523. else {
  52524. check = this.value === this._effectiveTarget[this._property];
  52525. }
  52526. return this.operator === ValueCondition.IsEqual ? check : !check;
  52527. }
  52528. return false;
  52529. };
  52530. /**
  52531. * Serialize the ValueCondition into a JSON compatible object
  52532. * @returns serialization object
  52533. */
  52534. ValueCondition.prototype.serialize = function () {
  52535. return this._serialize({
  52536. name: "ValueCondition",
  52537. properties: [
  52538. BABYLON.Action._GetTargetProperty(this._target),
  52539. { name: "propertyPath", value: this.propertyPath },
  52540. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52541. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  52542. ]
  52543. });
  52544. };
  52545. /**
  52546. * Gets the name of the conditional operator for the ValueCondition
  52547. * @param operator the conditional operator
  52548. * @returns the name
  52549. */
  52550. ValueCondition.GetOperatorName = function (operator) {
  52551. switch (operator) {
  52552. case ValueCondition._IsEqual: return "IsEqual";
  52553. case ValueCondition._IsDifferent: return "IsDifferent";
  52554. case ValueCondition._IsGreater: return "IsGreater";
  52555. case ValueCondition._IsLesser: return "IsLesser";
  52556. default: return "";
  52557. }
  52558. };
  52559. /**
  52560. * Internal only
  52561. * @hidden
  52562. */
  52563. ValueCondition._IsEqual = 0;
  52564. /**
  52565. * Internal only
  52566. * @hidden
  52567. */
  52568. ValueCondition._IsDifferent = 1;
  52569. /**
  52570. * Internal only
  52571. * @hidden
  52572. */
  52573. ValueCondition._IsGreater = 2;
  52574. /**
  52575. * Internal only
  52576. * @hidden
  52577. */
  52578. ValueCondition._IsLesser = 3;
  52579. return ValueCondition;
  52580. }(Condition));
  52581. BABYLON.ValueCondition = ValueCondition;
  52582. /**
  52583. * Defines a predicate condition as an extension of Condition
  52584. */
  52585. var PredicateCondition = /** @class */ (function (_super) {
  52586. __extends(PredicateCondition, _super);
  52587. /**
  52588. * Creates a new PredicateCondition
  52589. * @param actionManager manager for the action the condition applies to
  52590. * @param predicate defines the predicate function used to validate the condition
  52591. */
  52592. function PredicateCondition(actionManager,
  52593. /** defines the predicate function used to validate the condition */
  52594. predicate) {
  52595. var _this = _super.call(this, actionManager) || this;
  52596. _this.predicate = predicate;
  52597. return _this;
  52598. }
  52599. /**
  52600. * @returns the validity of the predicate condition
  52601. */
  52602. PredicateCondition.prototype.isValid = function () {
  52603. return this.predicate();
  52604. };
  52605. return PredicateCondition;
  52606. }(Condition));
  52607. BABYLON.PredicateCondition = PredicateCondition;
  52608. /**
  52609. * Defines a state condition as an extension of Condition
  52610. */
  52611. var StateCondition = /** @class */ (function (_super) {
  52612. __extends(StateCondition, _super);
  52613. /**
  52614. * Creates a new StateCondition
  52615. * @param actionManager manager for the action the condition applies to
  52616. * @param target of the condition
  52617. * @param value to compare with target state
  52618. */
  52619. function StateCondition(actionManager, target, value) {
  52620. var _this = _super.call(this, actionManager) || this;
  52621. _this.value = value;
  52622. _this._target = target;
  52623. return _this;
  52624. }
  52625. /**
  52626. * @returns the validity of the state
  52627. */
  52628. StateCondition.prototype.isValid = function () {
  52629. return this._target.state === this.value;
  52630. };
  52631. /**
  52632. * Serialize the StateCondition into a JSON compatible object
  52633. * @returns serialization object
  52634. */
  52635. StateCondition.prototype.serialize = function () {
  52636. return this._serialize({
  52637. name: "StateCondition",
  52638. properties: [
  52639. BABYLON.Action._GetTargetProperty(this._target),
  52640. { name: "value", value: this.value }
  52641. ]
  52642. });
  52643. };
  52644. return StateCondition;
  52645. }(Condition));
  52646. BABYLON.StateCondition = StateCondition;
  52647. })(BABYLON || (BABYLON = {}));
  52648. //# sourceMappingURL=babylon.condition.js.map
  52649. var BABYLON;
  52650. (function (BABYLON) {
  52651. /**
  52652. * The action to be carried out following a trigger
  52653. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52654. */
  52655. var Action = /** @class */ (function () {
  52656. /**
  52657. * Creates a new Action
  52658. * @param triggerOptions the trigger, with or without parameters, for the action
  52659. * @param condition an optional determinant of action
  52660. */
  52661. function Action(
  52662. /** the trigger, with or without parameters, for the action */
  52663. triggerOptions, condition) {
  52664. this.triggerOptions = triggerOptions;
  52665. /**
  52666. * An event triggered prior to action being executed.
  52667. */
  52668. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52669. if (triggerOptions.parameter) {
  52670. this.trigger = triggerOptions.trigger;
  52671. this._triggerParameter = triggerOptions.parameter;
  52672. }
  52673. else if (triggerOptions.trigger) {
  52674. this.trigger = triggerOptions.trigger;
  52675. }
  52676. else {
  52677. this.trigger = triggerOptions;
  52678. }
  52679. this._nextActiveAction = this;
  52680. this._condition = condition;
  52681. }
  52682. /**
  52683. * Internal only
  52684. * @hidden
  52685. */
  52686. Action.prototype._prepare = function () {
  52687. };
  52688. /**
  52689. * Gets the trigger parameters
  52690. * @returns the trigger parameters
  52691. */
  52692. Action.prototype.getTriggerParameter = function () {
  52693. return this._triggerParameter;
  52694. };
  52695. /**
  52696. * Internal only - executes current action event
  52697. * @hidden
  52698. */
  52699. Action.prototype._executeCurrent = function (evt) {
  52700. if (this._nextActiveAction._condition) {
  52701. var condition = this._nextActiveAction._condition;
  52702. var currentRenderId = this._actionManager.getScene().getRenderId();
  52703. // We cache the current evaluation for the current frame
  52704. if (condition._evaluationId === currentRenderId) {
  52705. if (!condition._currentResult) {
  52706. return;
  52707. }
  52708. }
  52709. else {
  52710. condition._evaluationId = currentRenderId;
  52711. if (!condition.isValid()) {
  52712. condition._currentResult = false;
  52713. return;
  52714. }
  52715. condition._currentResult = true;
  52716. }
  52717. }
  52718. this.onBeforeExecuteObservable.notifyObservers(this);
  52719. this._nextActiveAction.execute(evt);
  52720. this.skipToNextActiveAction();
  52721. };
  52722. /**
  52723. * Execute placeholder for child classes
  52724. * @param evt optional action event
  52725. */
  52726. Action.prototype.execute = function (evt) {
  52727. };
  52728. /**
  52729. * Skips to next active action
  52730. */
  52731. Action.prototype.skipToNextActiveAction = function () {
  52732. if (this._nextActiveAction._child) {
  52733. if (!this._nextActiveAction._child._actionManager) {
  52734. this._nextActiveAction._child._actionManager = this._actionManager;
  52735. }
  52736. this._nextActiveAction = this._nextActiveAction._child;
  52737. }
  52738. else {
  52739. this._nextActiveAction = this;
  52740. }
  52741. };
  52742. /**
  52743. * Adds action to chain of actions, may be a DoNothingAction
  52744. * @param action defines the next action to execute
  52745. * @returns The action passed in
  52746. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52747. */
  52748. Action.prototype.then = function (action) {
  52749. this._child = action;
  52750. action._actionManager = this._actionManager;
  52751. action._prepare();
  52752. return action;
  52753. };
  52754. /**
  52755. * Internal only
  52756. * @hidden
  52757. */
  52758. Action.prototype._getProperty = function (propertyPath) {
  52759. return this._actionManager._getProperty(propertyPath);
  52760. };
  52761. /**
  52762. * Internal only
  52763. * @hidden
  52764. */
  52765. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52766. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52767. };
  52768. /**
  52769. * Serialize placeholder for child classes
  52770. * @param parent of child
  52771. * @returns the serialized object
  52772. */
  52773. Action.prototype.serialize = function (parent) {
  52774. };
  52775. /**
  52776. * Internal only called by serialize
  52777. * @hidden
  52778. */
  52779. Action.prototype._serialize = function (serializedAction, parent) {
  52780. var serializationObject = {
  52781. type: 1,
  52782. children: [],
  52783. name: serializedAction.name,
  52784. properties: serializedAction.properties || []
  52785. };
  52786. // Serialize child
  52787. if (this._child) {
  52788. this._child.serialize(serializationObject);
  52789. }
  52790. // Check if "this" has a condition
  52791. if (this._condition) {
  52792. var serializedCondition = this._condition.serialize();
  52793. serializedCondition.children.push(serializationObject);
  52794. if (parent) {
  52795. parent.children.push(serializedCondition);
  52796. }
  52797. return serializedCondition;
  52798. }
  52799. if (parent) {
  52800. parent.children.push(serializationObject);
  52801. }
  52802. return serializationObject;
  52803. };
  52804. /**
  52805. * Internal only
  52806. * @hidden
  52807. */
  52808. Action._SerializeValueAsString = function (value) {
  52809. if (typeof value === "number") {
  52810. return value.toString();
  52811. }
  52812. if (typeof value === "boolean") {
  52813. return value ? "true" : "false";
  52814. }
  52815. if (value instanceof BABYLON.Vector2) {
  52816. return value.x + ", " + value.y;
  52817. }
  52818. if (value instanceof BABYLON.Vector3) {
  52819. return value.x + ", " + value.y + ", " + value.z;
  52820. }
  52821. if (value instanceof BABYLON.Color3) {
  52822. return value.r + ", " + value.g + ", " + value.b;
  52823. }
  52824. if (value instanceof BABYLON.Color4) {
  52825. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52826. }
  52827. return value; // string
  52828. };
  52829. /**
  52830. * Internal only
  52831. * @hidden
  52832. */
  52833. Action._GetTargetProperty = function (target) {
  52834. return {
  52835. name: "target",
  52836. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52837. : target instanceof BABYLON.Light ? "LightProperties"
  52838. : target instanceof BABYLON.Camera ? "CameraProperties"
  52839. : "SceneProperties",
  52840. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52841. };
  52842. };
  52843. return Action;
  52844. }());
  52845. BABYLON.Action = Action;
  52846. })(BABYLON || (BABYLON = {}));
  52847. //# sourceMappingURL=babylon.action.js.map
  52848. var BABYLON;
  52849. (function (BABYLON) {
  52850. /**
  52851. * ActionEvent is the event being sent when an action is triggered.
  52852. */
  52853. var ActionEvent = /** @class */ (function () {
  52854. /**
  52855. * Creates a new ActionEvent
  52856. * @param source The mesh or sprite that triggered the action
  52857. * @param pointerX The X mouse cursor position at the time of the event
  52858. * @param pointerY The Y mouse cursor position at the time of the event
  52859. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52860. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52861. * @param additionalData additional data for the event
  52862. */
  52863. function ActionEvent(
  52864. /** The mesh or sprite that triggered the action */
  52865. source,
  52866. /** The X mouse cursor position at the time of the event */
  52867. pointerX,
  52868. /** The Y mouse cursor position at the time of the event */
  52869. pointerY,
  52870. /** The mesh that is currently pointed at (can be null) */
  52871. meshUnderPointer,
  52872. /** the original (browser) event that triggered the ActionEvent */
  52873. sourceEvent,
  52874. /** additional data for the event */
  52875. additionalData) {
  52876. this.source = source;
  52877. this.pointerX = pointerX;
  52878. this.pointerY = pointerY;
  52879. this.meshUnderPointer = meshUnderPointer;
  52880. this.sourceEvent = sourceEvent;
  52881. this.additionalData = additionalData;
  52882. }
  52883. /**
  52884. * Helper function to auto-create an ActionEvent from a source mesh.
  52885. * @param source The source mesh that triggered the event
  52886. * @param evt The original (browser) event
  52887. * @param additionalData additional data for the event
  52888. * @returns the new ActionEvent
  52889. */
  52890. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52891. var scene = source.getScene();
  52892. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52893. };
  52894. /**
  52895. * Helper function to auto-create an ActionEvent from a source sprite
  52896. * @param source The source sprite that triggered the event
  52897. * @param scene Scene associated with the sprite
  52898. * @param evt The original (browser) event
  52899. * @param additionalData additional data for the event
  52900. * @returns the new ActionEvent
  52901. */
  52902. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52903. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52904. };
  52905. /**
  52906. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52907. * @param scene the scene where the event occurred
  52908. * @param evt The original (browser) event
  52909. * @returns the new ActionEvent
  52910. */
  52911. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52912. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52913. };
  52914. /**
  52915. * Helper function to auto-create an ActionEvent from a primitive
  52916. * @param prim defines the target primitive
  52917. * @param pointerPos defines the pointer position
  52918. * @param evt The original (browser) event
  52919. * @param additionalData additional data for the event
  52920. * @returns the new ActionEvent
  52921. */
  52922. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52923. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52924. };
  52925. return ActionEvent;
  52926. }());
  52927. BABYLON.ActionEvent = ActionEvent;
  52928. /**
  52929. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52930. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52931. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52932. */
  52933. var ActionManager = /** @class */ (function () {
  52934. /**
  52935. * Creates a new action manager
  52936. * @param scene defines the hosting scene
  52937. */
  52938. function ActionManager(scene) {
  52939. // Members
  52940. /** Gets the list of actions */
  52941. this.actions = new Array();
  52942. /** Gets the cursor to use when hovering items */
  52943. this.hoverCursor = '';
  52944. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52945. scene.actionManagers.push(this);
  52946. }
  52947. Object.defineProperty(ActionManager, "NothingTrigger", {
  52948. /**
  52949. * Nothing
  52950. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52951. */
  52952. get: function () {
  52953. return ActionManager._NothingTrigger;
  52954. },
  52955. enumerable: true,
  52956. configurable: true
  52957. });
  52958. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52959. /**
  52960. * On pick
  52961. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52962. */
  52963. get: function () {
  52964. return ActionManager._OnPickTrigger;
  52965. },
  52966. enumerable: true,
  52967. configurable: true
  52968. });
  52969. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52970. /**
  52971. * On left pick
  52972. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52973. */
  52974. get: function () {
  52975. return ActionManager._OnLeftPickTrigger;
  52976. },
  52977. enumerable: true,
  52978. configurable: true
  52979. });
  52980. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52981. /**
  52982. * On right pick
  52983. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52984. */
  52985. get: function () {
  52986. return ActionManager._OnRightPickTrigger;
  52987. },
  52988. enumerable: true,
  52989. configurable: true
  52990. });
  52991. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52992. /**
  52993. * On center pick
  52994. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52995. */
  52996. get: function () {
  52997. return ActionManager._OnCenterPickTrigger;
  52998. },
  52999. enumerable: true,
  53000. configurable: true
  53001. });
  53002. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  53003. /**
  53004. * On pick down
  53005. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53006. */
  53007. get: function () {
  53008. return ActionManager._OnPickDownTrigger;
  53009. },
  53010. enumerable: true,
  53011. configurable: true
  53012. });
  53013. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  53014. /**
  53015. * On double pick
  53016. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53017. */
  53018. get: function () {
  53019. return ActionManager._OnDoublePickTrigger;
  53020. },
  53021. enumerable: true,
  53022. configurable: true
  53023. });
  53024. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  53025. /**
  53026. * On pick up
  53027. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53028. */
  53029. get: function () {
  53030. return ActionManager._OnPickUpTrigger;
  53031. },
  53032. enumerable: true,
  53033. configurable: true
  53034. });
  53035. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  53036. /**
  53037. * On pick out.
  53038. * This trigger will only be raised if you also declared a OnPickDown
  53039. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53040. */
  53041. get: function () {
  53042. return ActionManager._OnPickOutTrigger;
  53043. },
  53044. enumerable: true,
  53045. configurable: true
  53046. });
  53047. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  53048. /**
  53049. * On long press
  53050. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53051. */
  53052. get: function () {
  53053. return ActionManager._OnLongPressTrigger;
  53054. },
  53055. enumerable: true,
  53056. configurable: true
  53057. });
  53058. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  53059. /**
  53060. * On pointer over
  53061. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53062. */
  53063. get: function () {
  53064. return ActionManager._OnPointerOverTrigger;
  53065. },
  53066. enumerable: true,
  53067. configurable: true
  53068. });
  53069. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  53070. /**
  53071. * On pointer out
  53072. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53073. */
  53074. get: function () {
  53075. return ActionManager._OnPointerOutTrigger;
  53076. },
  53077. enumerable: true,
  53078. configurable: true
  53079. });
  53080. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  53081. /**
  53082. * On every frame
  53083. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53084. */
  53085. get: function () {
  53086. return ActionManager._OnEveryFrameTrigger;
  53087. },
  53088. enumerable: true,
  53089. configurable: true
  53090. });
  53091. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  53092. /**
  53093. * On intersection enter
  53094. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53095. */
  53096. get: function () {
  53097. return ActionManager._OnIntersectionEnterTrigger;
  53098. },
  53099. enumerable: true,
  53100. configurable: true
  53101. });
  53102. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  53103. /**
  53104. * On intersection exit
  53105. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53106. */
  53107. get: function () {
  53108. return ActionManager._OnIntersectionExitTrigger;
  53109. },
  53110. enumerable: true,
  53111. configurable: true
  53112. });
  53113. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  53114. /**
  53115. * On key down
  53116. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53117. */
  53118. get: function () {
  53119. return ActionManager._OnKeyDownTrigger;
  53120. },
  53121. enumerable: true,
  53122. configurable: true
  53123. });
  53124. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  53125. /**
  53126. * On key up
  53127. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53128. */
  53129. get: function () {
  53130. return ActionManager._OnKeyUpTrigger;
  53131. },
  53132. enumerable: true,
  53133. configurable: true
  53134. });
  53135. // Methods
  53136. /**
  53137. * Releases all associated resources
  53138. */
  53139. ActionManager.prototype.dispose = function () {
  53140. var index = this._scene.actionManagers.indexOf(this);
  53141. for (var i = 0; i < this.actions.length; i++) {
  53142. var action = this.actions[i];
  53143. ActionManager.Triggers[action.trigger]--;
  53144. if (ActionManager.Triggers[action.trigger] === 0) {
  53145. delete ActionManager.Triggers[action.trigger];
  53146. }
  53147. }
  53148. if (index > -1) {
  53149. this._scene.actionManagers.splice(index, 1);
  53150. }
  53151. };
  53152. /**
  53153. * Gets hosting scene
  53154. * @returns the hosting scene
  53155. */
  53156. ActionManager.prototype.getScene = function () {
  53157. return this._scene;
  53158. };
  53159. /**
  53160. * Does this action manager handles actions of any of the given triggers
  53161. * @param triggers defines the triggers to be tested
  53162. * @return a boolean indicating whether one (or more) of the triggers is handled
  53163. */
  53164. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  53165. for (var index = 0; index < this.actions.length; index++) {
  53166. var action = this.actions[index];
  53167. if (triggers.indexOf(action.trigger) > -1) {
  53168. return true;
  53169. }
  53170. }
  53171. return false;
  53172. };
  53173. /**
  53174. * Does this action manager handles actions of any of the given triggers. This function takes two arguments for
  53175. * speed.
  53176. * @param triggerA defines the trigger to be tested
  53177. * @param triggerB defines the trigger to be tested
  53178. * @return a boolean indicating whether one (or more) of the triggers is handled
  53179. */
  53180. ActionManager.prototype.hasSpecificTriggers2 = function (triggerA, triggerB) {
  53181. for (var index = 0; index < this.actions.length; index++) {
  53182. var action = this.actions[index];
  53183. if (triggerA == action.trigger || triggerB == action.trigger) {
  53184. return true;
  53185. }
  53186. }
  53187. return false;
  53188. };
  53189. /**
  53190. * Does this action manager handles actions of a given trigger
  53191. * @param trigger defines the trigger to be tested
  53192. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  53193. * @return whether the trigger is handled
  53194. */
  53195. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  53196. for (var index = 0; index < this.actions.length; index++) {
  53197. var action = this.actions[index];
  53198. if (action.trigger === trigger) {
  53199. if (parameterPredicate) {
  53200. if (parameterPredicate(action.getTriggerParameter())) {
  53201. return true;
  53202. }
  53203. }
  53204. else {
  53205. return true;
  53206. }
  53207. }
  53208. }
  53209. return false;
  53210. };
  53211. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  53212. /**
  53213. * Does this action manager has pointer triggers
  53214. */
  53215. get: function () {
  53216. for (var index = 0; index < this.actions.length; index++) {
  53217. var action = this.actions[index];
  53218. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  53219. return true;
  53220. }
  53221. }
  53222. return false;
  53223. },
  53224. enumerable: true,
  53225. configurable: true
  53226. });
  53227. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  53228. /**
  53229. * Does this action manager has pick triggers
  53230. */
  53231. get: function () {
  53232. for (var index = 0; index < this.actions.length; index++) {
  53233. var action = this.actions[index];
  53234. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  53235. return true;
  53236. }
  53237. }
  53238. return false;
  53239. },
  53240. enumerable: true,
  53241. configurable: true
  53242. });
  53243. Object.defineProperty(ActionManager, "HasTriggers", {
  53244. /**
  53245. * Does exist one action manager with at least one trigger
  53246. **/
  53247. get: function () {
  53248. for (var t in ActionManager.Triggers) {
  53249. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53250. return true;
  53251. }
  53252. }
  53253. return false;
  53254. },
  53255. enumerable: true,
  53256. configurable: true
  53257. });
  53258. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53259. /**
  53260. * Does exist one action manager with at least one pick trigger
  53261. **/
  53262. get: function () {
  53263. for (var t in ActionManager.Triggers) {
  53264. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53265. var t_int = parseInt(t);
  53266. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  53267. return true;
  53268. }
  53269. }
  53270. }
  53271. return false;
  53272. },
  53273. enumerable: true,
  53274. configurable: true
  53275. });
  53276. /**
  53277. * Does exist one action manager that handles actions of a given trigger
  53278. * @param trigger defines the trigger to be tested
  53279. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53280. **/
  53281. ActionManager.HasSpecificTrigger = function (trigger) {
  53282. for (var t in ActionManager.Triggers) {
  53283. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53284. var t_int = parseInt(t);
  53285. if (t_int === trigger) {
  53286. return true;
  53287. }
  53288. }
  53289. }
  53290. return false;
  53291. };
  53292. /**
  53293. * Registers an action to this action manager
  53294. * @param action defines the action to be registered
  53295. * @return the action amended (prepared) after registration
  53296. */
  53297. ActionManager.prototype.registerAction = function (action) {
  53298. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53299. if (this.getScene().actionManager !== this) {
  53300. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53301. return null;
  53302. }
  53303. }
  53304. this.actions.push(action);
  53305. if (ActionManager.Triggers[action.trigger]) {
  53306. ActionManager.Triggers[action.trigger]++;
  53307. }
  53308. else {
  53309. ActionManager.Triggers[action.trigger] = 1;
  53310. }
  53311. action._actionManager = this;
  53312. action._prepare();
  53313. return action;
  53314. };
  53315. /**
  53316. * Unregisters an action to this action manager
  53317. * @param action defines the action to be unregistered
  53318. * @return a boolean indicating whether the action has been unregistered
  53319. */
  53320. ActionManager.prototype.unregisterAction = function (action) {
  53321. var index = this.actions.indexOf(action);
  53322. if (index !== -1) {
  53323. this.actions.splice(index, 1);
  53324. ActionManager.Triggers[action.trigger] -= 1;
  53325. if (ActionManager.Triggers[action.trigger] === 0) {
  53326. delete ActionManager.Triggers[action.trigger];
  53327. }
  53328. delete action._actionManager;
  53329. return true;
  53330. }
  53331. return false;
  53332. };
  53333. /**
  53334. * Process a specific trigger
  53335. * @param trigger defines the trigger to process
  53336. * @param evt defines the event details to be processed
  53337. */
  53338. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53339. for (var index = 0; index < this.actions.length; index++) {
  53340. var action = this.actions[index];
  53341. if (action.trigger === trigger) {
  53342. if (evt) {
  53343. if (trigger === ActionManager.OnKeyUpTrigger
  53344. || trigger === ActionManager.OnKeyDownTrigger) {
  53345. var parameter = action.getTriggerParameter();
  53346. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53347. if (!parameter.toLowerCase) {
  53348. continue;
  53349. }
  53350. var lowerCase = parameter.toLowerCase();
  53351. if (lowerCase !== evt.sourceEvent.key) {
  53352. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53353. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53354. if (actualkey !== lowerCase) {
  53355. continue;
  53356. }
  53357. }
  53358. }
  53359. }
  53360. }
  53361. action._executeCurrent(evt);
  53362. }
  53363. }
  53364. };
  53365. /** @hidden */
  53366. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53367. var properties = propertyPath.split(".");
  53368. for (var index = 0; index < properties.length - 1; index++) {
  53369. target = target[properties[index]];
  53370. }
  53371. return target;
  53372. };
  53373. /** @hidden */
  53374. ActionManager.prototype._getProperty = function (propertyPath) {
  53375. var properties = propertyPath.split(".");
  53376. return properties[properties.length - 1];
  53377. };
  53378. /**
  53379. * Serialize this manager to a JSON object
  53380. * @param name defines the property name to store this manager
  53381. * @returns a JSON representation of this manager
  53382. */
  53383. ActionManager.prototype.serialize = function (name) {
  53384. var root = {
  53385. children: new Array(),
  53386. name: name,
  53387. type: 3,
  53388. properties: new Array() // Empty for root but required
  53389. };
  53390. for (var i = 0; i < this.actions.length; i++) {
  53391. var triggerObject = {
  53392. type: 0,
  53393. children: new Array(),
  53394. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53395. properties: new Array()
  53396. };
  53397. var triggerOptions = this.actions[i].triggerOptions;
  53398. if (triggerOptions && typeof triggerOptions !== "number") {
  53399. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53400. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  53401. }
  53402. else {
  53403. var parameter = {};
  53404. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53405. if (triggerOptions.parameter.mesh) {
  53406. parameter._meshId = triggerOptions.parameter.mesh.id;
  53407. }
  53408. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53409. }
  53410. }
  53411. // Serialize child action, recursively
  53412. this.actions[i].serialize(triggerObject);
  53413. // Add serialized trigger
  53414. root.children.push(triggerObject);
  53415. }
  53416. return root;
  53417. };
  53418. /**
  53419. * Creates a new ActionManager from a JSON data
  53420. * @param parsedActions defines the JSON data to read from
  53421. * @param object defines the hosting mesh
  53422. * @param scene defines the hosting scene
  53423. */
  53424. ActionManager.Parse = function (parsedActions, object, scene) {
  53425. var actionManager = new ActionManager(scene);
  53426. if (object === null)
  53427. scene.actionManager = actionManager;
  53428. else
  53429. object.actionManager = actionManager;
  53430. // instanciate a new object
  53431. var instanciate = function (name, params) {
  53432. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  53433. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  53434. newInstance.constructor.apply(newInstance, params);
  53435. return newInstance;
  53436. };
  53437. var parseParameter = function (name, value, target, propertyPath) {
  53438. if (propertyPath === null) {
  53439. // String, boolean or float
  53440. var floatValue = parseFloat(value);
  53441. if (value === "true" || value === "false")
  53442. return value === "true";
  53443. else
  53444. return isNaN(floatValue) ? value : floatValue;
  53445. }
  53446. var effectiveTarget = propertyPath.split(".");
  53447. var values = value.split(",");
  53448. // Get effective Target
  53449. for (var i = 0; i < effectiveTarget.length; i++) {
  53450. target = target[effectiveTarget[i]];
  53451. }
  53452. // Return appropriate value with its type
  53453. if (typeof (target) === "boolean")
  53454. return values[0] === "true";
  53455. if (typeof (target) === "string")
  53456. return values[0];
  53457. // Parameters with multiple values such as Vector3 etc.
  53458. var split = new Array();
  53459. for (var i = 0; i < values.length; i++)
  53460. split.push(parseFloat(values[i]));
  53461. if (target instanceof BABYLON.Vector3)
  53462. return BABYLON.Vector3.FromArray(split);
  53463. if (target instanceof BABYLON.Vector4)
  53464. return BABYLON.Vector4.FromArray(split);
  53465. if (target instanceof BABYLON.Color3)
  53466. return BABYLON.Color3.FromArray(split);
  53467. if (target instanceof BABYLON.Color4)
  53468. return BABYLON.Color4.FromArray(split);
  53469. return parseFloat(values[0]);
  53470. };
  53471. // traverse graph per trigger
  53472. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  53473. if (combineArray === void 0) { combineArray = null; }
  53474. if (parsedAction.detached)
  53475. return;
  53476. var parameters = new Array();
  53477. var target = null;
  53478. var propertyPath = null;
  53479. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  53480. // Parameters
  53481. if (parsedAction.type === 2)
  53482. parameters.push(actionManager);
  53483. else
  53484. parameters.push(trigger);
  53485. if (combine) {
  53486. var actions = new Array();
  53487. for (var j = 0; j < parsedAction.combine.length; j++) {
  53488. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  53489. }
  53490. parameters.push(actions);
  53491. }
  53492. else {
  53493. for (var i = 0; i < parsedAction.properties.length; i++) {
  53494. var value = parsedAction.properties[i].value;
  53495. var name = parsedAction.properties[i].name;
  53496. var targetType = parsedAction.properties[i].targetType;
  53497. if (name === "target")
  53498. if (targetType !== null && targetType === "SceneProperties")
  53499. value = target = scene;
  53500. else
  53501. value = target = scene.getNodeByName(value);
  53502. else if (name === "parent")
  53503. value = scene.getNodeByName(value);
  53504. else if (name === "sound")
  53505. value = scene.getSoundByName(value);
  53506. else if (name !== "propertyPath") {
  53507. if (parsedAction.type === 2 && name === "operator")
  53508. value = BABYLON.ValueCondition[value];
  53509. else
  53510. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53511. }
  53512. else {
  53513. propertyPath = value;
  53514. }
  53515. parameters.push(value);
  53516. }
  53517. }
  53518. if (combineArray === null) {
  53519. parameters.push(condition);
  53520. }
  53521. else {
  53522. parameters.push(null);
  53523. }
  53524. // If interpolate value action
  53525. if (parsedAction.name === "InterpolateValueAction") {
  53526. var param = parameters[parameters.length - 2];
  53527. parameters[parameters.length - 1] = param;
  53528. parameters[parameters.length - 2] = condition;
  53529. }
  53530. // Action or condition(s) and not CombineAction
  53531. var newAction = instanciate(parsedAction.name, parameters);
  53532. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53533. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53534. if (action)
  53535. action.then(nothing);
  53536. else
  53537. actionManager.registerAction(nothing);
  53538. action = nothing;
  53539. }
  53540. if (combineArray === null) {
  53541. if (newAction instanceof BABYLON.Condition) {
  53542. condition = newAction;
  53543. newAction = action;
  53544. }
  53545. else {
  53546. condition = null;
  53547. if (action)
  53548. action.then(newAction);
  53549. else
  53550. actionManager.registerAction(newAction);
  53551. }
  53552. }
  53553. else {
  53554. combineArray.push(newAction);
  53555. }
  53556. for (var i = 0; i < parsedAction.children.length; i++)
  53557. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53558. };
  53559. // triggers
  53560. for (var i = 0; i < parsedActions.children.length; i++) {
  53561. var triggerParams;
  53562. var trigger = parsedActions.children[i];
  53563. if (trigger.properties.length > 0) {
  53564. var param = trigger.properties[0].value;
  53565. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53566. if (value._meshId) {
  53567. value.mesh = scene.getMeshByID(value._meshId);
  53568. }
  53569. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53570. }
  53571. else
  53572. triggerParams = ActionManager[trigger.name];
  53573. for (var j = 0; j < trigger.children.length; j++) {
  53574. if (!trigger.detached)
  53575. traverse(trigger.children[j], triggerParams, null, null);
  53576. }
  53577. }
  53578. };
  53579. /**
  53580. * Get a trigger name by index
  53581. * @param trigger defines the trigger index
  53582. * @returns a trigger name
  53583. */
  53584. ActionManager.GetTriggerName = function (trigger) {
  53585. switch (trigger) {
  53586. case 0: return "NothingTrigger";
  53587. case 1: return "OnPickTrigger";
  53588. case 2: return "OnLeftPickTrigger";
  53589. case 3: return "OnRightPickTrigger";
  53590. case 4: return "OnCenterPickTrigger";
  53591. case 5: return "OnPickDownTrigger";
  53592. case 6: return "OnPickUpTrigger";
  53593. case 7: return "OnLongPressTrigger";
  53594. case 8: return "OnPointerOverTrigger";
  53595. case 9: return "OnPointerOutTrigger";
  53596. case 10: return "OnEveryFrameTrigger";
  53597. case 11: return "OnIntersectionEnterTrigger";
  53598. case 12: return "OnIntersectionExitTrigger";
  53599. case 13: return "OnKeyDownTrigger";
  53600. case 14: return "OnKeyUpTrigger";
  53601. case 15: return "OnPickOutTrigger";
  53602. default: return "";
  53603. }
  53604. };
  53605. // Statics
  53606. ActionManager._NothingTrigger = 0;
  53607. ActionManager._OnPickTrigger = 1;
  53608. ActionManager._OnLeftPickTrigger = 2;
  53609. ActionManager._OnRightPickTrigger = 3;
  53610. ActionManager._OnCenterPickTrigger = 4;
  53611. ActionManager._OnPickDownTrigger = 5;
  53612. ActionManager._OnDoublePickTrigger = 6;
  53613. ActionManager._OnPickUpTrigger = 7;
  53614. ActionManager._OnLongPressTrigger = 8;
  53615. ActionManager._OnPointerOverTrigger = 9;
  53616. ActionManager._OnPointerOutTrigger = 10;
  53617. ActionManager._OnEveryFrameTrigger = 11;
  53618. ActionManager._OnIntersectionEnterTrigger = 12;
  53619. ActionManager._OnIntersectionExitTrigger = 13;
  53620. ActionManager._OnKeyDownTrigger = 14;
  53621. ActionManager._OnKeyUpTrigger = 15;
  53622. ActionManager._OnPickOutTrigger = 16;
  53623. /** Gets the list of active triggers */
  53624. ActionManager.Triggers = {};
  53625. return ActionManager;
  53626. }());
  53627. BABYLON.ActionManager = ActionManager;
  53628. })(BABYLON || (BABYLON = {}));
  53629. //# sourceMappingURL=babylon.actionManager.js.map
  53630. var BABYLON;
  53631. (function (BABYLON) {
  53632. var InterpolateValueAction = /** @class */ (function (_super) {
  53633. __extends(InterpolateValueAction, _super);
  53634. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53635. if (duration === void 0) { duration = 1000; }
  53636. var _this = _super.call(this, triggerOptions, condition) || this;
  53637. _this.propertyPath = propertyPath;
  53638. _this.value = value;
  53639. _this.duration = duration;
  53640. _this.stopOtherAnimations = stopOtherAnimations;
  53641. _this.onInterpolationDone = onInterpolationDone;
  53642. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53643. _this._target = _this._effectiveTarget = target;
  53644. return _this;
  53645. }
  53646. /** @hidden */
  53647. InterpolateValueAction.prototype._prepare = function () {
  53648. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53649. this._property = this._getProperty(this.propertyPath);
  53650. };
  53651. InterpolateValueAction.prototype.execute = function () {
  53652. var _this = this;
  53653. var scene = this._actionManager.getScene();
  53654. var keys = [
  53655. {
  53656. frame: 0,
  53657. value: this._effectiveTarget[this._property]
  53658. }, {
  53659. frame: 100,
  53660. value: this.value
  53661. }
  53662. ];
  53663. var dataType;
  53664. if (typeof this.value === "number") {
  53665. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53666. }
  53667. else if (this.value instanceof BABYLON.Color3) {
  53668. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53669. }
  53670. else if (this.value instanceof BABYLON.Vector3) {
  53671. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53672. }
  53673. else if (this.value instanceof BABYLON.Matrix) {
  53674. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53675. }
  53676. else if (this.value instanceof BABYLON.Quaternion) {
  53677. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53678. }
  53679. else {
  53680. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53681. return;
  53682. }
  53683. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53684. animation.setKeys(keys);
  53685. if (this.stopOtherAnimations) {
  53686. scene.stopAnimation(this._effectiveTarget);
  53687. }
  53688. var wrapper = function () {
  53689. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53690. if (_this.onInterpolationDone) {
  53691. _this.onInterpolationDone();
  53692. }
  53693. };
  53694. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53695. };
  53696. InterpolateValueAction.prototype.serialize = function (parent) {
  53697. return _super.prototype._serialize.call(this, {
  53698. name: "InterpolateValueAction",
  53699. properties: [
  53700. BABYLON.Action._GetTargetProperty(this._target),
  53701. { name: "propertyPath", value: this.propertyPath },
  53702. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53703. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53704. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53705. ]
  53706. }, parent);
  53707. };
  53708. return InterpolateValueAction;
  53709. }(BABYLON.Action));
  53710. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53711. })(BABYLON || (BABYLON = {}));
  53712. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53713. var BABYLON;
  53714. (function (BABYLON) {
  53715. var SwitchBooleanAction = /** @class */ (function (_super) {
  53716. __extends(SwitchBooleanAction, _super);
  53717. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53718. var _this = _super.call(this, triggerOptions, condition) || this;
  53719. _this.propertyPath = propertyPath;
  53720. _this._target = _this._effectiveTarget = target;
  53721. return _this;
  53722. }
  53723. /** @hidden */
  53724. SwitchBooleanAction.prototype._prepare = function () {
  53725. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53726. this._property = this._getProperty(this.propertyPath);
  53727. };
  53728. SwitchBooleanAction.prototype.execute = function () {
  53729. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53730. };
  53731. SwitchBooleanAction.prototype.serialize = function (parent) {
  53732. return _super.prototype._serialize.call(this, {
  53733. name: "SwitchBooleanAction",
  53734. properties: [
  53735. BABYLON.Action._GetTargetProperty(this._target),
  53736. { name: "propertyPath", value: this.propertyPath }
  53737. ]
  53738. }, parent);
  53739. };
  53740. return SwitchBooleanAction;
  53741. }(BABYLON.Action));
  53742. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53743. var SetStateAction = /** @class */ (function (_super) {
  53744. __extends(SetStateAction, _super);
  53745. function SetStateAction(triggerOptions, target, value, condition) {
  53746. var _this = _super.call(this, triggerOptions, condition) || this;
  53747. _this.value = value;
  53748. _this._target = target;
  53749. return _this;
  53750. }
  53751. SetStateAction.prototype.execute = function () {
  53752. this._target.state = this.value;
  53753. };
  53754. SetStateAction.prototype.serialize = function (parent) {
  53755. return _super.prototype._serialize.call(this, {
  53756. name: "SetStateAction",
  53757. properties: [
  53758. BABYLON.Action._GetTargetProperty(this._target),
  53759. { name: "value", value: this.value }
  53760. ]
  53761. }, parent);
  53762. };
  53763. return SetStateAction;
  53764. }(BABYLON.Action));
  53765. BABYLON.SetStateAction = SetStateAction;
  53766. var SetValueAction = /** @class */ (function (_super) {
  53767. __extends(SetValueAction, _super);
  53768. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53769. var _this = _super.call(this, triggerOptions, condition) || this;
  53770. _this.propertyPath = propertyPath;
  53771. _this.value = value;
  53772. _this._target = _this._effectiveTarget = target;
  53773. return _this;
  53774. }
  53775. /** @hidden */
  53776. SetValueAction.prototype._prepare = function () {
  53777. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53778. this._property = this._getProperty(this.propertyPath);
  53779. };
  53780. SetValueAction.prototype.execute = function () {
  53781. this._effectiveTarget[this._property] = this.value;
  53782. if (this._target.markAsDirty) {
  53783. this._target.markAsDirty(this._property);
  53784. }
  53785. };
  53786. SetValueAction.prototype.serialize = function (parent) {
  53787. return _super.prototype._serialize.call(this, {
  53788. name: "SetValueAction",
  53789. properties: [
  53790. BABYLON.Action._GetTargetProperty(this._target),
  53791. { name: "propertyPath", value: this.propertyPath },
  53792. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53793. ]
  53794. }, parent);
  53795. };
  53796. return SetValueAction;
  53797. }(BABYLON.Action));
  53798. BABYLON.SetValueAction = SetValueAction;
  53799. var IncrementValueAction = /** @class */ (function (_super) {
  53800. __extends(IncrementValueAction, _super);
  53801. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53802. var _this = _super.call(this, triggerOptions, condition) || this;
  53803. _this.propertyPath = propertyPath;
  53804. _this.value = value;
  53805. _this._target = _this._effectiveTarget = target;
  53806. return _this;
  53807. }
  53808. /** @hidden */
  53809. IncrementValueAction.prototype._prepare = function () {
  53810. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53811. this._property = this._getProperty(this.propertyPath);
  53812. if (typeof this._effectiveTarget[this._property] !== "number") {
  53813. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53814. }
  53815. };
  53816. IncrementValueAction.prototype.execute = function () {
  53817. this._effectiveTarget[this._property] += this.value;
  53818. if (this._target.markAsDirty) {
  53819. this._target.markAsDirty(this._property);
  53820. }
  53821. };
  53822. IncrementValueAction.prototype.serialize = function (parent) {
  53823. return _super.prototype._serialize.call(this, {
  53824. name: "IncrementValueAction",
  53825. properties: [
  53826. BABYLON.Action._GetTargetProperty(this._target),
  53827. { name: "propertyPath", value: this.propertyPath },
  53828. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53829. ]
  53830. }, parent);
  53831. };
  53832. return IncrementValueAction;
  53833. }(BABYLON.Action));
  53834. BABYLON.IncrementValueAction = IncrementValueAction;
  53835. var PlayAnimationAction = /** @class */ (function (_super) {
  53836. __extends(PlayAnimationAction, _super);
  53837. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53838. var _this = _super.call(this, triggerOptions, condition) || this;
  53839. _this.from = from;
  53840. _this.to = to;
  53841. _this.loop = loop;
  53842. _this._target = target;
  53843. return _this;
  53844. }
  53845. /** @hidden */
  53846. PlayAnimationAction.prototype._prepare = function () {
  53847. };
  53848. PlayAnimationAction.prototype.execute = function () {
  53849. var scene = this._actionManager.getScene();
  53850. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53851. };
  53852. PlayAnimationAction.prototype.serialize = function (parent) {
  53853. return _super.prototype._serialize.call(this, {
  53854. name: "PlayAnimationAction",
  53855. properties: [
  53856. BABYLON.Action._GetTargetProperty(this._target),
  53857. { name: "from", value: String(this.from) },
  53858. { name: "to", value: String(this.to) },
  53859. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53860. ]
  53861. }, parent);
  53862. };
  53863. return PlayAnimationAction;
  53864. }(BABYLON.Action));
  53865. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53866. var StopAnimationAction = /** @class */ (function (_super) {
  53867. __extends(StopAnimationAction, _super);
  53868. function StopAnimationAction(triggerOptions, target, condition) {
  53869. var _this = _super.call(this, triggerOptions, condition) || this;
  53870. _this._target = target;
  53871. return _this;
  53872. }
  53873. /** @hidden */
  53874. StopAnimationAction.prototype._prepare = function () {
  53875. };
  53876. StopAnimationAction.prototype.execute = function () {
  53877. var scene = this._actionManager.getScene();
  53878. scene.stopAnimation(this._target);
  53879. };
  53880. StopAnimationAction.prototype.serialize = function (parent) {
  53881. return _super.prototype._serialize.call(this, {
  53882. name: "StopAnimationAction",
  53883. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53884. }, parent);
  53885. };
  53886. return StopAnimationAction;
  53887. }(BABYLON.Action));
  53888. BABYLON.StopAnimationAction = StopAnimationAction;
  53889. var DoNothingAction = /** @class */ (function (_super) {
  53890. __extends(DoNothingAction, _super);
  53891. function DoNothingAction(triggerOptions, condition) {
  53892. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53893. return _super.call(this, triggerOptions, condition) || this;
  53894. }
  53895. DoNothingAction.prototype.execute = function () {
  53896. };
  53897. DoNothingAction.prototype.serialize = function (parent) {
  53898. return _super.prototype._serialize.call(this, {
  53899. name: "DoNothingAction",
  53900. properties: []
  53901. }, parent);
  53902. };
  53903. return DoNothingAction;
  53904. }(BABYLON.Action));
  53905. BABYLON.DoNothingAction = DoNothingAction;
  53906. var CombineAction = /** @class */ (function (_super) {
  53907. __extends(CombineAction, _super);
  53908. function CombineAction(triggerOptions, children, condition) {
  53909. var _this = _super.call(this, triggerOptions, condition) || this;
  53910. _this.children = children;
  53911. return _this;
  53912. }
  53913. /** @hidden */
  53914. CombineAction.prototype._prepare = function () {
  53915. for (var index = 0; index < this.children.length; index++) {
  53916. this.children[index]._actionManager = this._actionManager;
  53917. this.children[index]._prepare();
  53918. }
  53919. };
  53920. CombineAction.prototype.execute = function (evt) {
  53921. for (var index = 0; index < this.children.length; index++) {
  53922. this.children[index].execute(evt);
  53923. }
  53924. };
  53925. CombineAction.prototype.serialize = function (parent) {
  53926. var serializationObject = _super.prototype._serialize.call(this, {
  53927. name: "CombineAction",
  53928. properties: [],
  53929. combine: []
  53930. }, parent);
  53931. for (var i = 0; i < this.children.length; i++) {
  53932. serializationObject.combine.push(this.children[i].serialize(null));
  53933. }
  53934. return serializationObject;
  53935. };
  53936. return CombineAction;
  53937. }(BABYLON.Action));
  53938. BABYLON.CombineAction = CombineAction;
  53939. var ExecuteCodeAction = /** @class */ (function (_super) {
  53940. __extends(ExecuteCodeAction, _super);
  53941. function ExecuteCodeAction(triggerOptions, func, condition) {
  53942. var _this = _super.call(this, triggerOptions, condition) || this;
  53943. _this.func = func;
  53944. return _this;
  53945. }
  53946. ExecuteCodeAction.prototype.execute = function (evt) {
  53947. this.func(evt);
  53948. };
  53949. return ExecuteCodeAction;
  53950. }(BABYLON.Action));
  53951. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53952. var SetParentAction = /** @class */ (function (_super) {
  53953. __extends(SetParentAction, _super);
  53954. function SetParentAction(triggerOptions, target, parent, condition) {
  53955. var _this = _super.call(this, triggerOptions, condition) || this;
  53956. _this._target = target;
  53957. _this._parent = parent;
  53958. return _this;
  53959. }
  53960. /** @hidden */
  53961. SetParentAction.prototype._prepare = function () {
  53962. };
  53963. SetParentAction.prototype.execute = function () {
  53964. if (this._target.parent === this._parent) {
  53965. return;
  53966. }
  53967. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53968. invertParentWorldMatrix.invert();
  53969. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53970. this._target.parent = this._parent;
  53971. };
  53972. SetParentAction.prototype.serialize = function (parent) {
  53973. return _super.prototype._serialize.call(this, {
  53974. name: "SetParentAction",
  53975. properties: [
  53976. BABYLON.Action._GetTargetProperty(this._target),
  53977. BABYLON.Action._GetTargetProperty(this._parent),
  53978. ]
  53979. }, parent);
  53980. };
  53981. return SetParentAction;
  53982. }(BABYLON.Action));
  53983. BABYLON.SetParentAction = SetParentAction;
  53984. var PlaySoundAction = /** @class */ (function (_super) {
  53985. __extends(PlaySoundAction, _super);
  53986. function PlaySoundAction(triggerOptions, sound, condition) {
  53987. var _this = _super.call(this, triggerOptions, condition) || this;
  53988. _this._sound = sound;
  53989. return _this;
  53990. }
  53991. /** @hidden */
  53992. PlaySoundAction.prototype._prepare = function () {
  53993. };
  53994. PlaySoundAction.prototype.execute = function () {
  53995. if (this._sound !== undefined)
  53996. this._sound.play();
  53997. };
  53998. PlaySoundAction.prototype.serialize = function (parent) {
  53999. return _super.prototype._serialize.call(this, {
  54000. name: "PlaySoundAction",
  54001. properties: [{ name: "sound", value: this._sound.name }]
  54002. }, parent);
  54003. };
  54004. return PlaySoundAction;
  54005. }(BABYLON.Action));
  54006. BABYLON.PlaySoundAction = PlaySoundAction;
  54007. var StopSoundAction = /** @class */ (function (_super) {
  54008. __extends(StopSoundAction, _super);
  54009. function StopSoundAction(triggerOptions, sound, condition) {
  54010. var _this = _super.call(this, triggerOptions, condition) || this;
  54011. _this._sound = sound;
  54012. return _this;
  54013. }
  54014. /** @hidden */
  54015. StopSoundAction.prototype._prepare = function () {
  54016. };
  54017. StopSoundAction.prototype.execute = function () {
  54018. if (this._sound !== undefined)
  54019. this._sound.stop();
  54020. };
  54021. StopSoundAction.prototype.serialize = function (parent) {
  54022. return _super.prototype._serialize.call(this, {
  54023. name: "StopSoundAction",
  54024. properties: [{ name: "sound", value: this._sound.name }]
  54025. }, parent);
  54026. };
  54027. return StopSoundAction;
  54028. }(BABYLON.Action));
  54029. BABYLON.StopSoundAction = StopSoundAction;
  54030. })(BABYLON || (BABYLON = {}));
  54031. //# sourceMappingURL=babylon.directActions.js.map
  54032. var BABYLON;
  54033. (function (BABYLON) {
  54034. var SpriteManager = /** @class */ (function () {
  54035. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  54036. if (epsilon === void 0) { epsilon = 0.01; }
  54037. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54038. this.name = name;
  54039. this.sprites = new Array();
  54040. this.renderingGroupId = 0;
  54041. this.layerMask = 0x0FFFFFFF;
  54042. this.fogEnabled = true;
  54043. this.isPickable = false;
  54044. /**
  54045. * An event triggered when the manager is disposed.
  54046. */
  54047. this.onDisposeObservable = new BABYLON.Observable();
  54048. this._vertexBuffers = {};
  54049. this._capacity = capacity;
  54050. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  54051. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54052. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54053. if (cellSize.width && cellSize.height) {
  54054. this.cellWidth = cellSize.width;
  54055. this.cellHeight = cellSize.height;
  54056. }
  54057. else if (cellSize !== undefined) {
  54058. this.cellWidth = cellSize;
  54059. this.cellHeight = cellSize;
  54060. }
  54061. else {
  54062. return;
  54063. }
  54064. this._epsilon = epsilon;
  54065. this._scene = scene;
  54066. this._scene.spriteManagers.push(this);
  54067. var indices = [];
  54068. var index = 0;
  54069. for (var count = 0; count < capacity; count++) {
  54070. indices.push(index);
  54071. indices.push(index + 1);
  54072. indices.push(index + 2);
  54073. indices.push(index);
  54074. indices.push(index + 2);
  54075. indices.push(index + 3);
  54076. index += 4;
  54077. }
  54078. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  54079. // VBO
  54080. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  54081. this._vertexData = new Float32Array(capacity * 16 * 4);
  54082. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  54083. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  54084. var options = this._buffer.createVertexBuffer("options", 4, 4);
  54085. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  54086. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  54087. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54088. this._vertexBuffers["options"] = options;
  54089. this._vertexBuffers["cellInfo"] = cellInfo;
  54090. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54091. // Effects
  54092. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  54093. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  54094. }
  54095. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  54096. set: function (callback) {
  54097. if (this._onDisposeObserver) {
  54098. this.onDisposeObservable.remove(this._onDisposeObserver);
  54099. }
  54100. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54101. },
  54102. enumerable: true,
  54103. configurable: true
  54104. });
  54105. Object.defineProperty(SpriteManager.prototype, "texture", {
  54106. get: function () {
  54107. return this._spriteTexture;
  54108. },
  54109. set: function (value) {
  54110. this._spriteTexture = value;
  54111. },
  54112. enumerable: true,
  54113. configurable: true
  54114. });
  54115. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  54116. var arrayOffset = index * 16;
  54117. if (offsetX === 0)
  54118. offsetX = this._epsilon;
  54119. else if (offsetX === 1)
  54120. offsetX = 1 - this._epsilon;
  54121. if (offsetY === 0)
  54122. offsetY = this._epsilon;
  54123. else if (offsetY === 1)
  54124. offsetY = 1 - this._epsilon;
  54125. this._vertexData[arrayOffset] = sprite.position.x;
  54126. this._vertexData[arrayOffset + 1] = sprite.position.y;
  54127. this._vertexData[arrayOffset + 2] = sprite.position.z;
  54128. this._vertexData[arrayOffset + 3] = sprite.angle;
  54129. this._vertexData[arrayOffset + 4] = sprite.width;
  54130. this._vertexData[arrayOffset + 5] = sprite.height;
  54131. this._vertexData[arrayOffset + 6] = offsetX;
  54132. this._vertexData[arrayOffset + 7] = offsetY;
  54133. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  54134. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  54135. var offset = (sprite.cellIndex / rowSize) >> 0;
  54136. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  54137. this._vertexData[arrayOffset + 11] = offset;
  54138. // Color
  54139. this._vertexData[arrayOffset + 12] = sprite.color.r;
  54140. this._vertexData[arrayOffset + 13] = sprite.color.g;
  54141. this._vertexData[arrayOffset + 14] = sprite.color.b;
  54142. this._vertexData[arrayOffset + 15] = sprite.color.a;
  54143. };
  54144. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  54145. var count = Math.min(this._capacity, this.sprites.length);
  54146. var min = BABYLON.Vector3.Zero();
  54147. var max = BABYLON.Vector3.Zero();
  54148. var distance = Number.MAX_VALUE;
  54149. var currentSprite = null;
  54150. var cameraSpacePosition = BABYLON.Vector3.Zero();
  54151. var cameraView = camera.getViewMatrix();
  54152. for (var index = 0; index < count; index++) {
  54153. var sprite = this.sprites[index];
  54154. if (!sprite) {
  54155. continue;
  54156. }
  54157. if (predicate) {
  54158. if (!predicate(sprite)) {
  54159. continue;
  54160. }
  54161. }
  54162. else if (!sprite.isPickable) {
  54163. continue;
  54164. }
  54165. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  54166. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  54167. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  54168. if (ray.intersectsBoxMinMax(min, max)) {
  54169. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  54170. if (distance > currentDistance) {
  54171. distance = currentDistance;
  54172. currentSprite = sprite;
  54173. if (fastCheck) {
  54174. break;
  54175. }
  54176. }
  54177. }
  54178. }
  54179. if (currentSprite) {
  54180. var result = new BABYLON.PickingInfo();
  54181. result.hit = true;
  54182. result.pickedSprite = currentSprite;
  54183. result.distance = distance;
  54184. return result;
  54185. }
  54186. return null;
  54187. };
  54188. SpriteManager.prototype.render = function () {
  54189. // Check
  54190. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  54191. return;
  54192. var engine = this._scene.getEngine();
  54193. var baseSize = this._spriteTexture.getBaseSize();
  54194. // Sprites
  54195. var deltaTime = engine.getDeltaTime();
  54196. var max = Math.min(this._capacity, this.sprites.length);
  54197. var rowSize = baseSize.width / this.cellWidth;
  54198. var offset = 0;
  54199. for (var index = 0; index < max; index++) {
  54200. var sprite = this.sprites[index];
  54201. if (!sprite || !sprite.isVisible) {
  54202. continue;
  54203. }
  54204. sprite._animate(deltaTime);
  54205. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  54206. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  54207. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  54208. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  54209. }
  54210. this._buffer.update(this._vertexData);
  54211. // Render
  54212. var effect = this._effectBase;
  54213. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54214. effect = this._effectFog;
  54215. }
  54216. engine.enableEffect(effect);
  54217. var viewMatrix = this._scene.getViewMatrix();
  54218. effect.setTexture("diffuseSampler", this._spriteTexture);
  54219. effect.setMatrix("view", viewMatrix);
  54220. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  54221. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  54222. // Fog
  54223. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54224. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  54225. effect.setColor3("vFogColor", this._scene.fogColor);
  54226. }
  54227. // VBOs
  54228. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  54229. // Draw order
  54230. engine.setDepthFunctionToLessOrEqual();
  54231. effect.setBool("alphaTest", true);
  54232. engine.setColorWrite(false);
  54233. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  54234. engine.setColorWrite(true);
  54235. effect.setBool("alphaTest", false);
  54236. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54237. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  54238. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54239. };
  54240. SpriteManager.prototype.dispose = function () {
  54241. if (this._buffer) {
  54242. this._buffer.dispose();
  54243. this._buffer = null;
  54244. }
  54245. if (this._indexBuffer) {
  54246. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54247. this._indexBuffer = null;
  54248. }
  54249. if (this._spriteTexture) {
  54250. this._spriteTexture.dispose();
  54251. this._spriteTexture = null;
  54252. }
  54253. // Remove from scene
  54254. var index = this._scene.spriteManagers.indexOf(this);
  54255. this._scene.spriteManagers.splice(index, 1);
  54256. // Callback
  54257. this.onDisposeObservable.notifyObservers(this);
  54258. this.onDisposeObservable.clear();
  54259. };
  54260. return SpriteManager;
  54261. }());
  54262. BABYLON.SpriteManager = SpriteManager;
  54263. })(BABYLON || (BABYLON = {}));
  54264. //# sourceMappingURL=babylon.spriteManager.js.map
  54265. var BABYLON;
  54266. (function (BABYLON) {
  54267. var Sprite = /** @class */ (function () {
  54268. function Sprite(name, manager) {
  54269. this.name = name;
  54270. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54271. this.width = 1.0;
  54272. this.height = 1.0;
  54273. this.angle = 0;
  54274. this.cellIndex = 0;
  54275. this.invertU = 0;
  54276. this.invertV = 0;
  54277. this.animations = new Array();
  54278. this.isPickable = false;
  54279. this._animationStarted = false;
  54280. this._loopAnimation = false;
  54281. this._fromIndex = 0;
  54282. this._toIndex = 0;
  54283. this._delay = 0;
  54284. this._direction = 1;
  54285. this._time = 0;
  54286. /**
  54287. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  54288. */
  54289. this.isVisible = true;
  54290. this._manager = manager;
  54291. this._manager.sprites.push(this);
  54292. this.position = BABYLON.Vector3.Zero();
  54293. }
  54294. Object.defineProperty(Sprite.prototype, "size", {
  54295. get: function () {
  54296. return this.width;
  54297. },
  54298. set: function (value) {
  54299. this.width = value;
  54300. this.height = value;
  54301. },
  54302. enumerable: true,
  54303. configurable: true
  54304. });
  54305. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  54306. this._fromIndex = from;
  54307. this._toIndex = to;
  54308. this._loopAnimation = loop;
  54309. this._delay = delay;
  54310. this._animationStarted = true;
  54311. this._direction = from < to ? 1 : -1;
  54312. this.cellIndex = from;
  54313. this._time = 0;
  54314. this._onAnimationEnd = onAnimationEnd;
  54315. };
  54316. Sprite.prototype.stopAnimation = function () {
  54317. this._animationStarted = false;
  54318. };
  54319. /** @hidden */
  54320. Sprite.prototype._animate = function (deltaTime) {
  54321. if (!this._animationStarted)
  54322. return;
  54323. this._time += deltaTime;
  54324. if (this._time > this._delay) {
  54325. this._time = this._time % this._delay;
  54326. this.cellIndex += this._direction;
  54327. if (this.cellIndex > this._toIndex) {
  54328. if (this._loopAnimation) {
  54329. this.cellIndex = this._fromIndex;
  54330. }
  54331. else {
  54332. this.cellIndex = this._toIndex;
  54333. this._animationStarted = false;
  54334. if (this._onAnimationEnd) {
  54335. this._onAnimationEnd();
  54336. }
  54337. if (this.disposeWhenFinishedAnimating) {
  54338. this.dispose();
  54339. }
  54340. }
  54341. }
  54342. }
  54343. };
  54344. Sprite.prototype.dispose = function () {
  54345. for (var i = 0; i < this._manager.sprites.length; i++) {
  54346. if (this._manager.sprites[i] == this) {
  54347. this._manager.sprites.splice(i, 1);
  54348. }
  54349. }
  54350. };
  54351. return Sprite;
  54352. }());
  54353. BABYLON.Sprite = Sprite;
  54354. })(BABYLON || (BABYLON = {}));
  54355. //# sourceMappingURL=babylon.sprite.js.map
  54356. var BABYLON;
  54357. (function (BABYLON) {
  54358. var IntersectionInfo = /** @class */ (function () {
  54359. function IntersectionInfo(bu, bv, distance) {
  54360. this.bu = bu;
  54361. this.bv = bv;
  54362. this.distance = distance;
  54363. this.faceId = 0;
  54364. this.subMeshId = 0;
  54365. }
  54366. return IntersectionInfo;
  54367. }());
  54368. BABYLON.IntersectionInfo = IntersectionInfo;
  54369. /**
  54370. * Information about the result of picking within a scene
  54371. * See https://doc.babylonjs.com/babylon101/picking_collisions
  54372. */
  54373. var PickingInfo = /** @class */ (function () {
  54374. function PickingInfo() {
  54375. /**
  54376. * If the pick collided with an object
  54377. */
  54378. this.hit = false;
  54379. /**
  54380. * Distance away where the pick collided
  54381. */
  54382. this.distance = 0;
  54383. /**
  54384. * The location of pick collision
  54385. */
  54386. this.pickedPoint = null;
  54387. /**
  54388. * The mesh corresponding the the pick collision
  54389. */
  54390. this.pickedMesh = null;
  54391. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  54392. this.bu = 0;
  54393. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  54394. this.bv = 0;
  54395. /** The id of the face on the mesh that was picked */
  54396. this.faceId = -1;
  54397. /** Id of the the submesh that was picked */
  54398. this.subMeshId = 0;
  54399. /** If a sprite was picked, this will be the sprite the pick collided with */
  54400. this.pickedSprite = null;
  54401. /**
  54402. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  54403. */
  54404. this.originMesh = null;
  54405. /**
  54406. * The ray that was used to perform the picking.
  54407. */
  54408. this.ray = null;
  54409. }
  54410. /**
  54411. * Gets the normal correspodning to the face the pick collided with
  54412. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  54413. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  54414. * @returns The normal correspodning to the face the pick collided with
  54415. */
  54416. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  54417. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  54418. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  54419. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54420. return null;
  54421. }
  54422. var indices = this.pickedMesh.getIndices();
  54423. if (!indices) {
  54424. return null;
  54425. }
  54426. var result;
  54427. if (useVerticesNormals) {
  54428. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54429. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  54430. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  54431. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  54432. normal0 = normal0.scale(this.bu);
  54433. normal1 = normal1.scale(this.bv);
  54434. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  54435. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  54436. }
  54437. else {
  54438. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54439. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  54440. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  54441. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  54442. var p1p2 = vertex1.subtract(vertex2);
  54443. var p3p2 = vertex3.subtract(vertex2);
  54444. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  54445. }
  54446. if (useWorldCoordinates) {
  54447. var wm = this.pickedMesh.getWorldMatrix();
  54448. if (this.pickedMesh.nonUniformScaling) {
  54449. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  54450. wm = BABYLON.Tmp.Matrix[0];
  54451. wm.setTranslationFromFloats(0, 0, 0);
  54452. wm.invert();
  54453. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  54454. wm = BABYLON.Tmp.Matrix[1];
  54455. }
  54456. result = BABYLON.Vector3.TransformNormal(result, wm);
  54457. }
  54458. result.normalize();
  54459. return result;
  54460. };
  54461. /**
  54462. * Gets the texture coordinates of where the pick occured
  54463. * @returns the vector containing the coordnates of the texture
  54464. */
  54465. PickingInfo.prototype.getTextureCoordinates = function () {
  54466. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54467. return null;
  54468. }
  54469. var indices = this.pickedMesh.getIndices();
  54470. if (!indices) {
  54471. return null;
  54472. }
  54473. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54474. if (!uvs) {
  54475. return null;
  54476. }
  54477. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  54478. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  54479. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  54480. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  54481. uv1 = uv1.scale(this.bu);
  54482. uv2 = uv2.scale(this.bv);
  54483. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  54484. };
  54485. return PickingInfo;
  54486. }());
  54487. BABYLON.PickingInfo = PickingInfo;
  54488. })(BABYLON || (BABYLON = {}));
  54489. //# sourceMappingURL=babylon.pickingInfo.js.map
  54490. var BABYLON;
  54491. (function (BABYLON) {
  54492. var Ray = /** @class */ (function () {
  54493. function Ray(origin, direction, length) {
  54494. if (length === void 0) { length = Number.MAX_VALUE; }
  54495. this.origin = origin;
  54496. this.direction = direction;
  54497. this.length = length;
  54498. }
  54499. // Methods
  54500. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  54501. var d = 0.0;
  54502. var maxValue = Number.MAX_VALUE;
  54503. var inv;
  54504. var min;
  54505. var max;
  54506. var temp;
  54507. if (Math.abs(this.direction.x) < 0.0000001) {
  54508. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  54509. return false;
  54510. }
  54511. }
  54512. else {
  54513. inv = 1.0 / this.direction.x;
  54514. min = (minimum.x - this.origin.x) * inv;
  54515. max = (maximum.x - this.origin.x) * inv;
  54516. if (max === -Infinity) {
  54517. max = Infinity;
  54518. }
  54519. if (min > max) {
  54520. temp = min;
  54521. min = max;
  54522. max = temp;
  54523. }
  54524. d = Math.max(min, d);
  54525. maxValue = Math.min(max, maxValue);
  54526. if (d > maxValue) {
  54527. return false;
  54528. }
  54529. }
  54530. if (Math.abs(this.direction.y) < 0.0000001) {
  54531. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  54532. return false;
  54533. }
  54534. }
  54535. else {
  54536. inv = 1.0 / this.direction.y;
  54537. min = (minimum.y - this.origin.y) * inv;
  54538. max = (maximum.y - this.origin.y) * inv;
  54539. if (max === -Infinity) {
  54540. max = Infinity;
  54541. }
  54542. if (min > max) {
  54543. temp = min;
  54544. min = max;
  54545. max = temp;
  54546. }
  54547. d = Math.max(min, d);
  54548. maxValue = Math.min(max, maxValue);
  54549. if (d > maxValue) {
  54550. return false;
  54551. }
  54552. }
  54553. if (Math.abs(this.direction.z) < 0.0000001) {
  54554. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  54555. return false;
  54556. }
  54557. }
  54558. else {
  54559. inv = 1.0 / this.direction.z;
  54560. min = (minimum.z - this.origin.z) * inv;
  54561. max = (maximum.z - this.origin.z) * inv;
  54562. if (max === -Infinity) {
  54563. max = Infinity;
  54564. }
  54565. if (min > max) {
  54566. temp = min;
  54567. min = max;
  54568. max = temp;
  54569. }
  54570. d = Math.max(min, d);
  54571. maxValue = Math.min(max, maxValue);
  54572. if (d > maxValue) {
  54573. return false;
  54574. }
  54575. }
  54576. return true;
  54577. };
  54578. Ray.prototype.intersectsBox = function (box) {
  54579. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54580. };
  54581. Ray.prototype.intersectsSphere = function (sphere) {
  54582. var x = sphere.center.x - this.origin.x;
  54583. var y = sphere.center.y - this.origin.y;
  54584. var z = sphere.center.z - this.origin.z;
  54585. var pyth = (x * x) + (y * y) + (z * z);
  54586. var rr = sphere.radius * sphere.radius;
  54587. if (pyth <= rr) {
  54588. return true;
  54589. }
  54590. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54591. if (dot < 0.0) {
  54592. return false;
  54593. }
  54594. var temp = pyth - (dot * dot);
  54595. return temp <= rr;
  54596. };
  54597. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54598. if (!this._edge1) {
  54599. this._edge1 = BABYLON.Vector3.Zero();
  54600. this._edge2 = BABYLON.Vector3.Zero();
  54601. this._pvec = BABYLON.Vector3.Zero();
  54602. this._tvec = BABYLON.Vector3.Zero();
  54603. this._qvec = BABYLON.Vector3.Zero();
  54604. }
  54605. vertex1.subtractToRef(vertex0, this._edge1);
  54606. vertex2.subtractToRef(vertex0, this._edge2);
  54607. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54608. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54609. if (det === 0) {
  54610. return null;
  54611. }
  54612. var invdet = 1 / det;
  54613. this.origin.subtractToRef(vertex0, this._tvec);
  54614. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54615. if (bu < 0 || bu > 1.0) {
  54616. return null;
  54617. }
  54618. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54619. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54620. if (bv < 0 || bu + bv > 1.0) {
  54621. return null;
  54622. }
  54623. //check if the distance is longer than the predefined length.
  54624. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54625. if (distance > this.length) {
  54626. return null;
  54627. }
  54628. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54629. };
  54630. Ray.prototype.intersectsPlane = function (plane) {
  54631. var distance;
  54632. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54633. if (Math.abs(result1) < 9.99999997475243E-07) {
  54634. return null;
  54635. }
  54636. else {
  54637. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54638. distance = (-plane.d - result2) / result1;
  54639. if (distance < 0.0) {
  54640. if (distance < -9.99999997475243E-07) {
  54641. return null;
  54642. }
  54643. else {
  54644. return 0;
  54645. }
  54646. }
  54647. return distance;
  54648. }
  54649. };
  54650. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54651. var tm = BABYLON.Tmp.Matrix[0];
  54652. mesh.getWorldMatrix().invertToRef(tm);
  54653. if (this._tmpRay) {
  54654. Ray.TransformToRef(this, tm, this._tmpRay);
  54655. }
  54656. else {
  54657. this._tmpRay = Ray.Transform(this, tm);
  54658. }
  54659. return mesh.intersects(this._tmpRay, fastCheck);
  54660. };
  54661. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54662. if (results) {
  54663. results.length = 0;
  54664. }
  54665. else {
  54666. results = [];
  54667. }
  54668. for (var i = 0; i < meshes.length; i++) {
  54669. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54670. if (pickInfo.hit) {
  54671. results.push(pickInfo);
  54672. }
  54673. }
  54674. results.sort(this._comparePickingInfo);
  54675. return results;
  54676. };
  54677. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54678. if (pickingInfoA.distance < pickingInfoB.distance) {
  54679. return -1;
  54680. }
  54681. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54682. return 1;
  54683. }
  54684. else {
  54685. return 0;
  54686. }
  54687. };
  54688. /**
  54689. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54690. * @param sega the first point of the segment to test the intersection against
  54691. * @param segb the second point of the segment to test the intersection against
  54692. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54693. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54694. */
  54695. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54696. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54697. var u = segb.subtract(sega);
  54698. var v = rsegb.subtract(this.origin);
  54699. var w = sega.subtract(this.origin);
  54700. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54701. var b = BABYLON.Vector3.Dot(u, v);
  54702. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54703. var d = BABYLON.Vector3.Dot(u, w);
  54704. var e = BABYLON.Vector3.Dot(v, w);
  54705. var D = a * c - b * b; // always >= 0
  54706. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54707. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54708. // compute the line parameters of the two closest points
  54709. if (D < Ray.smallnum) { // the lines are almost parallel
  54710. sN = 0.0; // force using point P0 on segment S1
  54711. sD = 1.0; // to prevent possible division by 0.0 later
  54712. tN = e;
  54713. tD = c;
  54714. }
  54715. else { // get the closest points on the infinite lines
  54716. sN = (b * e - c * d);
  54717. tN = (a * e - b * d);
  54718. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54719. sN = 0.0;
  54720. tN = e;
  54721. tD = c;
  54722. }
  54723. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54724. sN = sD;
  54725. tN = e + b;
  54726. tD = c;
  54727. }
  54728. }
  54729. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54730. tN = 0.0;
  54731. // recompute sc for this edge
  54732. if (-d < 0.0) {
  54733. sN = 0.0;
  54734. }
  54735. else if (-d > a)
  54736. sN = sD;
  54737. else {
  54738. sN = -d;
  54739. sD = a;
  54740. }
  54741. }
  54742. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54743. tN = tD;
  54744. // recompute sc for this edge
  54745. if ((-d + b) < 0.0) {
  54746. sN = 0;
  54747. }
  54748. else if ((-d + b) > a) {
  54749. sN = sD;
  54750. }
  54751. else {
  54752. sN = (-d + b);
  54753. sD = a;
  54754. }
  54755. }
  54756. // finally do the division to get sc and tc
  54757. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54758. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54759. // get the difference of the two closest points
  54760. var qtc = v.multiplyByFloats(tc, tc, tc);
  54761. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54762. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54763. if (isIntersected) {
  54764. return qtc.length();
  54765. }
  54766. return -1;
  54767. };
  54768. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54769. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54770. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54771. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54772. this.direction.normalize();
  54773. return this;
  54774. };
  54775. // Statics
  54776. Ray.Zero = function () {
  54777. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54778. };
  54779. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54780. var result = Ray.Zero();
  54781. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54782. };
  54783. /**
  54784. * 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
  54785. * transformed to the given world matrix.
  54786. * @param origin The origin point
  54787. * @param end The end point
  54788. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54789. */
  54790. Ray.CreateNewFromTo = function (origin, end, world) {
  54791. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54792. var direction = end.subtract(origin);
  54793. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54794. direction.normalize();
  54795. return Ray.Transform(new Ray(origin, direction, length), world);
  54796. };
  54797. Ray.Transform = function (ray, matrix) {
  54798. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54799. Ray.TransformToRef(ray, matrix, result);
  54800. return result;
  54801. };
  54802. Ray.TransformToRef = function (ray, matrix, result) {
  54803. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54804. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54805. result.length = ray.length;
  54806. var dir = result.direction;
  54807. var len = dir.length();
  54808. if (!(len === 0 || len === 1)) {
  54809. var num = 1.0 / len;
  54810. dir.x *= num;
  54811. dir.y *= num;
  54812. dir.z *= num;
  54813. result.length *= len;
  54814. }
  54815. };
  54816. Ray.smallnum = 0.00000001;
  54817. Ray.rayl = 10e8;
  54818. return Ray;
  54819. }());
  54820. BABYLON.Ray = Ray;
  54821. })(BABYLON || (BABYLON = {}));
  54822. //# sourceMappingURL=babylon.ray.js.map
  54823. var BABYLON;
  54824. (function (BABYLON) {
  54825. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54826. if (boxMin.x > sphereCenter.x + sphereRadius)
  54827. return false;
  54828. if (sphereCenter.x - sphereRadius > boxMax.x)
  54829. return false;
  54830. if (boxMin.y > sphereCenter.y + sphereRadius)
  54831. return false;
  54832. if (sphereCenter.y - sphereRadius > boxMax.y)
  54833. return false;
  54834. if (boxMin.z > sphereCenter.z + sphereRadius)
  54835. return false;
  54836. if (sphereCenter.z - sphereRadius > boxMax.z)
  54837. return false;
  54838. return true;
  54839. };
  54840. var getLowestRoot = (function () {
  54841. var result = { root: 0, found: false };
  54842. return function (a, b, c, maxR) {
  54843. result.root = 0;
  54844. result.found = false;
  54845. var determinant = b * b - 4.0 * a * c;
  54846. if (determinant < 0)
  54847. return result;
  54848. var sqrtD = Math.sqrt(determinant);
  54849. var r1 = (-b - sqrtD) / (2.0 * a);
  54850. var r2 = (-b + sqrtD) / (2.0 * a);
  54851. if (r1 > r2) {
  54852. var temp = r2;
  54853. r2 = r1;
  54854. r1 = temp;
  54855. }
  54856. if (r1 > 0 && r1 < maxR) {
  54857. result.root = r1;
  54858. result.found = true;
  54859. return result;
  54860. }
  54861. if (r2 > 0 && r2 < maxR) {
  54862. result.root = r2;
  54863. result.found = true;
  54864. return result;
  54865. }
  54866. return result;
  54867. };
  54868. })();
  54869. var Collider = /** @class */ (function () {
  54870. function Collider() {
  54871. this._collisionPoint = BABYLON.Vector3.Zero();
  54872. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54873. this._tempVector = BABYLON.Vector3.Zero();
  54874. this._tempVector2 = BABYLON.Vector3.Zero();
  54875. this._tempVector3 = BABYLON.Vector3.Zero();
  54876. this._tempVector4 = BABYLON.Vector3.Zero();
  54877. this._edge = BABYLON.Vector3.Zero();
  54878. this._baseToVertex = BABYLON.Vector3.Zero();
  54879. this._destinationPoint = BABYLON.Vector3.Zero();
  54880. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54881. this._displacementVector = BABYLON.Vector3.Zero();
  54882. /** @hidden */
  54883. this._radius = BABYLON.Vector3.One();
  54884. /** @hidden */
  54885. this._retry = 0;
  54886. /** @hidden */
  54887. this._basePointWorld = BABYLON.Vector3.Zero();
  54888. this._velocityWorld = BABYLON.Vector3.Zero();
  54889. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54890. this._collisionMask = -1;
  54891. }
  54892. Object.defineProperty(Collider.prototype, "collisionMask", {
  54893. get: function () {
  54894. return this._collisionMask;
  54895. },
  54896. set: function (mask) {
  54897. this._collisionMask = !isNaN(mask) ? mask : -1;
  54898. },
  54899. enumerable: true,
  54900. configurable: true
  54901. });
  54902. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54903. /**
  54904. * Gets the plane normal used to compute the sliding response (in local space)
  54905. */
  54906. get: function () {
  54907. return this._slidePlaneNormal;
  54908. },
  54909. enumerable: true,
  54910. configurable: true
  54911. });
  54912. // Methods
  54913. /** @hidden */
  54914. Collider.prototype._initialize = function (source, dir, e) {
  54915. this._velocity = dir;
  54916. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54917. this._basePoint = source;
  54918. source.multiplyToRef(this._radius, this._basePointWorld);
  54919. dir.multiplyToRef(this._radius, this._velocityWorld);
  54920. this._velocityWorldLength = this._velocityWorld.length();
  54921. this._epsilon = e;
  54922. this.collisionFound = false;
  54923. };
  54924. /** @hidden */
  54925. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54926. pa.subtractToRef(point, this._tempVector);
  54927. pb.subtractToRef(point, this._tempVector2);
  54928. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54929. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54930. if (d < 0)
  54931. return false;
  54932. pc.subtractToRef(point, this._tempVector3);
  54933. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54934. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54935. if (d < 0)
  54936. return false;
  54937. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54938. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54939. return d >= 0;
  54940. };
  54941. /** @hidden */
  54942. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54943. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54944. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54945. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54946. return false;
  54947. }
  54948. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54949. return false;
  54950. return true;
  54951. };
  54952. /** @hidden */
  54953. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54954. var t0;
  54955. var embeddedInPlane = false;
  54956. //defensive programming, actually not needed.
  54957. if (!trianglePlaneArray) {
  54958. trianglePlaneArray = [];
  54959. }
  54960. if (!trianglePlaneArray[faceIndex]) {
  54961. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54962. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54963. }
  54964. var trianglePlane = trianglePlaneArray[faceIndex];
  54965. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54966. return;
  54967. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54968. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54969. if (normalDotVelocity == 0) {
  54970. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54971. return;
  54972. embeddedInPlane = true;
  54973. t0 = 0;
  54974. }
  54975. else {
  54976. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54977. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54978. if (t0 > t1) {
  54979. var temp = t1;
  54980. t1 = t0;
  54981. t0 = temp;
  54982. }
  54983. if (t0 > 1.0 || t1 < 0.0)
  54984. return;
  54985. if (t0 < 0)
  54986. t0 = 0;
  54987. if (t0 > 1.0)
  54988. t0 = 1.0;
  54989. }
  54990. this._collisionPoint.copyFromFloats(0, 0, 0);
  54991. var found = false;
  54992. var t = 1.0;
  54993. if (!embeddedInPlane) {
  54994. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54995. this._velocity.scaleToRef(t0, this._tempVector);
  54996. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54997. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54998. found = true;
  54999. t = t0;
  55000. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  55001. }
  55002. }
  55003. if (!found) {
  55004. var velocitySquaredLength = this._velocity.lengthSquared();
  55005. var a = velocitySquaredLength;
  55006. this._basePoint.subtractToRef(p1, this._tempVector);
  55007. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55008. var c = this._tempVector.lengthSquared() - 1.0;
  55009. var lowestRoot = getLowestRoot(a, b, c, t);
  55010. if (lowestRoot.found) {
  55011. t = lowestRoot.root;
  55012. found = true;
  55013. this._collisionPoint.copyFrom(p1);
  55014. }
  55015. this._basePoint.subtractToRef(p2, this._tempVector);
  55016. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55017. c = this._tempVector.lengthSquared() - 1.0;
  55018. lowestRoot = getLowestRoot(a, b, c, t);
  55019. if (lowestRoot.found) {
  55020. t = lowestRoot.root;
  55021. found = true;
  55022. this._collisionPoint.copyFrom(p2);
  55023. }
  55024. this._basePoint.subtractToRef(p3, this._tempVector);
  55025. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55026. c = this._tempVector.lengthSquared() - 1.0;
  55027. lowestRoot = getLowestRoot(a, b, c, t);
  55028. if (lowestRoot.found) {
  55029. t = lowestRoot.root;
  55030. found = true;
  55031. this._collisionPoint.copyFrom(p3);
  55032. }
  55033. p2.subtractToRef(p1, this._edge);
  55034. p1.subtractToRef(this._basePoint, this._baseToVertex);
  55035. var edgeSquaredLength = this._edge.lengthSquared();
  55036. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55037. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55038. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55039. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55040. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55041. lowestRoot = getLowestRoot(a, b, c, t);
  55042. if (lowestRoot.found) {
  55043. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55044. if (f >= 0.0 && f <= 1.0) {
  55045. t = lowestRoot.root;
  55046. found = true;
  55047. this._edge.scaleInPlace(f);
  55048. p1.addToRef(this._edge, this._collisionPoint);
  55049. }
  55050. }
  55051. p3.subtractToRef(p2, this._edge);
  55052. p2.subtractToRef(this._basePoint, this._baseToVertex);
  55053. edgeSquaredLength = this._edge.lengthSquared();
  55054. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55055. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55056. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55057. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55058. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55059. lowestRoot = getLowestRoot(a, b, c, t);
  55060. if (lowestRoot.found) {
  55061. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55062. if (f >= 0.0 && f <= 1.0) {
  55063. t = lowestRoot.root;
  55064. found = true;
  55065. this._edge.scaleInPlace(f);
  55066. p2.addToRef(this._edge, this._collisionPoint);
  55067. }
  55068. }
  55069. p1.subtractToRef(p3, this._edge);
  55070. p3.subtractToRef(this._basePoint, this._baseToVertex);
  55071. edgeSquaredLength = this._edge.lengthSquared();
  55072. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55073. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55074. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55075. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55076. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55077. lowestRoot = getLowestRoot(a, b, c, t);
  55078. if (lowestRoot.found) {
  55079. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55080. if (f >= 0.0 && f <= 1.0) {
  55081. t = lowestRoot.root;
  55082. found = true;
  55083. this._edge.scaleInPlace(f);
  55084. p3.addToRef(this._edge, this._collisionPoint);
  55085. }
  55086. }
  55087. }
  55088. if (found) {
  55089. var distToCollision = t * this._velocity.length();
  55090. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  55091. if (!this.intersectionPoint) {
  55092. this.intersectionPoint = this._collisionPoint.clone();
  55093. }
  55094. else {
  55095. this.intersectionPoint.copyFrom(this._collisionPoint);
  55096. }
  55097. this._nearestDistance = distToCollision;
  55098. this.collisionFound = true;
  55099. }
  55100. }
  55101. };
  55102. /** @hidden */
  55103. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  55104. for (var i = indexStart; i < indexEnd; i += 3) {
  55105. var p1 = pts[indices[i] - decal];
  55106. var p2 = pts[indices[i + 1] - decal];
  55107. var p3 = pts[indices[i + 2] - decal];
  55108. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  55109. }
  55110. };
  55111. /** @hidden */
  55112. Collider.prototype._getResponse = function (pos, vel) {
  55113. pos.addToRef(vel, this._destinationPoint);
  55114. vel.scaleInPlace((this._nearestDistance / vel.length()));
  55115. this._basePoint.addToRef(vel, pos);
  55116. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  55117. this._slidePlaneNormal.normalize();
  55118. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  55119. pos.addInPlace(this._displacementVector);
  55120. this.intersectionPoint.addInPlace(this._displacementVector);
  55121. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  55122. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  55123. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  55124. };
  55125. return Collider;
  55126. }());
  55127. BABYLON.Collider = Collider;
  55128. })(BABYLON || (BABYLON = {}));
  55129. //# sourceMappingURL=babylon.collider.js.map
  55130. var BABYLON;
  55131. (function (BABYLON) {
  55132. //WebWorker code will be inserted to this variable.
  55133. BABYLON.CollisionWorker = "";
  55134. /** Defines supported task for worker process */
  55135. var WorkerTaskType;
  55136. (function (WorkerTaskType) {
  55137. /** Initialization */
  55138. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  55139. /** Update of geometry */
  55140. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  55141. /** Evaluate collision */
  55142. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  55143. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  55144. /** Defines kind of replies returned by worker */
  55145. var WorkerReplyType;
  55146. (function (WorkerReplyType) {
  55147. /** Success */
  55148. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  55149. /** Unkown error */
  55150. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  55151. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  55152. var CollisionCoordinatorWorker = /** @class */ (function () {
  55153. function CollisionCoordinatorWorker() {
  55154. var _this = this;
  55155. this._scaledPosition = BABYLON.Vector3.Zero();
  55156. this._scaledVelocity = BABYLON.Vector3.Zero();
  55157. this.onMeshUpdated = function (transformNode) {
  55158. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  55159. };
  55160. this.onGeometryUpdated = function (geometry) {
  55161. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  55162. };
  55163. this._afterRender = function () {
  55164. if (!_this._init)
  55165. return;
  55166. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  55167. return;
  55168. }
  55169. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  55170. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  55171. if (_this._runningUpdated > 4) {
  55172. return;
  55173. }
  55174. ++_this._runningUpdated;
  55175. var payload = {
  55176. updatedMeshes: _this._addUpdateMeshesList,
  55177. updatedGeometries: _this._addUpdateGeometriesList,
  55178. removedGeometries: _this._toRemoveGeometryArray,
  55179. removedMeshes: _this._toRemoveMeshesArray
  55180. };
  55181. var message = {
  55182. payload: payload,
  55183. taskType: WorkerTaskType.UPDATE
  55184. };
  55185. var serializable = [];
  55186. for (var id in payload.updatedGeometries) {
  55187. if (payload.updatedGeometries.hasOwnProperty(id)) {
  55188. //prepare transferables
  55189. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  55190. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  55191. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  55192. }
  55193. }
  55194. _this._worker.postMessage(message, serializable);
  55195. _this._addUpdateMeshesList = {};
  55196. _this._addUpdateGeometriesList = {};
  55197. _this._toRemoveGeometryArray = [];
  55198. _this._toRemoveMeshesArray = [];
  55199. };
  55200. this._onMessageFromWorker = function (e) {
  55201. var returnData = e.data;
  55202. if (returnData.error != WorkerReplyType.SUCCESS) {
  55203. //TODO what errors can be returned from the worker?
  55204. BABYLON.Tools.Warn("error returned from worker!");
  55205. return;
  55206. }
  55207. switch (returnData.taskType) {
  55208. case WorkerTaskType.INIT:
  55209. _this._init = true;
  55210. //Update the worked with ALL of the scene's current state
  55211. _this._scene.meshes.forEach(function (mesh) {
  55212. _this.onMeshAdded(mesh);
  55213. });
  55214. _this._scene.getGeometries().forEach(function (geometry) {
  55215. _this.onGeometryAdded(geometry);
  55216. });
  55217. break;
  55218. case WorkerTaskType.UPDATE:
  55219. _this._runningUpdated--;
  55220. break;
  55221. case WorkerTaskType.COLLIDE:
  55222. var returnPayload = returnData.payload;
  55223. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  55224. return;
  55225. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  55226. if (callback) {
  55227. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  55228. if (mesh) {
  55229. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  55230. }
  55231. }
  55232. //cleanup
  55233. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  55234. break;
  55235. }
  55236. };
  55237. this._collisionsCallbackArray = [];
  55238. this._init = false;
  55239. this._runningUpdated = 0;
  55240. this._addUpdateMeshesList = {};
  55241. this._addUpdateGeometriesList = {};
  55242. this._toRemoveGeometryArray = [];
  55243. this._toRemoveMeshesArray = [];
  55244. }
  55245. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55246. if (!this._init)
  55247. return;
  55248. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  55249. return;
  55250. position.divideToRef(collider._radius, this._scaledPosition);
  55251. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55252. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  55253. var payload = {
  55254. collider: {
  55255. position: this._scaledPosition.asArray(),
  55256. velocity: this._scaledVelocity.asArray(),
  55257. radius: collider._radius.asArray()
  55258. },
  55259. collisionId: collisionIndex,
  55260. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  55261. maximumRetry: maximumRetry
  55262. };
  55263. var message = {
  55264. payload: payload,
  55265. taskType: WorkerTaskType.COLLIDE
  55266. };
  55267. this._worker.postMessage(message);
  55268. };
  55269. CollisionCoordinatorWorker.prototype.init = function (scene) {
  55270. this._scene = scene;
  55271. this._scene.registerAfterRender(this._afterRender);
  55272. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  55273. this._worker = new Worker(workerUrl);
  55274. this._worker.onmessage = this._onMessageFromWorker;
  55275. var message = {
  55276. payload: {},
  55277. taskType: WorkerTaskType.INIT
  55278. };
  55279. this._worker.postMessage(message);
  55280. };
  55281. CollisionCoordinatorWorker.prototype.destroy = function () {
  55282. this._scene.unregisterAfterRender(this._afterRender);
  55283. this._worker.terminate();
  55284. };
  55285. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  55286. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  55287. this.onMeshUpdated(mesh);
  55288. };
  55289. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  55290. this._toRemoveMeshesArray.push(mesh.uniqueId);
  55291. };
  55292. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  55293. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  55294. geometry.onGeometryUpdated = this.onGeometryUpdated;
  55295. this.onGeometryUpdated(geometry);
  55296. };
  55297. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  55298. this._toRemoveGeometryArray.push(geometry.id);
  55299. };
  55300. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  55301. var submeshes = [];
  55302. if (mesh.subMeshes) {
  55303. submeshes = mesh.subMeshes.map(function (sm, idx) {
  55304. var boundingInfo = sm.getBoundingInfo();
  55305. return {
  55306. position: idx,
  55307. verticesStart: sm.verticesStart,
  55308. verticesCount: sm.verticesCount,
  55309. indexStart: sm.indexStart,
  55310. indexCount: sm.indexCount,
  55311. hasMaterial: !!sm.getMaterial(),
  55312. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55313. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55314. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55315. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  55316. };
  55317. });
  55318. }
  55319. var geometryId = null;
  55320. if (mesh instanceof BABYLON.Mesh) {
  55321. var geometry = mesh.geometry;
  55322. geometryId = geometry ? geometry.id : null;
  55323. }
  55324. else if (mesh instanceof BABYLON.InstancedMesh) {
  55325. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  55326. geometryId = geometry ? geometry.id : null;
  55327. }
  55328. var boundingInfo = mesh.getBoundingInfo();
  55329. return {
  55330. uniqueId: mesh.uniqueId,
  55331. id: mesh.id,
  55332. name: mesh.name,
  55333. geometryId: geometryId,
  55334. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55335. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55336. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55337. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  55338. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  55339. subMeshes: submeshes,
  55340. checkCollisions: mesh.checkCollisions
  55341. };
  55342. };
  55343. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  55344. return {
  55345. id: geometry.id,
  55346. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  55347. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  55348. indices: new Uint32Array(geometry.getIndices() || []),
  55349. };
  55350. };
  55351. return CollisionCoordinatorWorker;
  55352. }());
  55353. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  55354. var CollisionCoordinatorLegacy = /** @class */ (function () {
  55355. function CollisionCoordinatorLegacy() {
  55356. this._scaledPosition = BABYLON.Vector3.Zero();
  55357. this._scaledVelocity = BABYLON.Vector3.Zero();
  55358. this._finalPosition = BABYLON.Vector3.Zero();
  55359. }
  55360. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55361. position.divideToRef(collider._radius, this._scaledPosition);
  55362. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55363. collider.collidedMesh = null;
  55364. collider._retry = 0;
  55365. collider._initialVelocity = this._scaledVelocity;
  55366. collider._initialPosition = this._scaledPosition;
  55367. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  55368. this._finalPosition.multiplyInPlace(collider._radius);
  55369. //run the callback
  55370. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  55371. };
  55372. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  55373. this._scene = scene;
  55374. };
  55375. CollisionCoordinatorLegacy.prototype.destroy = function () {
  55376. //Legacy need no destruction method.
  55377. };
  55378. //No update in legacy mode
  55379. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  55380. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  55381. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  55382. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  55383. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  55384. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  55385. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  55386. if (excludedMesh === void 0) { excludedMesh = null; }
  55387. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  55388. if (collider._retry >= maximumRetry) {
  55389. finalPosition.copyFrom(position);
  55390. return;
  55391. }
  55392. // Check if this is a mesh else camera or -1
  55393. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  55394. collider._initialize(position, velocity, closeDistance);
  55395. // Check all meshes
  55396. for (var index = 0; index < this._scene.meshes.length; index++) {
  55397. var mesh = this._scene.meshes[index];
  55398. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  55399. mesh._checkCollision(collider);
  55400. }
  55401. }
  55402. if (!collider.collisionFound) {
  55403. position.addToRef(velocity, finalPosition);
  55404. return;
  55405. }
  55406. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  55407. collider._getResponse(position, velocity);
  55408. }
  55409. if (velocity.length() <= closeDistance) {
  55410. finalPosition.copyFrom(position);
  55411. return;
  55412. }
  55413. collider._retry++;
  55414. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  55415. };
  55416. return CollisionCoordinatorLegacy;
  55417. }());
  55418. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  55419. })(BABYLON || (BABYLON = {}));
  55420. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  55421. var BABYLON;
  55422. (function (BABYLON) {
  55423. /**
  55424. * A particle represents one of the element emitted by a particle system.
  55425. * This is mainly define by its coordinates, direction, velocity and age.
  55426. */
  55427. var Particle = /** @class */ (function () {
  55428. /**
  55429. * Creates a new instance Particle
  55430. * @param particleSystem the particle system the particle belongs to
  55431. */
  55432. function Particle(
  55433. /**
  55434. * particleSystem the particle system the particle belongs to.
  55435. */
  55436. particleSystem) {
  55437. this.particleSystem = particleSystem;
  55438. /**
  55439. * The world position of the particle in the scene.
  55440. */
  55441. this.position = BABYLON.Vector3.Zero();
  55442. /**
  55443. * The world direction of the particle in the scene.
  55444. */
  55445. this.direction = BABYLON.Vector3.Zero();
  55446. /**
  55447. * The color of the particle.
  55448. */
  55449. this.color = new BABYLON.Color4(0, 0, 0, 0);
  55450. /**
  55451. * The color change of the particle per step.
  55452. */
  55453. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  55454. /**
  55455. * Defines how long will the life of the particle be.
  55456. */
  55457. this.lifeTime = 1.0;
  55458. /**
  55459. * The current age of the particle.
  55460. */
  55461. this.age = 0;
  55462. /**
  55463. * The current size of the particle.
  55464. */
  55465. this.size = 0;
  55466. /**
  55467. * The current scale of the particle.
  55468. */
  55469. this.scale = new BABYLON.Vector2(1, 1);
  55470. /**
  55471. * The current angle of the particle.
  55472. */
  55473. this.angle = 0;
  55474. /**
  55475. * Defines how fast is the angle changing.
  55476. */
  55477. this.angularSpeed = 0;
  55478. /**
  55479. * Defines the cell index used by the particle to be rendered from a sprite.
  55480. */
  55481. this.cellIndex = 0;
  55482. /** @hidden */
  55483. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  55484. /** @hidden */
  55485. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  55486. /** @hidden */
  55487. this._currentSize1 = 0;
  55488. /** @hidden */
  55489. this._currentSize2 = 0;
  55490. /** @hidden */
  55491. this._currentAngularSpeed1 = 0;
  55492. /** @hidden */
  55493. this._currentAngularSpeed2 = 0;
  55494. /** @hidden */
  55495. this._currentVelocity1 = 0;
  55496. /** @hidden */
  55497. this._currentVelocity2 = 0;
  55498. /** @hidden */
  55499. this._currentLimitVelocity1 = 0;
  55500. /** @hidden */
  55501. this._currentLimitVelocity2 = 0;
  55502. /** @hidden */
  55503. this._currentDrag1 = 0;
  55504. /** @hidden */
  55505. this._currentDrag2 = 0;
  55506. if (!this.particleSystem.isAnimationSheetEnabled) {
  55507. return;
  55508. }
  55509. this.updateCellInfoFromSystem();
  55510. }
  55511. Particle.prototype.updateCellInfoFromSystem = function () {
  55512. this.cellIndex = this.particleSystem.startSpriteCellID;
  55513. };
  55514. /**
  55515. * Defines how the sprite cell index is updated for the particle
  55516. */
  55517. Particle.prototype.updateCellIndex = function () {
  55518. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  55519. var ratio = BABYLON.Scalar.Clamp(((this.age * this.particleSystem.spriteCellChangeSpeed) % this.lifeTime) / this.lifeTime);
  55520. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  55521. };
  55522. /**
  55523. * Copy the properties of particle to another one.
  55524. * @param other the particle to copy the information to.
  55525. */
  55526. Particle.prototype.copyTo = function (other) {
  55527. other.position.copyFrom(this.position);
  55528. if (this._initialDirection) {
  55529. if (other._initialDirection) {
  55530. other._initialDirection.copyFrom(this._initialDirection);
  55531. }
  55532. else {
  55533. other._initialDirection = this._initialDirection.clone();
  55534. }
  55535. }
  55536. else {
  55537. other._initialDirection = null;
  55538. }
  55539. other.direction.copyFrom(this.direction);
  55540. other.color.copyFrom(this.color);
  55541. other.colorStep.copyFrom(this.colorStep);
  55542. other.lifeTime = this.lifeTime;
  55543. other.age = this.age;
  55544. other.size = this.size;
  55545. other.scale.copyFrom(this.scale);
  55546. other.angle = this.angle;
  55547. other.angularSpeed = this.angularSpeed;
  55548. other.particleSystem = this.particleSystem;
  55549. other.cellIndex = this.cellIndex;
  55550. if (this._currentColorGradient) {
  55551. other._currentColorGradient = this._currentColorGradient;
  55552. other._currentColor1.copyFrom(this._currentColor1);
  55553. other._currentColor2.copyFrom(this._currentColor2);
  55554. }
  55555. if (this._currentSizeGradient) {
  55556. other._currentSizeGradient = this._currentSizeGradient;
  55557. other._currentSize1 = this._currentSize1;
  55558. other._currentSize2 = this._currentSize2;
  55559. }
  55560. if (this._currentAngularSpeedGradient) {
  55561. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  55562. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  55563. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  55564. }
  55565. if (this._currentVelocityGradient) {
  55566. other._currentVelocityGradient = this._currentVelocityGradient;
  55567. other._currentVelocity1 = this._currentVelocity1;
  55568. other._currentVelocity2 = this._currentVelocity2;
  55569. }
  55570. if (this._currentLimitVelocityGradient) {
  55571. other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
  55572. other._currentLimitVelocity1 = this._currentLimitVelocity1;
  55573. other._currentLimitVelocity2 = this._currentLimitVelocity2;
  55574. }
  55575. if (this._currentDragGradient) {
  55576. other._currentDragGradient = this._currentDragGradient;
  55577. other._currentDrag1 = this._currentDrag1;
  55578. other._currentDrag2 = this._currentDrag2;
  55579. }
  55580. if (this.particleSystem.isAnimationSheetEnabled) {
  55581. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  55582. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  55583. }
  55584. };
  55585. return Particle;
  55586. }());
  55587. BABYLON.Particle = Particle;
  55588. })(BABYLON || (BABYLON = {}));
  55589. //# sourceMappingURL=babylon.particle.js.map
  55590. var BABYLON;
  55591. (function (BABYLON) {
  55592. /**
  55593. * This represents the base class for particle system in Babylon.
  55594. * 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.
  55595. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55596. * @example https://doc.babylonjs.com/babylon101/particles
  55597. */
  55598. var BaseParticleSystem = /** @class */ (function () {
  55599. /**
  55600. * Instantiates a particle system.
  55601. * 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.
  55602. * @param name The name of the particle system
  55603. */
  55604. function BaseParticleSystem(name) {
  55605. /**
  55606. * List of animations used by the particle system.
  55607. */
  55608. this.animations = [];
  55609. /**
  55610. * The rendering group used by the Particle system to chose when to render.
  55611. */
  55612. this.renderingGroupId = 0;
  55613. /**
  55614. * The emitter represents the Mesh or position we are attaching the particle system to.
  55615. */
  55616. this.emitter = null;
  55617. /**
  55618. * The maximum number of particles to emit per frame
  55619. */
  55620. this.emitRate = 10;
  55621. /**
  55622. * If you want to launch only a few particles at once, that can be done, as well.
  55623. */
  55624. this.manualEmitCount = -1;
  55625. /**
  55626. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55627. */
  55628. this.updateSpeed = 0.01;
  55629. /**
  55630. * The amount of time the particle system is running (depends of the overall update speed).
  55631. */
  55632. this.targetStopDuration = 0;
  55633. /**
  55634. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55635. */
  55636. this.disposeOnStop = false;
  55637. /**
  55638. * Minimum power of emitting particles.
  55639. */
  55640. this.minEmitPower = 1;
  55641. /**
  55642. * Maximum power of emitting particles.
  55643. */
  55644. this.maxEmitPower = 1;
  55645. /**
  55646. * Minimum life time of emitting particles.
  55647. */
  55648. this.minLifeTime = 1;
  55649. /**
  55650. * Maximum life time of emitting particles.
  55651. */
  55652. this.maxLifeTime = 1;
  55653. /**
  55654. * Minimum Size of emitting particles.
  55655. */
  55656. this.minSize = 1;
  55657. /**
  55658. * Maximum Size of emitting particles.
  55659. */
  55660. this.maxSize = 1;
  55661. /**
  55662. * Minimum scale of emitting particles on X axis.
  55663. */
  55664. this.minScaleX = 1;
  55665. /**
  55666. * Maximum scale of emitting particles on X axis.
  55667. */
  55668. this.maxScaleX = 1;
  55669. /**
  55670. * Minimum scale of emitting particles on Y axis.
  55671. */
  55672. this.minScaleY = 1;
  55673. /**
  55674. * Maximum scale of emitting particles on Y axis.
  55675. */
  55676. this.maxScaleY = 1;
  55677. /**
  55678. * Gets or sets the minimal initial rotation in radians.
  55679. */
  55680. this.minInitialRotation = 0;
  55681. /**
  55682. * Gets or sets the maximal initial rotation in radians.
  55683. */
  55684. this.maxInitialRotation = 0;
  55685. /**
  55686. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55687. */
  55688. this.minAngularSpeed = 0;
  55689. /**
  55690. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55691. */
  55692. this.maxAngularSpeed = 0;
  55693. /**
  55694. * The layer mask we are rendering the particles through.
  55695. */
  55696. this.layerMask = 0x0FFFFFFF;
  55697. /**
  55698. * This can help using your own shader to render the particle system.
  55699. * The according effect will be created
  55700. */
  55701. this.customShader = null;
  55702. /**
  55703. * By default particle system starts as soon as they are created. This prevents the
  55704. * automatic start to happen and let you decide when to start emitting particles.
  55705. */
  55706. this.preventAutoStart = false;
  55707. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  55708. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  55709. /**
  55710. * Callback triggered when the particle animation is ending.
  55711. */
  55712. this.onAnimationEnd = null;
  55713. /**
  55714. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55715. */
  55716. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  55717. /**
  55718. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55719. * to override the particles.
  55720. */
  55721. this.forceDepthWrite = false;
  55722. /** 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 */
  55723. this.preWarmCycles = 0;
  55724. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  55725. this.preWarmStepOffset = 1;
  55726. /**
  55727. * 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)
  55728. */
  55729. this.spriteCellChangeSpeed = 1;
  55730. /**
  55731. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  55732. */
  55733. this.startSpriteCellID = 0;
  55734. /**
  55735. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  55736. */
  55737. this.endSpriteCellID = 0;
  55738. /**
  55739. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  55740. */
  55741. this.spriteCellWidth = 0;
  55742. /**
  55743. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  55744. */
  55745. this.spriteCellHeight = 0;
  55746. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  55747. this.translationPivot = new BABYLON.Vector2(0, 0);
  55748. /**
  55749. * You can use gravity if you want to give an orientation to your particles.
  55750. */
  55751. this.gravity = BABYLON.Vector3.Zero();
  55752. this._colorGradients = null;
  55753. this._sizeGradients = null;
  55754. this._lifeTimeGradients = null;
  55755. this._angularSpeedGradients = null;
  55756. this._velocityGradients = null;
  55757. this._limitVelocityGradients = null;
  55758. this._dragGradients = null;
  55759. this._emitRateGradients = null;
  55760. /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */
  55761. this.limitVelocityDamping = 0.4;
  55762. /**
  55763. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55764. */
  55765. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55766. /**
  55767. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55768. */
  55769. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55770. /**
  55771. * Color the particle will have at the end of its lifetime
  55772. */
  55773. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55774. /**
  55775. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  55776. */
  55777. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55778. /**
  55779. * Gets or sets the billboard mode to use when isBillboardBased = true.
  55780. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  55781. */
  55782. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  55783. this._isBillboardBased = true;
  55784. /**
  55785. * Local cache of defines for image processing.
  55786. */
  55787. this._imageProcessingConfigurationDefines = new BABYLON.ImageProcessingConfigurationDefines();
  55788. this.id = name;
  55789. this.name = name;
  55790. }
  55791. Object.defineProperty(BaseParticleSystem.prototype, "isAnimationSheetEnabled", {
  55792. /**
  55793. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  55794. */
  55795. get: function () {
  55796. return this._isAnimationSheetEnabled;
  55797. },
  55798. set: function (value) {
  55799. if (this._isAnimationSheetEnabled == value) {
  55800. return;
  55801. }
  55802. this._isAnimationSheetEnabled = value;
  55803. this._reset();
  55804. },
  55805. enumerable: true,
  55806. configurable: true
  55807. });
  55808. /**
  55809. * Gets the current list of drag gradients.
  55810. * You must use addDragGradient and removeDragGradient to udpate this list
  55811. * @returns the list of drag gradients
  55812. */
  55813. BaseParticleSystem.prototype.getDragGradients = function () {
  55814. return this._dragGradients;
  55815. };
  55816. /**
  55817. * Gets the current list of limit velocity gradients.
  55818. * You must use addLimitVelocityGradient and removeLimitVelocityGradient to udpate this list
  55819. * @returns the list of limit velocity gradients
  55820. */
  55821. BaseParticleSystem.prototype.getLimitVelocityGradients = function () {
  55822. return this._limitVelocityGradients;
  55823. };
  55824. /**
  55825. * Gets the current list of color gradients.
  55826. * You must use addColorGradient and removeColorGradient to udpate this list
  55827. * @returns the list of color gradients
  55828. */
  55829. BaseParticleSystem.prototype.getColorGradients = function () {
  55830. return this._colorGradients;
  55831. };
  55832. /**
  55833. * Gets the current list of size gradients.
  55834. * You must use addSizeGradient and removeSizeGradient to udpate this list
  55835. * @returns the list of size gradients
  55836. */
  55837. BaseParticleSystem.prototype.getSizeGradients = function () {
  55838. return this._sizeGradients;
  55839. };
  55840. /**
  55841. * Gets the current list of life time gradients.
  55842. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  55843. * @returns the list of life time gradients
  55844. */
  55845. BaseParticleSystem.prototype.getLifeTimeGradients = function () {
  55846. return this._lifeTimeGradients;
  55847. };
  55848. /**
  55849. * Gets the current list of angular speed gradients.
  55850. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  55851. * @returns the list of angular speed gradients
  55852. */
  55853. BaseParticleSystem.prototype.getAngularSpeedGradients = function () {
  55854. return this._angularSpeedGradients;
  55855. };
  55856. /**
  55857. * Gets the current list of velocity gradients.
  55858. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  55859. * @returns the list of velocity gradients
  55860. */
  55861. BaseParticleSystem.prototype.getVelocityGradients = function () {
  55862. return this._velocityGradients;
  55863. };
  55864. /**
  55865. * Gets the current list of emit rate gradients.
  55866. * You must use addEmitRateGradient and removeEmitRateGradient to udpate this list
  55867. * @returns the list of emit rate gradients
  55868. */
  55869. BaseParticleSystem.prototype.getEmitRateGradients = function () {
  55870. return this._emitRateGradients;
  55871. };
  55872. Object.defineProperty(BaseParticleSystem.prototype, "direction1", {
  55873. /**
  55874. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55875. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55876. */
  55877. get: function () {
  55878. if (this.particleEmitterType.direction1) {
  55879. return this.particleEmitterType.direction1;
  55880. }
  55881. return BABYLON.Vector3.Zero();
  55882. },
  55883. set: function (value) {
  55884. if (this.particleEmitterType.direction1) {
  55885. this.particleEmitterType.direction1 = value;
  55886. }
  55887. },
  55888. enumerable: true,
  55889. configurable: true
  55890. });
  55891. Object.defineProperty(BaseParticleSystem.prototype, "direction2", {
  55892. /**
  55893. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55894. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55895. */
  55896. get: function () {
  55897. if (this.particleEmitterType.direction2) {
  55898. return this.particleEmitterType.direction2;
  55899. }
  55900. return BABYLON.Vector3.Zero();
  55901. },
  55902. set: function (value) {
  55903. if (this.particleEmitterType.direction2) {
  55904. this.particleEmitterType.direction2 = value;
  55905. }
  55906. },
  55907. enumerable: true,
  55908. configurable: true
  55909. });
  55910. Object.defineProperty(BaseParticleSystem.prototype, "minEmitBox", {
  55911. /**
  55912. * 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.
  55913. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55914. */
  55915. get: function () {
  55916. if (this.particleEmitterType.minEmitBox) {
  55917. return this.particleEmitterType.minEmitBox;
  55918. }
  55919. return BABYLON.Vector3.Zero();
  55920. },
  55921. set: function (value) {
  55922. if (this.particleEmitterType.minEmitBox) {
  55923. this.particleEmitterType.minEmitBox = value;
  55924. }
  55925. },
  55926. enumerable: true,
  55927. configurable: true
  55928. });
  55929. Object.defineProperty(BaseParticleSystem.prototype, "maxEmitBox", {
  55930. /**
  55931. * 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.
  55932. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55933. */
  55934. get: function () {
  55935. if (this.particleEmitterType.maxEmitBox) {
  55936. return this.particleEmitterType.maxEmitBox;
  55937. }
  55938. return BABYLON.Vector3.Zero();
  55939. },
  55940. set: function (value) {
  55941. if (this.particleEmitterType.maxEmitBox) {
  55942. this.particleEmitterType.maxEmitBox = value;
  55943. }
  55944. },
  55945. enumerable: true,
  55946. configurable: true
  55947. });
  55948. Object.defineProperty(BaseParticleSystem.prototype, "isBillboardBased", {
  55949. /**
  55950. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  55951. */
  55952. get: function () {
  55953. return this._isBillboardBased;
  55954. },
  55955. set: function (value) {
  55956. if (this._isBillboardBased === value) {
  55957. return;
  55958. }
  55959. this._isBillboardBased = value;
  55960. this._reset();
  55961. },
  55962. enumerable: true,
  55963. configurable: true
  55964. });
  55965. Object.defineProperty(BaseParticleSystem.prototype, "imageProcessingConfiguration", {
  55966. /**
  55967. * Gets the image processing configuration used either in this material.
  55968. */
  55969. get: function () {
  55970. return this._imageProcessingConfiguration;
  55971. },
  55972. /**
  55973. * Sets the Default image processing configuration used either in the this material.
  55974. *
  55975. * If sets to null, the scene one is in use.
  55976. */
  55977. set: function (value) {
  55978. this._attachImageProcessingConfiguration(value);
  55979. },
  55980. enumerable: true,
  55981. configurable: true
  55982. });
  55983. /**
  55984. * Attaches a new image processing configuration to the Standard Material.
  55985. * @param configuration
  55986. */
  55987. BaseParticleSystem.prototype._attachImageProcessingConfiguration = function (configuration) {
  55988. if (configuration === this._imageProcessingConfiguration) {
  55989. return;
  55990. }
  55991. // Pick the scene configuration if needed.
  55992. if (!configuration) {
  55993. this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;
  55994. }
  55995. else {
  55996. this._imageProcessingConfiguration = configuration;
  55997. }
  55998. };
  55999. /** @hidden */
  56000. BaseParticleSystem.prototype._reset = function () {
  56001. };
  56002. /**
  56003. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  56004. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56005. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56006. * @returns the emitter
  56007. */
  56008. BaseParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
  56009. var particleEmitter = new BABYLON.PointParticleEmitter();
  56010. particleEmitter.direction1 = direction1;
  56011. particleEmitter.direction2 = direction2;
  56012. this.particleEmitterType = particleEmitter;
  56013. return particleEmitter;
  56014. };
  56015. /**
  56016. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  56017. * @param radius The radius of the hemisphere to emit from
  56018. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  56019. * @returns the emitter
  56020. */
  56021. BaseParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
  56022. if (radius === void 0) { radius = 1; }
  56023. if (radiusRange === void 0) { radiusRange = 1; }
  56024. var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
  56025. this.particleEmitterType = particleEmitter;
  56026. return particleEmitter;
  56027. };
  56028. /**
  56029. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  56030. * @param radius The radius of the sphere to emit from
  56031. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  56032. * @returns the emitter
  56033. */
  56034. BaseParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  56035. if (radius === void 0) { radius = 1; }
  56036. if (radiusRange === void 0) { radiusRange = 1; }
  56037. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  56038. this.particleEmitterType = particleEmitter;
  56039. return particleEmitter;
  56040. };
  56041. /**
  56042. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  56043. * @param radius The radius of the sphere to emit from
  56044. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56045. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56046. * @returns the emitter
  56047. */
  56048. BaseParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56049. if (radius === void 0) { radius = 1; }
  56050. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56051. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56052. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56053. this.particleEmitterType = particleEmitter;
  56054. return particleEmitter;
  56055. };
  56056. /**
  56057. * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position)
  56058. * @param radius The radius of the emission cylinder
  56059. * @param height The height of the emission cylinder
  56060. * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius
  56061. * @param directionRandomizer How much to randomize the particle direction [0-1]
  56062. * @returns the emitter
  56063. */
  56064. BaseParticleSystem.prototype.createCylinderEmitter = function (radius, height, radiusRange, directionRandomizer) {
  56065. if (radius === void 0) { radius = 1; }
  56066. if (height === void 0) { height = 1; }
  56067. if (radiusRange === void 0) { radiusRange = 1; }
  56068. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56069. var particleEmitter = new BABYLON.CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer);
  56070. this.particleEmitterType = particleEmitter;
  56071. return particleEmitter;
  56072. };
  56073. /**
  56074. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  56075. * @param radius The radius of the cone to emit from
  56076. * @param angle The base angle of the cone
  56077. * @returns the emitter
  56078. */
  56079. BaseParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56080. if (radius === void 0) { radius = 1; }
  56081. if (angle === void 0) { angle = Math.PI / 4; }
  56082. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56083. this.particleEmitterType = particleEmitter;
  56084. return particleEmitter;
  56085. };
  56086. /**
  56087. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56088. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56089. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56090. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56091. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56092. * @returns the emitter
  56093. */
  56094. BaseParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56095. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56096. this.particleEmitterType = particleEmitter;
  56097. this.direction1 = direction1;
  56098. this.direction2 = direction2;
  56099. this.minEmitBox = minEmitBox;
  56100. this.maxEmitBox = maxEmitBox;
  56101. return particleEmitter;
  56102. };
  56103. /**
  56104. * Source color is added to the destination color without alpha affecting the result.
  56105. */
  56106. BaseParticleSystem.BLENDMODE_ONEONE = 0;
  56107. /**
  56108. * Blend current color and particle color using particle’s alpha.
  56109. */
  56110. BaseParticleSystem.BLENDMODE_STANDARD = 1;
  56111. /**
  56112. * Add current color and particle color multiplied by particle’s alpha.
  56113. */
  56114. BaseParticleSystem.BLENDMODE_ADD = 2;
  56115. /**
  56116. * Multiply current color with particle color
  56117. */
  56118. BaseParticleSystem.BLENDMODE_MULTIPLY = 3;
  56119. return BaseParticleSystem;
  56120. }());
  56121. BABYLON.BaseParticleSystem = BaseParticleSystem;
  56122. })(BABYLON || (BABYLON = {}));
  56123. //# sourceMappingURL=babylon.baseParticleSystem.js.map
  56124. var BABYLON;
  56125. (function (BABYLON) {
  56126. /**
  56127. * This represents a particle system in Babylon.
  56128. * 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.
  56129. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  56130. * @example https://doc.babylonjs.com/babylon101/particles
  56131. */
  56132. var ParticleSystem = /** @class */ (function (_super) {
  56133. __extends(ParticleSystem, _super);
  56134. /**
  56135. * Instantiates a particle system.
  56136. * 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.
  56137. * @param name The name of the particle system
  56138. * @param capacity The max number of particles alive at the same time
  56139. * @param scene The scene the particle system belongs to
  56140. * @param customEffect a custom effect used to change the way particles are rendered by default
  56141. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  56142. * @param epsilon Offset used to render the particles
  56143. */
  56144. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  56145. if (customEffect === void 0) { customEffect = null; }
  56146. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56147. if (epsilon === void 0) { epsilon = 0.01; }
  56148. var _this = _super.call(this, name) || this;
  56149. /**
  56150. * An event triggered when the system is disposed
  56151. */
  56152. _this.onDisposeObservable = new BABYLON.Observable();
  56153. _this._particles = new Array();
  56154. _this._stockParticles = new Array();
  56155. _this._newPartsExcess = 0;
  56156. _this._vertexBuffers = {};
  56157. _this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  56158. _this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  56159. _this._scaledDirection = BABYLON.Vector3.Zero();
  56160. _this._scaledGravity = BABYLON.Vector3.Zero();
  56161. _this._currentRenderId = -1;
  56162. _this._useInstancing = false;
  56163. _this._started = false;
  56164. _this._stopped = false;
  56165. _this._actualFrame = 0;
  56166. /** @hidden */
  56167. _this._currentEmitRate1 = 0;
  56168. /** @hidden */
  56169. _this._currentEmitRate2 = 0;
  56170. // start of sub system methods
  56171. /**
  56172. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  56173. * Its lifetime will start back at 0.
  56174. */
  56175. _this.recycleParticle = function (particle) {
  56176. var lastParticle = _this._particles.pop();
  56177. if (lastParticle !== particle) {
  56178. lastParticle.copyTo(particle);
  56179. }
  56180. _this._stockParticles.push(lastParticle);
  56181. };
  56182. _this._createParticle = function () {
  56183. var particle;
  56184. if (_this._stockParticles.length !== 0) {
  56185. particle = _this._stockParticles.pop();
  56186. particle.age = 0;
  56187. particle._currentColorGradient = null;
  56188. particle.cellIndex = _this.startSpriteCellID;
  56189. }
  56190. else {
  56191. particle = new BABYLON.Particle(_this);
  56192. }
  56193. return particle;
  56194. };
  56195. _this._emitFromParticle = function (particle) {
  56196. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  56197. return;
  56198. }
  56199. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  56200. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  56201. subSystem._rootParticleSystem = _this;
  56202. _this.activeSubSystems.push(subSystem);
  56203. subSystem.start();
  56204. };
  56205. _this._capacity = capacity;
  56206. _this._epsilon = epsilon;
  56207. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  56208. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56209. // Setup the default processing configuration to the scene.
  56210. _this._attachImageProcessingConfiguration(null);
  56211. _this._customEffect = customEffect;
  56212. _this._scene.particleSystems.push(_this);
  56213. _this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
  56214. _this._createIndexBuffer();
  56215. _this._createVertexBuffers();
  56216. // Default emitter type
  56217. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56218. _this.updateFunction = function (particles) {
  56219. var noiseTextureData = null;
  56220. var noiseTextureSize = null;
  56221. if (_this.noiseTexture) { // We need to get texture data back to CPU
  56222. noiseTextureData = (_this.noiseTexture.readPixels());
  56223. noiseTextureSize = _this.noiseTexture.getSize();
  56224. }
  56225. var _loop_1 = function () {
  56226. particle = particles[index];
  56227. particle.age += _this._scaledUpdateSpeed;
  56228. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  56229. _this._emitFromParticle(particle);
  56230. _this.recycleParticle(particle);
  56231. index--;
  56232. return "continue";
  56233. }
  56234. else {
  56235. var ratio = particle.age / particle.lifeTime;
  56236. // Color
  56237. if (_this._colorGradients && _this._colorGradients.length > 0) {
  56238. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  56239. if (currentGradient !== particle._currentColorGradient) {
  56240. particle._currentColor1.copyFrom(particle._currentColor2);
  56241. nextGradient.getColorToRef(particle._currentColor2);
  56242. particle._currentColorGradient = currentGradient;
  56243. }
  56244. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  56245. });
  56246. }
  56247. else {
  56248. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  56249. particle.color.addInPlace(_this._scaledColorStep);
  56250. if (particle.color.a < 0) {
  56251. particle.color.a = 0;
  56252. }
  56253. }
  56254. // Angular speed
  56255. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  56256. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  56257. if (currentGradient !== particle._currentAngularSpeedGradient) {
  56258. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  56259. particle._currentAngularSpeed2 = nextGradient.getFactor();
  56260. particle._currentAngularSpeedGradient = currentGradient;
  56261. }
  56262. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  56263. });
  56264. }
  56265. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  56266. // Direction
  56267. var directionScale_1 = _this._scaledUpdateSpeed;
  56268. /// Velocity
  56269. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  56270. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  56271. if (currentGradient !== particle._currentVelocityGradient) {
  56272. particle._currentVelocity1 = particle._currentVelocity2;
  56273. particle._currentVelocity2 = nextGradient.getFactor();
  56274. particle._currentVelocityGradient = currentGradient;
  56275. }
  56276. directionScale_1 *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  56277. });
  56278. }
  56279. particle.direction.scaleToRef(directionScale_1, _this._scaledDirection);
  56280. /// Limit velocity
  56281. if (_this._limitVelocityGradients && _this._limitVelocityGradients.length > 0) {
  56282. BABYLON.Tools.GetCurrentGradient(ratio, _this._limitVelocityGradients, function (currentGradient, nextGradient, scale) {
  56283. if (currentGradient !== particle._currentLimitVelocityGradient) {
  56284. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  56285. particle._currentLimitVelocity2 = nextGradient.getFactor();
  56286. particle._currentLimitVelocityGradient = currentGradient;
  56287. }
  56288. var limitVelocity = BABYLON.Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  56289. var currentVelocity = particle.direction.length();
  56290. if (currentVelocity > limitVelocity) {
  56291. particle.direction.scaleInPlace(_this.limitVelocityDamping);
  56292. }
  56293. });
  56294. }
  56295. /// Drag
  56296. if (_this._dragGradients && _this._dragGradients.length > 0) {
  56297. BABYLON.Tools.GetCurrentGradient(ratio, _this._dragGradients, function (currentGradient, nextGradient, scale) {
  56298. if (currentGradient !== particle._currentDragGradient) {
  56299. particle._currentDrag1 = particle._currentDrag2;
  56300. particle._currentDrag2 = nextGradient.getFactor();
  56301. particle._currentDragGradient = currentGradient;
  56302. }
  56303. var drag = BABYLON.Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale);
  56304. _this._scaledDirection.scaleInPlace(drag);
  56305. });
  56306. }
  56307. particle.position.addInPlace(_this._scaledDirection);
  56308. // Noise
  56309. if (noiseTextureData && noiseTextureSize) {
  56310. var localPosition = BABYLON.Tmp.Vector3[0];
  56311. var emitterPosition = BABYLON.Tmp.Vector3[1];
  56312. _this._emitterWorldMatrix.getTranslationToRef(emitterPosition);
  56313. particle.position.subtractToRef(emitterPosition, localPosition);
  56314. var fetchedColorR = _this._fetchR(localPosition.y, localPosition.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56315. var fetchedColorG = _this._fetchR(localPosition.x + 0.33, localPosition.z + 0.33, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56316. var fetchedColorB = _this._fetchR(localPosition.x - 0.33, localPosition.y - 0.33, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56317. var force = BABYLON.Tmp.Vector3[0];
  56318. var scaledForce = BABYLON.Tmp.Vector3[1];
  56319. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  56320. force.scaleToRef(_this._scaledUpdateSpeed, scaledForce);
  56321. particle.direction.addInPlace(scaledForce);
  56322. }
  56323. // Gravity
  56324. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  56325. particle.direction.addInPlace(_this._scaledGravity);
  56326. // Size
  56327. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  56328. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  56329. if (currentGradient !== particle._currentSizeGradient) {
  56330. particle._currentSize1 = particle._currentSize2;
  56331. particle._currentSize2 = nextGradient.getFactor();
  56332. particle._currentSizeGradient = currentGradient;
  56333. }
  56334. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  56335. });
  56336. }
  56337. if (_this._isAnimationSheetEnabled) {
  56338. particle.updateCellIndex();
  56339. }
  56340. }
  56341. };
  56342. var particle;
  56343. for (var index = 0; index < particles.length; index++) {
  56344. _loop_1();
  56345. }
  56346. };
  56347. return _this;
  56348. }
  56349. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  56350. /**
  56351. * Sets a callback that will be triggered when the system is disposed
  56352. */
  56353. set: function (callback) {
  56354. if (this._onDisposeObserver) {
  56355. this.onDisposeObservable.remove(this._onDisposeObserver);
  56356. }
  56357. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  56358. },
  56359. enumerable: true,
  56360. configurable: true
  56361. });
  56362. /**
  56363. * Get hosting scene
  56364. * @returns the scene
  56365. */
  56366. ParticleSystem.prototype.getScene = function () {
  56367. return this._scene;
  56368. };
  56369. Object.defineProperty(ParticleSystem.prototype, "particles", {
  56370. //end of Sub-emitter
  56371. /**
  56372. * Gets the current list of active particles
  56373. */
  56374. get: function () {
  56375. return this._particles;
  56376. },
  56377. enumerable: true,
  56378. configurable: true
  56379. });
  56380. /**
  56381. * Returns the string "ParticleSystem"
  56382. * @returns a string containing the class name
  56383. */
  56384. ParticleSystem.prototype.getClassName = function () {
  56385. return "ParticleSystem";
  56386. };
  56387. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  56388. var newGradient = new BABYLON.FactorGradient();
  56389. newGradient.gradient = gradient;
  56390. newGradient.factor1 = factor;
  56391. newGradient.factor2 = factor2;
  56392. factorGradients.push(newGradient);
  56393. factorGradients.sort(function (a, b) {
  56394. if (a.gradient < b.gradient) {
  56395. return -1;
  56396. }
  56397. else if (a.gradient > b.gradient) {
  56398. return 1;
  56399. }
  56400. return 0;
  56401. });
  56402. };
  56403. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  56404. if (!factorGradients) {
  56405. return;
  56406. }
  56407. var index = 0;
  56408. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  56409. var factorGradient = factorGradients_1[_i];
  56410. if (factorGradient.gradient === gradient) {
  56411. factorGradients.splice(index, 1);
  56412. break;
  56413. }
  56414. index++;
  56415. }
  56416. };
  56417. /**
  56418. * Adds a new life time gradient
  56419. * @param gradient defines the gradient to use (between 0 and 1)
  56420. * @param factor defines the life time factor to affect to the specified gradient
  56421. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56422. * @returns the current particle system
  56423. */
  56424. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  56425. if (!this._lifeTimeGradients) {
  56426. this._lifeTimeGradients = [];
  56427. }
  56428. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  56429. return this;
  56430. };
  56431. /**
  56432. * Remove a specific life time gradient
  56433. * @param gradient defines the gradient to remove
  56434. * @returns the current particle system
  56435. */
  56436. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  56437. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  56438. return this;
  56439. };
  56440. /**
  56441. * Adds a new size gradient
  56442. * @param gradient defines the gradient to use (between 0 and 1)
  56443. * @param factor defines the size factor to affect to the specified gradient
  56444. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56445. * @returns the current particle system
  56446. */
  56447. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  56448. if (!this._sizeGradients) {
  56449. this._sizeGradients = [];
  56450. }
  56451. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  56452. return this;
  56453. };
  56454. /**
  56455. * Remove a specific size gradient
  56456. * @param gradient defines the gradient to remove
  56457. * @returns the current particle system
  56458. */
  56459. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  56460. this._removeFactorGradient(this._sizeGradients, gradient);
  56461. return this;
  56462. };
  56463. /**
  56464. * Adds a new angular speed gradient
  56465. * @param gradient defines the gradient to use (between 0 and 1)
  56466. * @param factor defines the angular speed to affect to the specified gradient
  56467. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56468. * @returns the current particle system
  56469. */
  56470. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  56471. if (!this._angularSpeedGradients) {
  56472. this._angularSpeedGradients = [];
  56473. }
  56474. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  56475. return this;
  56476. };
  56477. /**
  56478. * Remove a specific angular speed gradient
  56479. * @param gradient defines the gradient to remove
  56480. * @returns the current particle system
  56481. */
  56482. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  56483. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  56484. return this;
  56485. };
  56486. /**
  56487. * Adds a new velocity gradient
  56488. * @param gradient defines the gradient to use (between 0 and 1)
  56489. * @param factor defines the velocity to affect to the specified gradient
  56490. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56491. * @returns the current particle system
  56492. */
  56493. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  56494. if (!this._velocityGradients) {
  56495. this._velocityGradients = [];
  56496. }
  56497. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  56498. return this;
  56499. };
  56500. /**
  56501. * Remove a specific velocity gradient
  56502. * @param gradient defines the gradient to remove
  56503. * @returns the current particle system
  56504. */
  56505. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  56506. this._removeFactorGradient(this._velocityGradients, gradient);
  56507. return this;
  56508. };
  56509. /**
  56510. * Adds a new limit velocity gradient
  56511. * @param gradient defines the gradient to use (between 0 and 1)
  56512. * @param factor defines the limit velocity value to affect to the specified gradient
  56513. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56514. * @returns the current particle system
  56515. */
  56516. ParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor, factor2) {
  56517. if (!this._limitVelocityGradients) {
  56518. this._limitVelocityGradients = [];
  56519. }
  56520. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  56521. return this;
  56522. };
  56523. /**
  56524. * Remove a specific limit velocity gradient
  56525. * @param gradient defines the gradient to remove
  56526. * @returns the current particle system
  56527. */
  56528. ParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  56529. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  56530. return this;
  56531. };
  56532. /**
  56533. * Adds a new drag gradient
  56534. * @param gradient defines the gradient to use (between 0 and 1)
  56535. * @param factor defines the drag value to affect to the specified gradient
  56536. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56537. * @returns the current particle system
  56538. */
  56539. ParticleSystem.prototype.addDragGradient = function (gradient, factor, factor2) {
  56540. if (!this._dragGradients) {
  56541. this._dragGradients = [];
  56542. }
  56543. this._addFactorGradient(this._dragGradients, gradient, factor, factor2);
  56544. return this;
  56545. };
  56546. /**
  56547. * Remove a specific drag gradient
  56548. * @param gradient defines the gradient to remove
  56549. * @returns the current particle system
  56550. */
  56551. ParticleSystem.prototype.removeDragGradient = function (gradient) {
  56552. this._removeFactorGradient(this._dragGradients, gradient);
  56553. return this;
  56554. };
  56555. /**
  56556. * Adds a new emit rate gradient (please note that this will only work if you set the targetStopDuration property)
  56557. * @param gradient defines the gradient to use (between 0 and 1)
  56558. * @param factor defines the emit rate value to affect to the specified gradient
  56559. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56560. * @returns the current particle system
  56561. */
  56562. ParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  56563. if (!this._emitRateGradients) {
  56564. this._emitRateGradients = [];
  56565. }
  56566. this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2);
  56567. if (!this._currentEmitRateGradient) {
  56568. this._currentEmitRateGradient = this._emitRateGradients[0];
  56569. this._currentEmitRate1 = this._currentEmitRateGradient.getFactor();
  56570. this._currentEmitRate2 = this._currentEmitRate1;
  56571. }
  56572. if (this._emitRateGradients.length === 2) {
  56573. this._currentEmitRate2 = this._emitRateGradients[1].getFactor();
  56574. }
  56575. return this;
  56576. };
  56577. /**
  56578. * Remove a specific emit rate gradient
  56579. * @param gradient defines the gradient to remove
  56580. * @returns the current particle system
  56581. */
  56582. ParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  56583. this._removeFactorGradient(this._emitRateGradients, gradient);
  56584. return this;
  56585. };
  56586. /**
  56587. * Adds a new color gradient
  56588. * @param gradient defines the gradient to use (between 0 and 1)
  56589. * @param color defines the color to affect to the specified gradient
  56590. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  56591. */
  56592. ParticleSystem.prototype.addColorGradient = function (gradient, color, color2) {
  56593. if (!this._colorGradients) {
  56594. this._colorGradients = [];
  56595. }
  56596. var colorGradient = new BABYLON.ColorGradient();
  56597. colorGradient.gradient = gradient;
  56598. colorGradient.color1 = color;
  56599. colorGradient.color2 = color2;
  56600. this._colorGradients.push(colorGradient);
  56601. this._colorGradients.sort(function (a, b) {
  56602. if (a.gradient < b.gradient) {
  56603. return -1;
  56604. }
  56605. else if (a.gradient > b.gradient) {
  56606. return 1;
  56607. }
  56608. return 0;
  56609. });
  56610. return this;
  56611. };
  56612. /**
  56613. * Remove a specific color gradient
  56614. * @param gradient defines the gradient to remove
  56615. */
  56616. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  56617. if (!this._colorGradients) {
  56618. return this;
  56619. }
  56620. var index = 0;
  56621. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  56622. var colorGradient = _a[_i];
  56623. if (colorGradient.gradient === gradient) {
  56624. this._colorGradients.splice(index, 1);
  56625. break;
  56626. }
  56627. index++;
  56628. }
  56629. return this;
  56630. };
  56631. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  56632. u = Math.abs(u) * 0.5 + 0.5;
  56633. v = Math.abs(v) * 0.5 + 0.5;
  56634. var wrappedU = ((u * width) % width) | 0;
  56635. var wrappedV = ((v * height) % height) | 0;
  56636. var position = (wrappedU + wrappedV * width) * 4;
  56637. return pixels[position] / 255;
  56638. };
  56639. ParticleSystem.prototype._reset = function () {
  56640. this._resetEffect();
  56641. };
  56642. ParticleSystem.prototype._resetEffect = function () {
  56643. if (this._vertexBuffer) {
  56644. this._vertexBuffer.dispose();
  56645. this._vertexBuffer = null;
  56646. }
  56647. if (this._spriteBuffer) {
  56648. this._spriteBuffer.dispose();
  56649. this._spriteBuffer = null;
  56650. }
  56651. this._createVertexBuffers();
  56652. };
  56653. ParticleSystem.prototype._createVertexBuffers = function () {
  56654. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  56655. if (this._isAnimationSheetEnabled) {
  56656. this._vertexBufferSize += 1;
  56657. }
  56658. if (!this._isBillboardBased) {
  56659. this._vertexBufferSize += 3;
  56660. }
  56661. var engine = this._scene.getEngine();
  56662. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  56663. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  56664. var dataOffset = 0;
  56665. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  56666. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  56667. dataOffset += 3;
  56668. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  56669. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  56670. dataOffset += 4;
  56671. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  56672. this._vertexBuffers["angle"] = options;
  56673. dataOffset += 1;
  56674. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  56675. this._vertexBuffers["size"] = size;
  56676. dataOffset += 2;
  56677. if (this._isAnimationSheetEnabled) {
  56678. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  56679. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  56680. dataOffset += 1;
  56681. }
  56682. if (!this._isBillboardBased) {
  56683. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  56684. this._vertexBuffers["direction"] = directionBuffer;
  56685. dataOffset += 3;
  56686. }
  56687. var offsets;
  56688. if (this._useInstancing) {
  56689. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  56690. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  56691. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  56692. }
  56693. else {
  56694. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  56695. dataOffset += 2;
  56696. }
  56697. this._vertexBuffers["offset"] = offsets;
  56698. };
  56699. ParticleSystem.prototype._createIndexBuffer = function () {
  56700. if (this._useInstancing) {
  56701. return;
  56702. }
  56703. var indices = [];
  56704. var index = 0;
  56705. for (var count = 0; count < this._capacity; count++) {
  56706. indices.push(index);
  56707. indices.push(index + 1);
  56708. indices.push(index + 2);
  56709. indices.push(index);
  56710. indices.push(index + 2);
  56711. indices.push(index + 3);
  56712. index += 4;
  56713. }
  56714. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  56715. };
  56716. /**
  56717. * Gets the maximum number of particles active at the same time.
  56718. * @returns The max number of active particles.
  56719. */
  56720. ParticleSystem.prototype.getCapacity = function () {
  56721. return this._capacity;
  56722. };
  56723. /**
  56724. * Gets whether there are still active particles in the system.
  56725. * @returns True if it is alive, otherwise false.
  56726. */
  56727. ParticleSystem.prototype.isAlive = function () {
  56728. return this._alive;
  56729. };
  56730. /**
  56731. * Gets if the system has been started. (Note: this will still be true after stop is called)
  56732. * @returns True if it has been started, otherwise false.
  56733. */
  56734. ParticleSystem.prototype.isStarted = function () {
  56735. return this._started;
  56736. };
  56737. /**
  56738. * Starts the particle system and begins to emit
  56739. * @param delay defines the delay in milliseconds before starting the system (0 by default)
  56740. */
  56741. ParticleSystem.prototype.start = function (delay) {
  56742. var _this = this;
  56743. if (delay === void 0) { delay = 0; }
  56744. if (delay) {
  56745. setTimeout(function () {
  56746. _this.start(0);
  56747. }, delay);
  56748. return;
  56749. }
  56750. this._started = true;
  56751. this._stopped = false;
  56752. this._actualFrame = 0;
  56753. if (this.subEmitters && this.subEmitters.length != 0) {
  56754. this.activeSubSystems = new Array();
  56755. }
  56756. if (this.preWarmCycles) {
  56757. for (var index = 0; index < this.preWarmCycles; index++) {
  56758. this.animate(true);
  56759. }
  56760. }
  56761. };
  56762. /**
  56763. * Stops the particle system.
  56764. * @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.
  56765. */
  56766. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  56767. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  56768. this._stopped = true;
  56769. if (stopSubEmitters) {
  56770. this._stopSubEmitters();
  56771. }
  56772. };
  56773. // animation sheet
  56774. /**
  56775. * Remove all active particles
  56776. */
  56777. ParticleSystem.prototype.reset = function () {
  56778. this._stockParticles = [];
  56779. this._particles = [];
  56780. };
  56781. /**
  56782. * @hidden (for internal use only)
  56783. */
  56784. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  56785. var offset = index * this._vertexBufferSize;
  56786. this._vertexData[offset++] = particle.position.x;
  56787. this._vertexData[offset++] = particle.position.y;
  56788. this._vertexData[offset++] = particle.position.z;
  56789. this._vertexData[offset++] = particle.color.r;
  56790. this._vertexData[offset++] = particle.color.g;
  56791. this._vertexData[offset++] = particle.color.b;
  56792. this._vertexData[offset++] = particle.color.a;
  56793. this._vertexData[offset++] = particle.angle;
  56794. this._vertexData[offset++] = particle.scale.x * particle.size;
  56795. this._vertexData[offset++] = particle.scale.y * particle.size;
  56796. if (this._isAnimationSheetEnabled) {
  56797. this._vertexData[offset++] = particle.cellIndex;
  56798. }
  56799. if (!this._isBillboardBased) {
  56800. if (particle._initialDirection) {
  56801. this._vertexData[offset++] = particle._initialDirection.x;
  56802. this._vertexData[offset++] = particle._initialDirection.y;
  56803. this._vertexData[offset++] = particle._initialDirection.z;
  56804. }
  56805. else {
  56806. this._vertexData[offset++] = particle.direction.x;
  56807. this._vertexData[offset++] = particle.direction.y;
  56808. this._vertexData[offset++] = particle.direction.z;
  56809. }
  56810. }
  56811. if (!this._useInstancing) {
  56812. if (this._isAnimationSheetEnabled) {
  56813. if (offsetX === 0)
  56814. offsetX = this._epsilon;
  56815. else if (offsetX === 1)
  56816. offsetX = 1 - this._epsilon;
  56817. if (offsetY === 0)
  56818. offsetY = this._epsilon;
  56819. else if (offsetY === 1)
  56820. offsetY = 1 - this._epsilon;
  56821. }
  56822. this._vertexData[offset++] = offsetX;
  56823. this._vertexData[offset++] = offsetY;
  56824. }
  56825. };
  56826. ParticleSystem.prototype._stopSubEmitters = function () {
  56827. if (!this.activeSubSystems) {
  56828. return;
  56829. }
  56830. this.activeSubSystems.forEach(function (subSystem) {
  56831. subSystem.stop(true);
  56832. });
  56833. this.activeSubSystems = new Array();
  56834. };
  56835. ParticleSystem.prototype._removeFromRoot = function () {
  56836. if (!this._rootParticleSystem) {
  56837. return;
  56838. }
  56839. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  56840. if (index !== -1) {
  56841. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  56842. }
  56843. };
  56844. // End of sub system methods
  56845. ParticleSystem.prototype._update = function (newParticles) {
  56846. // Update current
  56847. this._alive = this._particles.length > 0;
  56848. if (this.emitter.position) {
  56849. var emitterMesh = this.emitter;
  56850. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  56851. }
  56852. else {
  56853. var emitterPosition = this.emitter;
  56854. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56855. }
  56856. this.updateFunction(this._particles);
  56857. // Add new ones
  56858. var particle;
  56859. var _loop_2 = function () {
  56860. if (this_1._particles.length === this_1._capacity) {
  56861. return "break";
  56862. }
  56863. particle = this_1._createParticle();
  56864. this_1._particles.push(particle);
  56865. // Emitter
  56866. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  56867. if (this_1.startPositionFunction) {
  56868. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  56869. }
  56870. else {
  56871. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  56872. }
  56873. if (this_1.startDirectionFunction) {
  56874. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  56875. }
  56876. else {
  56877. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  56878. }
  56879. if (emitPower === 0) {
  56880. if (!particle._initialDirection) {
  56881. particle._initialDirection = particle.direction.clone();
  56882. }
  56883. else {
  56884. particle._initialDirection.copyFrom(particle.direction);
  56885. }
  56886. }
  56887. else {
  56888. particle._initialDirection = null;
  56889. }
  56890. particle.direction.scaleInPlace(emitPower);
  56891. // Life time
  56892. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  56893. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  56894. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  56895. var factorGradient1 = currentGradient;
  56896. var factorGradient2 = nextGradient;
  56897. var lifeTime1 = factorGradient1.getFactor();
  56898. var lifeTime2 = factorGradient2.getFactor();
  56899. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  56900. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  56901. });
  56902. }
  56903. else {
  56904. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  56905. }
  56906. // Size
  56907. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  56908. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  56909. }
  56910. else {
  56911. particle._currentSizeGradient = this_1._sizeGradients[0];
  56912. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  56913. particle.size = particle._currentSize1;
  56914. if (this_1._sizeGradients.length > 1) {
  56915. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  56916. }
  56917. else {
  56918. particle._currentSize2 = particle._currentSize1;
  56919. }
  56920. }
  56921. // Size and scale
  56922. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  56923. // Angle
  56924. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  56925. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  56926. }
  56927. else {
  56928. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  56929. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  56930. particle._currentAngularSpeed1 = particle.angularSpeed;
  56931. if (this_1._angularSpeedGradients.length > 1) {
  56932. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  56933. }
  56934. else {
  56935. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  56936. }
  56937. }
  56938. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  56939. // Velocity
  56940. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  56941. particle._currentVelocityGradient = this_1._velocityGradients[0];
  56942. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  56943. if (this_1._velocityGradients.length > 1) {
  56944. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  56945. }
  56946. else {
  56947. particle._currentVelocity2 = particle._currentVelocity1;
  56948. }
  56949. }
  56950. // Limit velocity
  56951. if (this_1._limitVelocityGradients && this_1._limitVelocityGradients.length > 0) {
  56952. particle._currentLimitVelocityGradient = this_1._limitVelocityGradients[0];
  56953. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  56954. if (this_1._limitVelocityGradients.length > 1) {
  56955. particle._currentLimitVelocity2 = this_1._limitVelocityGradients[1].getFactor();
  56956. }
  56957. else {
  56958. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  56959. }
  56960. }
  56961. // Drag
  56962. if (this_1._dragGradients && this_1._dragGradients.length > 0) {
  56963. particle._currentDragGradient = this_1._dragGradients[0];
  56964. particle._currentDrag1 = particle._currentDragGradient.getFactor();
  56965. if (this_1._dragGradients.length > 1) {
  56966. particle._currentDrag2 = this_1._dragGradients[1].getFactor();
  56967. }
  56968. else {
  56969. particle._currentDrag2 = particle._currentDrag1;
  56970. }
  56971. }
  56972. // Color
  56973. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  56974. step = BABYLON.Scalar.RandomRange(0, 1.0);
  56975. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  56976. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  56977. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  56978. }
  56979. else {
  56980. particle._currentColorGradient = this_1._colorGradients[0];
  56981. particle._currentColorGradient.getColorToRef(particle.color);
  56982. particle._currentColor1.copyFrom(particle.color);
  56983. if (this_1._colorGradients.length > 1) {
  56984. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  56985. }
  56986. else {
  56987. particle._currentColor2.copyFrom(particle.color);
  56988. }
  56989. }
  56990. // Sheet
  56991. if (this_1._isAnimationSheetEnabled) {
  56992. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  56993. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  56994. }
  56995. };
  56996. var this_1 = this, step;
  56997. for (var index = 0; index < newParticles; index++) {
  56998. var state_1 = _loop_2();
  56999. if (state_1 === "break")
  57000. break;
  57001. }
  57002. };
  57003. /** @hidden */
  57004. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased) {
  57005. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  57006. if (isBillboardBased === void 0) { isBillboardBased = false; }
  57007. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  57008. if (isAnimationSheetEnabled) {
  57009. attributeNamesOrOptions.push("cellIndex");
  57010. }
  57011. if (!isBillboardBased) {
  57012. attributeNamesOrOptions.push("direction");
  57013. }
  57014. return attributeNamesOrOptions;
  57015. };
  57016. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  57017. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  57018. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "textureMask", "translationPivot", "eyePosition"];
  57019. if (isAnimationSheetEnabled) {
  57020. effectCreationOption.push("particlesInfos");
  57021. }
  57022. return effectCreationOption;
  57023. };
  57024. ParticleSystem.prototype._getEffect = function () {
  57025. if (this._customEffect) {
  57026. return this._customEffect;
  57027. }
  57028. ;
  57029. var defines = [];
  57030. if (this._scene.clipPlane) {
  57031. defines.push("#define CLIPPLANE");
  57032. }
  57033. if (this._scene.clipPlane2) {
  57034. defines.push("#define CLIPPLANE2");
  57035. }
  57036. if (this._scene.clipPlane3) {
  57037. defines.push("#define CLIPPLANE3");
  57038. }
  57039. if (this._scene.clipPlane4) {
  57040. defines.push("#define CLIPPLANE4");
  57041. }
  57042. if (this._isAnimationSheetEnabled) {
  57043. defines.push("#define ANIMATESHEET");
  57044. }
  57045. if (this._isBillboardBased) {
  57046. defines.push("#define BILLBOARD");
  57047. switch (this.billboardMode) {
  57048. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  57049. defines.push("#define BILLBOARDY");
  57050. break;
  57051. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  57052. default:
  57053. break;
  57054. }
  57055. }
  57056. if (this._imageProcessingConfiguration) {
  57057. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  57058. defines.push(this._imageProcessingConfigurationDefines.toString());
  57059. }
  57060. // Effect
  57061. var join = defines.join("\n");
  57062. if (this._cachedDefines !== join) {
  57063. this._cachedDefines = join;
  57064. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased);
  57065. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  57066. var samplers = ["diffuseSampler"];
  57067. if (BABYLON.ImageProcessingConfiguration) {
  57068. BABYLON.ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
  57069. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  57070. }
  57071. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  57072. }
  57073. return this._effect;
  57074. };
  57075. /**
  57076. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57077. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  57078. */
  57079. ParticleSystem.prototype.animate = function (preWarmOnly) {
  57080. var _this = this;
  57081. if (preWarmOnly === void 0) { preWarmOnly = false; }
  57082. if (!this._started)
  57083. return;
  57084. if (!preWarmOnly) {
  57085. var effect = this._getEffect();
  57086. // Check
  57087. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  57088. return;
  57089. if (this._currentRenderId === this._scene.getRenderId()) {
  57090. return;
  57091. }
  57092. this._currentRenderId = this._scene.getRenderId();
  57093. }
  57094. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  57095. // Determine the number of particles we need to create
  57096. var newParticles;
  57097. if (this.manualEmitCount > -1) {
  57098. newParticles = this.manualEmitCount;
  57099. this._newPartsExcess = 0;
  57100. this.manualEmitCount = 0;
  57101. }
  57102. else {
  57103. var rate_1 = this.emitRate;
  57104. if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {
  57105. var ratio = this._actualFrame / this.targetStopDuration;
  57106. BABYLON.Tools.GetCurrentGradient(ratio, this._emitRateGradients, function (currentGradient, nextGradient, scale) {
  57107. if (currentGradient !== _this._currentEmitRateGradient) {
  57108. _this._currentEmitRate1 = _this._currentEmitRate2;
  57109. _this._currentEmitRate2 = nextGradient.getFactor();
  57110. _this._currentEmitRateGradient = currentGradient;
  57111. }
  57112. rate_1 = BABYLON.Scalar.Lerp(_this._currentEmitRate1, _this._currentEmitRate2, scale);
  57113. });
  57114. }
  57115. newParticles = ((rate_1 * this._scaledUpdateSpeed) >> 0);
  57116. this._newPartsExcess += rate_1 * this._scaledUpdateSpeed - newParticles;
  57117. }
  57118. if (this._newPartsExcess > 1.0) {
  57119. newParticles += this._newPartsExcess >> 0;
  57120. this._newPartsExcess -= this._newPartsExcess >> 0;
  57121. }
  57122. this._alive = false;
  57123. if (!this._stopped) {
  57124. this._actualFrame += this._scaledUpdateSpeed;
  57125. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  57126. this.stop();
  57127. }
  57128. else {
  57129. newParticles = 0;
  57130. }
  57131. this._update(newParticles);
  57132. // Stopped?
  57133. if (this._stopped) {
  57134. if (!this._alive) {
  57135. this._started = false;
  57136. if (this.onAnimationEnd) {
  57137. this.onAnimationEnd();
  57138. }
  57139. if (this.disposeOnStop) {
  57140. this._scene._toBeDisposed.push(this);
  57141. }
  57142. }
  57143. }
  57144. if (!preWarmOnly) {
  57145. // Update VBO
  57146. var offset = 0;
  57147. for (var index = 0; index < this._particles.length; index++) {
  57148. var particle = this._particles[index];
  57149. this._appendParticleVertices(offset, particle);
  57150. offset += this._useInstancing ? 1 : 4;
  57151. }
  57152. if (this._vertexBuffer) {
  57153. this._vertexBuffer.update(this._vertexData);
  57154. }
  57155. }
  57156. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  57157. this.stop();
  57158. }
  57159. };
  57160. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  57161. this._appendParticleVertex(offset++, particle, 0, 0);
  57162. if (!this._useInstancing) {
  57163. this._appendParticleVertex(offset++, particle, 1, 0);
  57164. this._appendParticleVertex(offset++, particle, 1, 1);
  57165. this._appendParticleVertex(offset++, particle, 0, 1);
  57166. }
  57167. };
  57168. /**
  57169. * Rebuilds the particle system.
  57170. */
  57171. ParticleSystem.prototype.rebuild = function () {
  57172. this._createIndexBuffer();
  57173. if (this._vertexBuffer) {
  57174. this._vertexBuffer._rebuild();
  57175. }
  57176. };
  57177. /**
  57178. * Is this system ready to be used/rendered
  57179. * @return true if the system is ready
  57180. */
  57181. ParticleSystem.prototype.isReady = function () {
  57182. var effect = this._getEffect();
  57183. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57184. return false;
  57185. }
  57186. return true;
  57187. };
  57188. /**
  57189. * Renders the particle system in its current state.
  57190. * @returns the current number of particles
  57191. */
  57192. ParticleSystem.prototype.render = function () {
  57193. var effect = this._getEffect();
  57194. // Check
  57195. if (!this.isReady() || !this._particles.length) {
  57196. return 0;
  57197. }
  57198. var engine = this._scene.getEngine();
  57199. // Render
  57200. engine.enableEffect(effect);
  57201. engine.setState(false);
  57202. var viewMatrix = this._scene.getViewMatrix();
  57203. effect.setTexture("diffuseSampler", this.particleTexture);
  57204. effect.setMatrix("view", viewMatrix);
  57205. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  57206. if (this._isAnimationSheetEnabled && this.particleTexture) {
  57207. var baseSize = this.particleTexture.getBaseSize();
  57208. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  57209. }
  57210. effect.setVector2("translationPivot", this.translationPivot);
  57211. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  57212. if (this._isBillboardBased) {
  57213. var camera = this._scene.activeCamera;
  57214. effect.setVector3("eyePosition", camera.globalPosition);
  57215. }
  57216. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  57217. var invView = viewMatrix.clone();
  57218. invView.invert();
  57219. effect.setMatrix("invView", invView);
  57220. BABYLON.MaterialHelper.BindClipPlane(effect, this._scene);
  57221. }
  57222. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  57223. // image processing
  57224. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  57225. this._imageProcessingConfiguration.bind(effect);
  57226. }
  57227. // Draw order
  57228. switch (this.blendMode) {
  57229. case ParticleSystem.BLENDMODE_ADD:
  57230. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  57231. break;
  57232. case ParticleSystem.BLENDMODE_ONEONE:
  57233. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57234. break;
  57235. case ParticleSystem.BLENDMODE_STANDARD:
  57236. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57237. break;
  57238. case ParticleSystem.BLENDMODE_MULTIPLY:
  57239. engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  57240. break;
  57241. }
  57242. if (this.forceDepthWrite) {
  57243. engine.setDepthWrite(true);
  57244. }
  57245. if (this._useInstancing) {
  57246. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  57247. engine.unbindInstanceAttributes();
  57248. }
  57249. else {
  57250. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  57251. }
  57252. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57253. return this._particles.length;
  57254. };
  57255. /**
  57256. * Disposes the particle system and free the associated resources
  57257. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57258. */
  57259. ParticleSystem.prototype.dispose = function (disposeTexture) {
  57260. if (disposeTexture === void 0) { disposeTexture = true; }
  57261. if (this._vertexBuffer) {
  57262. this._vertexBuffer.dispose();
  57263. this._vertexBuffer = null;
  57264. }
  57265. if (this._spriteBuffer) {
  57266. this._spriteBuffer.dispose();
  57267. this._spriteBuffer = null;
  57268. }
  57269. if (this._indexBuffer) {
  57270. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  57271. this._indexBuffer = null;
  57272. }
  57273. if (disposeTexture && this.particleTexture) {
  57274. this.particleTexture.dispose();
  57275. this.particleTexture = null;
  57276. }
  57277. if (disposeTexture && this.noiseTexture) {
  57278. this.noiseTexture.dispose();
  57279. this.noiseTexture = null;
  57280. }
  57281. this._removeFromRoot();
  57282. // Remove from scene
  57283. var index = this._scene.particleSystems.indexOf(this);
  57284. if (index > -1) {
  57285. this._scene.particleSystems.splice(index, 1);
  57286. }
  57287. // Callback
  57288. this.onDisposeObservable.notifyObservers(this);
  57289. this.onDisposeObservable.clear();
  57290. };
  57291. // Clone
  57292. /**
  57293. * Clones the particle system.
  57294. * @param name The name of the cloned object
  57295. * @param newEmitter The new emitter to use
  57296. * @returns the cloned particle system
  57297. */
  57298. ParticleSystem.prototype.clone = function (name, newEmitter) {
  57299. var custom = null;
  57300. var program = null;
  57301. if (this.customShader != null) {
  57302. program = this.customShader;
  57303. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  57304. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  57305. }
  57306. else if (this._customEffect) {
  57307. custom = this._customEffect;
  57308. }
  57309. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  57310. result.customShader = program;
  57311. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  57312. if (newEmitter === undefined) {
  57313. newEmitter = this.emitter;
  57314. }
  57315. result.emitter = newEmitter;
  57316. if (this.particleTexture) {
  57317. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57318. }
  57319. if (!this.preventAutoStart) {
  57320. result.start();
  57321. }
  57322. return result;
  57323. };
  57324. /**
  57325. * Serializes the particle system to a JSON object.
  57326. * @returns the JSON object
  57327. */
  57328. ParticleSystem.prototype.serialize = function () {
  57329. var serializationObject = {};
  57330. ParticleSystem._Serialize(serializationObject, this);
  57331. serializationObject.textureMask = this.textureMask.asArray();
  57332. serializationObject.customShader = this.customShader;
  57333. serializationObject.preventAutoStart = this.preventAutoStart;
  57334. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  57335. return serializationObject;
  57336. };
  57337. /** @hidden */
  57338. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  57339. serializationObject.name = particleSystem.name;
  57340. serializationObject.id = particleSystem.id;
  57341. serializationObject.capacity = particleSystem.getCapacity();
  57342. // Emitter
  57343. if (particleSystem.emitter.position) {
  57344. var emitterMesh = particleSystem.emitter;
  57345. serializationObject.emitterId = emitterMesh.id;
  57346. }
  57347. else {
  57348. var emitterPosition = particleSystem.emitter;
  57349. serializationObject.emitter = emitterPosition.asArray();
  57350. }
  57351. // Emitter
  57352. if (particleSystem.particleEmitterType) {
  57353. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  57354. }
  57355. if (particleSystem.particleTexture) {
  57356. serializationObject.textureName = particleSystem.particleTexture.name;
  57357. }
  57358. // Animations
  57359. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  57360. // Particle system
  57361. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  57362. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  57363. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  57364. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  57365. serializationObject.minSize = particleSystem.minSize;
  57366. serializationObject.maxSize = particleSystem.maxSize;
  57367. serializationObject.minScaleX = particleSystem.minScaleX;
  57368. serializationObject.maxScaleX = particleSystem.maxScaleX;
  57369. serializationObject.minScaleY = particleSystem.minScaleY;
  57370. serializationObject.maxScaleY = particleSystem.maxScaleY;
  57371. serializationObject.minEmitPower = particleSystem.minEmitPower;
  57372. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  57373. serializationObject.minLifeTime = particleSystem.minLifeTime;
  57374. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  57375. serializationObject.emitRate = particleSystem.emitRate;
  57376. serializationObject.gravity = particleSystem.gravity.asArray();
  57377. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  57378. serializationObject.color1 = particleSystem.color1.asArray();
  57379. serializationObject.color2 = particleSystem.color2.asArray();
  57380. serializationObject.colorDead = particleSystem.colorDead.asArray();
  57381. serializationObject.updateSpeed = particleSystem.updateSpeed;
  57382. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  57383. serializationObject.blendMode = particleSystem.blendMode;
  57384. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  57385. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  57386. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  57387. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  57388. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  57389. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  57390. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  57391. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  57392. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  57393. var colorGradients = particleSystem.getColorGradients();
  57394. if (colorGradients) {
  57395. serializationObject.colorGradients = [];
  57396. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  57397. var colorGradient = colorGradients_1[_i];
  57398. var serializedGradient = {
  57399. gradient: colorGradient.gradient,
  57400. color1: colorGradient.color1.asArray()
  57401. };
  57402. if (colorGradient.color2) {
  57403. serializedGradient.color2 = colorGradient.color2.asArray();
  57404. }
  57405. serializationObject.colorGradients.push(serializedGradient);
  57406. }
  57407. }
  57408. var sizeGradients = particleSystem.getSizeGradients();
  57409. if (sizeGradients) {
  57410. serializationObject.sizeGradients = [];
  57411. for (var _a = 0, sizeGradients_1 = sizeGradients; _a < sizeGradients_1.length; _a++) {
  57412. var sizeGradient = sizeGradients_1[_a];
  57413. var serializedGradient = {
  57414. gradient: sizeGradient.gradient,
  57415. factor1: sizeGradient.factor1
  57416. };
  57417. if (sizeGradient.factor2 !== undefined) {
  57418. serializedGradient.factor2 = sizeGradient.factor2;
  57419. }
  57420. serializationObject.sizeGradients.push(serializedGradient);
  57421. }
  57422. }
  57423. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  57424. if (angularSpeedGradients) {
  57425. serializationObject.angularSpeedGradients = [];
  57426. for (var _b = 0, angularSpeedGradients_1 = angularSpeedGradients; _b < angularSpeedGradients_1.length; _b++) {
  57427. var angularSpeedGradient = angularSpeedGradients_1[_b];
  57428. var serializedGradient = {
  57429. gradient: angularSpeedGradient.gradient,
  57430. factor1: angularSpeedGradient.factor1
  57431. };
  57432. if (angularSpeedGradient.factor2 !== undefined) {
  57433. serializedGradient.factor2 = angularSpeedGradient.factor2;
  57434. }
  57435. serializationObject.angularSpeedGradients.push(serializedGradient);
  57436. }
  57437. }
  57438. var velocityGradients = particleSystem.getVelocityGradients();
  57439. if (velocityGradients) {
  57440. serializationObject.velocityGradients = [];
  57441. for (var _c = 0, velocityGradients_1 = velocityGradients; _c < velocityGradients_1.length; _c++) {
  57442. var velocityGradient = velocityGradients_1[_c];
  57443. var serializedGradient = {
  57444. gradient: velocityGradient.gradient,
  57445. factor1: velocityGradient.factor1
  57446. };
  57447. if (velocityGradient.factor2 !== undefined) {
  57448. serializedGradient.factor2 = velocityGradient.factor2;
  57449. }
  57450. serializationObject.velocityGradients.push(serializedGradient);
  57451. }
  57452. }
  57453. var dragGradients = particleSystem.getDragGradients();
  57454. if (dragGradients) {
  57455. serializationObject.dragyGradients = [];
  57456. for (var _d = 0, dragGradients_1 = dragGradients; _d < dragGradients_1.length; _d++) {
  57457. var dragGradient = dragGradients_1[_d];
  57458. var serializedGradient = {
  57459. gradient: dragGradient.gradient,
  57460. factor1: dragGradient.factor1
  57461. };
  57462. if (dragGradient.factor2 !== undefined) {
  57463. serializedGradient.factor2 = dragGradient.factor2;
  57464. }
  57465. serializationObject.dragGradients.push(serializedGradient);
  57466. }
  57467. }
  57468. var emitRateGradients = particleSystem.getEmitRateGradients();
  57469. if (emitRateGradients) {
  57470. serializationObject.emitRateGradients = [];
  57471. for (var _e = 0, emitRateGradients_1 = emitRateGradients; _e < emitRateGradients_1.length; _e++) {
  57472. var emitRateGradient = emitRateGradients_1[_e];
  57473. var serializedGradient = {
  57474. gradient: emitRateGradient.gradient,
  57475. factor1: emitRateGradient.factor1
  57476. };
  57477. if (emitRateGradient.factor2 !== undefined) {
  57478. serializedGradient.factor2 = emitRateGradient.factor2;
  57479. }
  57480. serializationObject.emitRateGradients.push(serializedGradient);
  57481. }
  57482. }
  57483. var limitVelocityGradients = particleSystem.getLimitVelocityGradients();
  57484. if (limitVelocityGradients) {
  57485. serializationObject.limitVelocityGradients = [];
  57486. for (var _f = 0, limitVelocityGradients_1 = limitVelocityGradients; _f < limitVelocityGradients_1.length; _f++) {
  57487. var limitVelocityGradient = limitVelocityGradients_1[_f];
  57488. var serializedGradient = {
  57489. gradient: limitVelocityGradient.gradient,
  57490. factor1: limitVelocityGradient.factor1
  57491. };
  57492. if (limitVelocityGradient.factor2 !== undefined) {
  57493. serializedGradient.factor2 = limitVelocityGradient.factor2;
  57494. }
  57495. serializationObject.limitVelocityGradients.push(serializedGradient);
  57496. }
  57497. serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
  57498. }
  57499. if (particleSystem.noiseTexture && particleSystem.noiseTexture instanceof BABYLON.ProceduralTexture) {
  57500. var noiseTexture = particleSystem.noiseTexture;
  57501. serializationObject.noiseTexture = noiseTexture.serialize();
  57502. }
  57503. };
  57504. /** @hidden */
  57505. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  57506. // Texture
  57507. if (parsedParticleSystem.textureName) {
  57508. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57509. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57510. }
  57511. // Emitter
  57512. if (parsedParticleSystem.emitterId === undefined) {
  57513. particleSystem.emitter = BABYLON.Vector3.Zero();
  57514. }
  57515. else if (parsedParticleSystem.emitterId) {
  57516. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57517. }
  57518. else {
  57519. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57520. }
  57521. // Misc.
  57522. if (parsedParticleSystem.renderingGroupId !== undefined) {
  57523. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  57524. }
  57525. if (parsedParticleSystem.isBillboardBased !== undefined) {
  57526. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  57527. }
  57528. // Animations
  57529. if (parsedParticleSystem.animations) {
  57530. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57531. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57532. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57533. }
  57534. }
  57535. if (parsedParticleSystem.autoAnimate) {
  57536. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  57537. }
  57538. // Particle system
  57539. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  57540. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  57541. particleSystem.minSize = parsedParticleSystem.minSize;
  57542. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57543. if (parsedParticleSystem.minScaleX) {
  57544. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  57545. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  57546. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  57547. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  57548. }
  57549. if (parsedParticleSystem.preWarmCycles !== undefined) {
  57550. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  57551. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  57552. }
  57553. if (parsedParticleSystem.minInitialRotation !== undefined) {
  57554. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  57555. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  57556. }
  57557. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57558. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57559. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57560. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57561. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57562. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57563. if (parsedParticleSystem.noiseStrength) {
  57564. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  57565. }
  57566. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57567. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57568. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57569. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57570. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57571. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57572. if (parsedParticleSystem.colorGradients) {
  57573. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  57574. var colorGradient = _a[_i];
  57575. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  57576. }
  57577. }
  57578. if (parsedParticleSystem.sizeGradients) {
  57579. for (var _b = 0, _c = parsedParticleSystem.sizeGradients; _b < _c.length; _b++) {
  57580. var sizeGradient = _c[_b];
  57581. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  57582. }
  57583. }
  57584. if (parsedParticleSystem.angularSpeedGradients) {
  57585. for (var _d = 0, _e = parsedParticleSystem.angularSpeedGradients; _d < _e.length; _d++) {
  57586. var angularSpeedGradient = _e[_d];
  57587. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  57588. }
  57589. }
  57590. if (parsedParticleSystem.velocityGradients) {
  57591. for (var _f = 0, _g = parsedParticleSystem.velocityGradients; _f < _g.length; _f++) {
  57592. var velocityGradient = _g[_f];
  57593. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  57594. }
  57595. }
  57596. if (parsedParticleSystem.dragGradients) {
  57597. for (var _h = 0, _j = parsedParticleSystem.dragGradients; _h < _j.length; _h++) {
  57598. var dragGradient = _j[_h];
  57599. particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== undefined ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2);
  57600. }
  57601. }
  57602. if (parsedParticleSystem.emitRateGradients) {
  57603. for (var _k = 0, _l = parsedParticleSystem.emitRateGradients; _k < _l.length; _k++) {
  57604. var emitRateGradient = _l[_k];
  57605. particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== undefined ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2);
  57606. }
  57607. }
  57608. if (parsedParticleSystem.limitVelocityGradients) {
  57609. for (var _m = 0, _o = parsedParticleSystem.limitVelocityGradients; _m < _o.length; _m++) {
  57610. var limitVelocityGradient = _o[_m];
  57611. particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
  57612. }
  57613. particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
  57614. }
  57615. if (parsedParticleSystem.noiseTexture) {
  57616. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  57617. }
  57618. // Emitter
  57619. var emitterType;
  57620. if (parsedParticleSystem.particleEmitterType) {
  57621. switch (parsedParticleSystem.particleEmitterType.type) {
  57622. case "SphereParticleEmitter":
  57623. emitterType = new BABYLON.SphereParticleEmitter();
  57624. break;
  57625. case "SphereDirectedParticleEmitter":
  57626. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  57627. break;
  57628. case "ConeEmitter":
  57629. case "ConeParticleEmitter":
  57630. emitterType = new BABYLON.ConeParticleEmitter();
  57631. break;
  57632. case "BoxEmitter":
  57633. case "BoxParticleEmitter":
  57634. default:
  57635. emitterType = new BABYLON.BoxParticleEmitter();
  57636. break;
  57637. }
  57638. emitterType.parse(parsedParticleSystem.particleEmitterType);
  57639. }
  57640. else {
  57641. emitterType = new BABYLON.BoxParticleEmitter();
  57642. emitterType.parse(parsedParticleSystem);
  57643. }
  57644. particleSystem.particleEmitterType = emitterType;
  57645. // Animation sheet
  57646. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  57647. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  57648. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  57649. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  57650. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  57651. };
  57652. /**
  57653. * Parses a JSON object to create a particle system.
  57654. * @param parsedParticleSystem The JSON object to parse
  57655. * @param scene The scene to create the particle system in
  57656. * @param rootUrl The root url to use to load external dependencies like texture
  57657. * @returns the Parsed particle system
  57658. */
  57659. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57660. var name = parsedParticleSystem.name;
  57661. var custom = null;
  57662. var program = null;
  57663. if (parsedParticleSystem.customShader) {
  57664. program = parsedParticleSystem.customShader;
  57665. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  57666. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  57667. }
  57668. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  57669. particleSystem.customShader = program;
  57670. if (parsedParticleSystem.id) {
  57671. particleSystem.id = parsedParticleSystem.id;
  57672. }
  57673. // Auto start
  57674. if (parsedParticleSystem.preventAutoStart) {
  57675. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  57676. }
  57677. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  57678. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  57679. if (!particleSystem.preventAutoStart) {
  57680. particleSystem.start();
  57681. }
  57682. return particleSystem;
  57683. };
  57684. return ParticleSystem;
  57685. }(BABYLON.BaseParticleSystem));
  57686. BABYLON.ParticleSystem = ParticleSystem;
  57687. })(BABYLON || (BABYLON = {}));
  57688. //# sourceMappingURL=babylon.particleSystem.js.map
  57689. var BABYLON;
  57690. (function (BABYLON) {
  57691. /**
  57692. * Particle emitter emitting particles from the inside of a box.
  57693. * It emits the particles randomly between 2 given directions.
  57694. */
  57695. var BoxParticleEmitter = /** @class */ (function () {
  57696. /**
  57697. * Creates a new instance BoxParticleEmitter
  57698. */
  57699. function BoxParticleEmitter() {
  57700. /**
  57701. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57702. */
  57703. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  57704. /**
  57705. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57706. */
  57707. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  57708. /**
  57709. * 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.
  57710. */
  57711. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  57712. /**
  57713. * 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.
  57714. */
  57715. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  57716. }
  57717. /**
  57718. * Called by the particle System when the direction is computed for the created particle.
  57719. * @param worldMatrix is the world matrix of the particle system
  57720. * @param directionToUpdate is the direction vector to update with the result
  57721. * @param particle is the particle we are computed the direction for
  57722. */
  57723. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57724. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57725. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57726. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57727. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  57728. };
  57729. /**
  57730. * Called by the particle System when the position is computed for the created particle.
  57731. * @param worldMatrix is the world matrix of the particle system
  57732. * @param positionToUpdate is the position vector to update with the result
  57733. * @param particle is the particle we are computed the position for
  57734. */
  57735. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57736. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  57737. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  57738. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  57739. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57740. };
  57741. /**
  57742. * Clones the current emitter and returns a copy of it
  57743. * @returns the new emitter
  57744. */
  57745. BoxParticleEmitter.prototype.clone = function () {
  57746. var newOne = new BoxParticleEmitter();
  57747. BABYLON.Tools.DeepCopy(this, newOne);
  57748. return newOne;
  57749. };
  57750. /**
  57751. * Called by the GPUParticleSystem to setup the update shader
  57752. * @param effect defines the update shader
  57753. */
  57754. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  57755. effect.setVector3("direction1", this.direction1);
  57756. effect.setVector3("direction2", this.direction2);
  57757. effect.setVector3("minEmitBox", this.minEmitBox);
  57758. effect.setVector3("maxEmitBox", this.maxEmitBox);
  57759. };
  57760. /**
  57761. * Returns a string to use to update the GPU particles update shader
  57762. * @returns a string containng the defines string
  57763. */
  57764. BoxParticleEmitter.prototype.getEffectDefines = function () {
  57765. return "#define BOXEMITTER";
  57766. };
  57767. /**
  57768. * Returns the string "BoxParticleEmitter"
  57769. * @returns a string containing the class name
  57770. */
  57771. BoxParticleEmitter.prototype.getClassName = function () {
  57772. return "BoxParticleEmitter";
  57773. };
  57774. /**
  57775. * Serializes the particle system to a JSON object.
  57776. * @returns the JSON object
  57777. */
  57778. BoxParticleEmitter.prototype.serialize = function () {
  57779. var serializationObject = {};
  57780. serializationObject.type = this.getClassName();
  57781. serializationObject.direction1 = this.direction1.asArray();
  57782. serializationObject.direction2 = this.direction2.asArray();
  57783. serializationObject.minEmitBox = this.minEmitBox.asArray();
  57784. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  57785. return serializationObject;
  57786. };
  57787. /**
  57788. * Parse properties from a JSON object
  57789. * @param serializationObject defines the JSON object
  57790. */
  57791. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  57792. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  57793. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  57794. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  57795. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  57796. };
  57797. return BoxParticleEmitter;
  57798. }());
  57799. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  57800. })(BABYLON || (BABYLON = {}));
  57801. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  57802. var BABYLON;
  57803. (function (BABYLON) {
  57804. /**
  57805. * Particle emitter emitting particles from the inside of a cylinder.
  57806. * It emits the particles alongside the cylinder radius. The emission direction might be randomized.
  57807. */
  57808. var CylinderParticleEmitter = /** @class */ (function () {
  57809. /**
  57810. * Creates a new instance CylinderParticleEmitter
  57811. * @param radius the radius of the emission cylinder (1 by default)
  57812. * @param height the height of the emission cylinder (1 by default)
  57813. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  57814. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57815. */
  57816. function CylinderParticleEmitter(
  57817. /**
  57818. * The radius of the emission cylinder.
  57819. */
  57820. radius,
  57821. /**
  57822. * The height of the emission cylinder.
  57823. */
  57824. height,
  57825. /**
  57826. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  57827. */
  57828. radiusRange,
  57829. /**
  57830. * How much to randomize the particle direction [0-1].
  57831. */
  57832. directionRandomizer) {
  57833. if (radius === void 0) { radius = 1; }
  57834. if (height === void 0) { height = 1; }
  57835. if (radiusRange === void 0) { radiusRange = 1; }
  57836. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57837. this.radius = radius;
  57838. this.height = height;
  57839. this.radiusRange = radiusRange;
  57840. this.directionRandomizer = directionRandomizer;
  57841. }
  57842. /**
  57843. * Called by the particle System when the direction is computed for the created particle.
  57844. * @param worldMatrix is the world matrix of the particle system
  57845. * @param directionToUpdate is the direction vector to update with the result
  57846. * @param particle is the particle we are computed the direction for
  57847. */
  57848. CylinderParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57849. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57850. var randY = BABYLON.Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2);
  57851. var angle = Math.atan2(direction.x, direction.z);
  57852. angle += BABYLON.Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer;
  57853. direction.y = randY; // set direction y to rand y to mirror normal of cylinder surface
  57854. direction.x = Math.sin(angle);
  57855. direction.z = Math.cos(angle);
  57856. direction.normalize();
  57857. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  57858. };
  57859. /**
  57860. * Called by the particle System when the position is computed for the created particle.
  57861. * @param worldMatrix is the world matrix of the particle system
  57862. * @param positionToUpdate is the position vector to update with the result
  57863. * @param particle is the particle we are computed the position for
  57864. */
  57865. CylinderParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57866. var yPos = BABYLON.Scalar.RandomRange(-this.height / 2, this.height / 2);
  57867. var angle = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  57868. // Pick a properly distributed point within the circle https://programming.guide/random-point-within-circle.html
  57869. var radiusDistribution = BABYLON.Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1);
  57870. var positionRadius = Math.sqrt(radiusDistribution) * this.radius;
  57871. var xPos = positionRadius * Math.cos(angle);
  57872. var zPos = positionRadius * Math.sin(angle);
  57873. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate);
  57874. };
  57875. /**
  57876. * Clones the current emitter and returns a copy of it
  57877. * @returns the new emitter
  57878. */
  57879. CylinderParticleEmitter.prototype.clone = function () {
  57880. var newOne = new CylinderParticleEmitter(this.radius, this.directionRandomizer);
  57881. BABYLON.Tools.DeepCopy(this, newOne);
  57882. return newOne;
  57883. };
  57884. /**
  57885. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57886. * @param effect defines the update shader
  57887. */
  57888. CylinderParticleEmitter.prototype.applyToShader = function (effect) {
  57889. effect.setFloat("radius", this.radius);
  57890. effect.setFloat("height", this.height);
  57891. effect.setFloat("radiusRange", this.radiusRange);
  57892. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57893. };
  57894. /**
  57895. * Returns a string to use to update the GPU particles update shader
  57896. * @returns a string containng the defines string
  57897. */
  57898. CylinderParticleEmitter.prototype.getEffectDefines = function () {
  57899. return "#define CYLINDEREMITTER";
  57900. };
  57901. /**
  57902. * Returns the string "CylinderParticleEmitter"
  57903. * @returns a string containing the class name
  57904. */
  57905. CylinderParticleEmitter.prototype.getClassName = function () {
  57906. return "CylinderParticleEmitter";
  57907. };
  57908. /**
  57909. * Serializes the particle system to a JSON object.
  57910. * @returns the JSON object
  57911. */
  57912. CylinderParticleEmitter.prototype.serialize = function () {
  57913. var serializationObject = {};
  57914. serializationObject.type = this.getClassName();
  57915. serializationObject.radius = this.radius;
  57916. serializationObject.height = this.height;
  57917. serializationObject.radiusRange = this.radiusRange;
  57918. serializationObject.directionRandomizer = this.directionRandomizer;
  57919. return serializationObject;
  57920. };
  57921. /**
  57922. * Parse properties from a JSON object
  57923. * @param serializationObject defines the JSON object
  57924. */
  57925. CylinderParticleEmitter.prototype.parse = function (serializationObject) {
  57926. this.radius = serializationObject.radius;
  57927. this.height = serializationObject.height;
  57928. this.radiusRange = serializationObject.radiusRange;
  57929. this.directionRandomizer = serializationObject.directionRandomizer;
  57930. };
  57931. return CylinderParticleEmitter;
  57932. }());
  57933. BABYLON.CylinderParticleEmitter = CylinderParticleEmitter;
  57934. })(BABYLON || (BABYLON = {}));
  57935. //# sourceMappingURL=babylon.cylinderParticleEmitter.js.map
  57936. var BABYLON;
  57937. (function (BABYLON) {
  57938. /**
  57939. * Particle emitter emitting particles from the inside of a cone.
  57940. * It emits the particles alongside the cone volume from the base to the particle.
  57941. * The emission direction might be randomized.
  57942. */
  57943. var ConeParticleEmitter = /** @class */ (function () {
  57944. /**
  57945. * Creates a new instance ConeParticleEmitter
  57946. * @param radius the radius of the emission cone (1 by default)
  57947. * @param angles the cone base angle (PI by default)
  57948. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  57949. */
  57950. function ConeParticleEmitter(radius, angle,
  57951. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  57952. directionRandomizer) {
  57953. if (radius === void 0) { radius = 1; }
  57954. if (angle === void 0) { angle = Math.PI; }
  57955. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57956. this.directionRandomizer = directionRandomizer;
  57957. /**
  57958. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  57959. */
  57960. this.radiusRange = 1;
  57961. /**
  57962. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  57963. */
  57964. this.heightRange = 1;
  57965. /**
  57966. * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
  57967. */
  57968. this.emitFromSpawnPointOnly = false;
  57969. this.angle = angle;
  57970. this.radius = radius;
  57971. }
  57972. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  57973. /**
  57974. * Gets or sets the radius of the emission cone
  57975. */
  57976. get: function () {
  57977. return this._radius;
  57978. },
  57979. set: function (value) {
  57980. this._radius = value;
  57981. this._buildHeight();
  57982. },
  57983. enumerable: true,
  57984. configurable: true
  57985. });
  57986. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  57987. /**
  57988. * Gets or sets the angle of the emission cone
  57989. */
  57990. get: function () {
  57991. return this._angle;
  57992. },
  57993. set: function (value) {
  57994. this._angle = value;
  57995. this._buildHeight();
  57996. },
  57997. enumerable: true,
  57998. configurable: true
  57999. });
  58000. ConeParticleEmitter.prototype._buildHeight = function () {
  58001. if (this._angle !== 0) {
  58002. this._height = this._radius / Math.tan(this._angle / 2);
  58003. }
  58004. else {
  58005. this._height = 1;
  58006. }
  58007. };
  58008. /**
  58009. * Called by the particle System when the direction is computed for the created particle.
  58010. * @param worldMatrix is the world matrix of the particle system
  58011. * @param directionToUpdate is the direction vector to update with the result
  58012. * @param particle is the particle we are computed the direction for
  58013. */
  58014. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58015. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  58016. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  58017. }
  58018. else {
  58019. // measure the direction Vector from the emitter to the particle.
  58020. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  58021. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58022. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58023. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58024. direction.x += randX;
  58025. direction.y += randY;
  58026. direction.z += randZ;
  58027. direction.normalize();
  58028. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  58029. }
  58030. };
  58031. /**
  58032. * Called by the particle System when the position is computed for the created particle.
  58033. * @param worldMatrix is the world matrix of the particle system
  58034. * @param positionToUpdate is the position vector to update with the result
  58035. * @param particle is the particle we are computed the position for
  58036. */
  58037. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58038. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  58039. var h;
  58040. if (!this.emitFromSpawnPointOnly) {
  58041. h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  58042. // Better distribution in a cone at normal angles.
  58043. h = 1 - h * h;
  58044. }
  58045. else {
  58046. h = 0.0001;
  58047. }
  58048. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  58049. radius = radius * h;
  58050. var randX = radius * Math.sin(s);
  58051. var randZ = radius * Math.cos(s);
  58052. var randY = h * this._height;
  58053. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  58054. };
  58055. /**
  58056. * Clones the current emitter and returns a copy of it
  58057. * @returns the new emitter
  58058. */
  58059. ConeParticleEmitter.prototype.clone = function () {
  58060. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  58061. BABYLON.Tools.DeepCopy(this, newOne);
  58062. return newOne;
  58063. };
  58064. /**
  58065. * Called by the GPUParticleSystem to setup the update shader
  58066. * @param effect defines the update shader
  58067. */
  58068. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  58069. effect.setFloat2("radius", this._radius, this.radiusRange);
  58070. effect.setFloat("coneAngle", this._angle);
  58071. effect.setFloat2("height", this._height, this.heightRange);
  58072. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58073. };
  58074. /**
  58075. * Returns a string to use to update the GPU particles update shader
  58076. * @returns a string containng the defines string
  58077. */
  58078. ConeParticleEmitter.prototype.getEffectDefines = function () {
  58079. var defines = "#define CONEEMITTER";
  58080. if (this.emitFromSpawnPointOnly) {
  58081. defines += "\n#define CONEEMITTERSPAWNPOINT";
  58082. }
  58083. return defines;
  58084. };
  58085. /**
  58086. * Returns the string "ConeParticleEmitter"
  58087. * @returns a string containing the class name
  58088. */
  58089. ConeParticleEmitter.prototype.getClassName = function () {
  58090. return "ConeParticleEmitter";
  58091. };
  58092. /**
  58093. * Serializes the particle system to a JSON object.
  58094. * @returns the JSON object
  58095. */
  58096. ConeParticleEmitter.prototype.serialize = function () {
  58097. var serializationObject = {};
  58098. serializationObject.type = this.getClassName();
  58099. serializationObject.radius = this._radius;
  58100. serializationObject.angle = this._angle;
  58101. serializationObject.directionRandomizer = this.directionRandomizer;
  58102. return serializationObject;
  58103. };
  58104. /**
  58105. * Parse properties from a JSON object
  58106. * @param serializationObject defines the JSON object
  58107. */
  58108. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  58109. this.radius = serializationObject.radius;
  58110. this.angle = serializationObject.angle;
  58111. this.directionRandomizer = serializationObject.directionRandomizer;
  58112. };
  58113. return ConeParticleEmitter;
  58114. }());
  58115. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  58116. })(BABYLON || (BABYLON = {}));
  58117. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  58118. var BABYLON;
  58119. (function (BABYLON) {
  58120. /**
  58121. * Particle emitter emitting particles from the inside of a sphere.
  58122. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  58123. */
  58124. var SphereParticleEmitter = /** @class */ (function () {
  58125. /**
  58126. * Creates a new instance SphereParticleEmitter
  58127. * @param radius the radius of the emission sphere (1 by default)
  58128. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58129. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  58130. */
  58131. function SphereParticleEmitter(
  58132. /**
  58133. * The radius of the emission sphere.
  58134. */
  58135. radius,
  58136. /**
  58137. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  58138. */
  58139. radiusRange,
  58140. /**
  58141. * How much to randomize the particle direction [0-1].
  58142. */
  58143. directionRandomizer) {
  58144. if (radius === void 0) { radius = 1; }
  58145. if (radiusRange === void 0) { radiusRange = 1; }
  58146. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58147. this.radius = radius;
  58148. this.radiusRange = radiusRange;
  58149. this.directionRandomizer = directionRandomizer;
  58150. }
  58151. /**
  58152. * Called by the particle System when the direction is computed for the created particle.
  58153. * @param worldMatrix is the world matrix of the particle system
  58154. * @param directionToUpdate is the direction vector to update with the result
  58155. * @param particle is the particle we are computed the direction for
  58156. */
  58157. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58158. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  58159. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58160. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58161. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58162. direction.x += randX;
  58163. direction.y += randY;
  58164. direction.z += randZ;
  58165. direction.normalize();
  58166. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  58167. };
  58168. /**
  58169. * Called by the particle System when the position is computed for the created particle.
  58170. * @param worldMatrix is the world matrix of the particle system
  58171. * @param positionToUpdate is the position vector to update with the result
  58172. * @param particle is the particle we are computed the position for
  58173. */
  58174. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58175. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  58176. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  58177. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  58178. var theta = Math.acos(2 * v - 1);
  58179. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  58180. var randY = randRadius * Math.cos(theta);
  58181. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  58182. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  58183. };
  58184. /**
  58185. * Clones the current emitter and returns a copy of it
  58186. * @returns the new emitter
  58187. */
  58188. SphereParticleEmitter.prototype.clone = function () {
  58189. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  58190. BABYLON.Tools.DeepCopy(this, newOne);
  58191. return newOne;
  58192. };
  58193. /**
  58194. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  58195. * @param effect defines the update shader
  58196. */
  58197. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  58198. effect.setFloat("radius", this.radius);
  58199. effect.setFloat("radiusRange", this.radiusRange);
  58200. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58201. };
  58202. /**
  58203. * Returns a string to use to update the GPU particles update shader
  58204. * @returns a string containng the defines string
  58205. */
  58206. SphereParticleEmitter.prototype.getEffectDefines = function () {
  58207. return "#define SPHEREEMITTER";
  58208. };
  58209. /**
  58210. * Returns the string "SphereParticleEmitter"
  58211. * @returns a string containing the class name
  58212. */
  58213. SphereParticleEmitter.prototype.getClassName = function () {
  58214. return "SphereParticleEmitter";
  58215. };
  58216. /**
  58217. * Serializes the particle system to a JSON object.
  58218. * @returns the JSON object
  58219. */
  58220. SphereParticleEmitter.prototype.serialize = function () {
  58221. var serializationObject = {};
  58222. serializationObject.type = this.getClassName();
  58223. serializationObject.radius = this.radius;
  58224. serializationObject.radiusRange = this.radiusRange;
  58225. serializationObject.directionRandomizer = this.directionRandomizer;
  58226. return serializationObject;
  58227. };
  58228. /**
  58229. * Parse properties from a JSON object
  58230. * @param serializationObject defines the JSON object
  58231. */
  58232. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  58233. this.radius = serializationObject.radius;
  58234. this.radiusRange = serializationObject.radiusRange;
  58235. this.directionRandomizer = serializationObject.directionRandomizer;
  58236. };
  58237. return SphereParticleEmitter;
  58238. }());
  58239. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  58240. /**
  58241. * Particle emitter emitting particles from the inside of a sphere.
  58242. * It emits the particles randomly between two vectors.
  58243. */
  58244. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  58245. __extends(SphereDirectedParticleEmitter, _super);
  58246. /**
  58247. * Creates a new instance SphereDirectedParticleEmitter
  58248. * @param radius the radius of the emission sphere (1 by default)
  58249. * @param direction1 the min limit of the emission direction (up vector by default)
  58250. * @param direction2 the max limit of the emission direction (up vector by default)
  58251. */
  58252. function SphereDirectedParticleEmitter(radius,
  58253. /**
  58254. * The min limit of the emission direction.
  58255. */
  58256. direction1,
  58257. /**
  58258. * The max limit of the emission direction.
  58259. */
  58260. direction2) {
  58261. if (radius === void 0) { radius = 1; }
  58262. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  58263. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  58264. var _this = _super.call(this, radius) || this;
  58265. _this.direction1 = direction1;
  58266. _this.direction2 = direction2;
  58267. return _this;
  58268. }
  58269. /**
  58270. * Called by the particle System when the direction is computed for the created particle.
  58271. * @param worldMatrix is the world matrix of the particle system
  58272. * @param directionToUpdate is the direction vector to update with the result
  58273. * @param particle is the particle we are computed the direction for
  58274. */
  58275. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58276. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  58277. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  58278. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  58279. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  58280. };
  58281. /**
  58282. * Clones the current emitter and returns a copy of it
  58283. * @returns the new emitter
  58284. */
  58285. SphereDirectedParticleEmitter.prototype.clone = function () {
  58286. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  58287. BABYLON.Tools.DeepCopy(this, newOne);
  58288. return newOne;
  58289. };
  58290. /**
  58291. * Called by the GPUParticleSystem to setup the update shader
  58292. * @param effect defines the update shader
  58293. */
  58294. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  58295. effect.setFloat("radius", this.radius);
  58296. effect.setFloat("radiusRange", this.radiusRange);
  58297. effect.setVector3("direction1", this.direction1);
  58298. effect.setVector3("direction2", this.direction2);
  58299. };
  58300. /**
  58301. * Returns a string to use to update the GPU particles update shader
  58302. * @returns a string containng the defines string
  58303. */
  58304. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  58305. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  58306. };
  58307. /**
  58308. * Returns the string "SphereDirectedParticleEmitter"
  58309. * @returns a string containing the class name
  58310. */
  58311. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  58312. return "SphereDirectedParticleEmitter";
  58313. };
  58314. /**
  58315. * Serializes the particle system to a JSON object.
  58316. * @returns the JSON object
  58317. */
  58318. SphereDirectedParticleEmitter.prototype.serialize = function () {
  58319. var serializationObject = _super.prototype.serialize.call(this);
  58320. serializationObject.direction1 = this.direction1.asArray();
  58321. serializationObject.direction2 = this.direction2.asArray();
  58322. return serializationObject;
  58323. };
  58324. /**
  58325. * Parse properties from a JSON object
  58326. * @param serializationObject defines the JSON object
  58327. */
  58328. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  58329. _super.prototype.parse.call(this, serializationObject);
  58330. this.direction1.copyFrom(serializationObject.direction1);
  58331. this.direction2.copyFrom(serializationObject.direction2);
  58332. };
  58333. return SphereDirectedParticleEmitter;
  58334. }(SphereParticleEmitter));
  58335. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  58336. })(BABYLON || (BABYLON = {}));
  58337. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  58338. var BABYLON;
  58339. (function (BABYLON) {
  58340. /**
  58341. * Particle emitter emitting particles from the inside of a hemisphere.
  58342. * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
  58343. */
  58344. var HemisphericParticleEmitter = /** @class */ (function () {
  58345. /**
  58346. * Creates a new instance HemisphericParticleEmitter
  58347. * @param radius the radius of the emission hemisphere (1 by default)
  58348. * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58349. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  58350. */
  58351. function HemisphericParticleEmitter(
  58352. /**
  58353. * The radius of the emission hemisphere.
  58354. */
  58355. radius,
  58356. /**
  58357. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  58358. */
  58359. radiusRange,
  58360. /**
  58361. * How much to randomize the particle direction [0-1].
  58362. */
  58363. directionRandomizer) {
  58364. if (radius === void 0) { radius = 1; }
  58365. if (radiusRange === void 0) { radiusRange = 1; }
  58366. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58367. this.radius = radius;
  58368. this.radiusRange = radiusRange;
  58369. this.directionRandomizer = directionRandomizer;
  58370. }
  58371. /**
  58372. * Called by the particle System when the direction is computed for the created particle.
  58373. * @param worldMatrix is the world matrix of the particle system
  58374. * @param directionToUpdate is the direction vector to update with the result
  58375. * @param particle is the particle we are computed the direction for
  58376. */
  58377. HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58378. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  58379. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58380. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58381. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58382. direction.x += randX;
  58383. direction.y += randY;
  58384. direction.z += randZ;
  58385. direction.normalize();
  58386. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  58387. };
  58388. /**
  58389. * Called by the particle System when the position is computed for the created particle.
  58390. * @param worldMatrix is the world matrix of the particle system
  58391. * @param positionToUpdate is the position vector to update with the result
  58392. * @param particle is the particle we are computed the position for
  58393. */
  58394. HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58395. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  58396. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  58397. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  58398. var theta = Math.acos(2 * v - 1);
  58399. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  58400. var randY = randRadius * Math.cos(theta);
  58401. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  58402. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  58403. };
  58404. /**
  58405. * Clones the current emitter and returns a copy of it
  58406. * @returns the new emitter
  58407. */
  58408. HemisphericParticleEmitter.prototype.clone = function () {
  58409. var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
  58410. BABYLON.Tools.DeepCopy(this, newOne);
  58411. return newOne;
  58412. };
  58413. /**
  58414. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  58415. * @param effect defines the update shader
  58416. */
  58417. HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
  58418. effect.setFloat("radius", this.radius);
  58419. effect.setFloat("radiusRange", this.radiusRange);
  58420. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58421. };
  58422. /**
  58423. * Returns a string to use to update the GPU particles update shader
  58424. * @returns a string containng the defines string
  58425. */
  58426. HemisphericParticleEmitter.prototype.getEffectDefines = function () {
  58427. return "#define HEMISPHERICEMITTER";
  58428. };
  58429. /**
  58430. * Returns the string "HemisphericParticleEmitter"
  58431. * @returns a string containing the class name
  58432. */
  58433. HemisphericParticleEmitter.prototype.getClassName = function () {
  58434. return "HemisphericParticleEmitter";
  58435. };
  58436. /**
  58437. * Serializes the particle system to a JSON object.
  58438. * @returns the JSON object
  58439. */
  58440. HemisphericParticleEmitter.prototype.serialize = function () {
  58441. var serializationObject = {};
  58442. serializationObject.type = this.getClassName();
  58443. serializationObject.radius = this.radius;
  58444. serializationObject.radiusRange = this.radiusRange;
  58445. serializationObject.directionRandomizer = this.directionRandomizer;
  58446. return serializationObject;
  58447. };
  58448. /**
  58449. * Parse properties from a JSON object
  58450. * @param serializationObject defines the JSON object
  58451. */
  58452. HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
  58453. this.radius = serializationObject.radius;
  58454. this.radiusRange = serializationObject.radiusRange;
  58455. this.directionRandomizer = serializationObject.directionRandomizer;
  58456. };
  58457. return HemisphericParticleEmitter;
  58458. }());
  58459. BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
  58460. })(BABYLON || (BABYLON = {}));
  58461. //# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map
  58462. var BABYLON;
  58463. (function (BABYLON) {
  58464. /**
  58465. * Particle emitter emitting particles from a point.
  58466. * It emits the particles randomly between 2 given directions.
  58467. */
  58468. var PointParticleEmitter = /** @class */ (function () {
  58469. /**
  58470. * Creates a new instance PointParticleEmitter
  58471. */
  58472. function PointParticleEmitter() {
  58473. /**
  58474. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58475. */
  58476. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  58477. /**
  58478. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58479. */
  58480. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  58481. }
  58482. /**
  58483. * Called by the particle System when the direction is computed for the created particle.
  58484. * @param worldMatrix is the world matrix of the particle system
  58485. * @param directionToUpdate is the direction vector to update with the result
  58486. * @param particle is the particle we are computed the direction for
  58487. */
  58488. PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58489. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  58490. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  58491. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  58492. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  58493. };
  58494. /**
  58495. * Called by the particle System when the position is computed for the created particle.
  58496. * @param worldMatrix is the world matrix of the particle system
  58497. * @param positionToUpdate is the position vector to update with the result
  58498. * @param particle is the particle we are computed the position for
  58499. */
  58500. PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58501. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  58502. };
  58503. /**
  58504. * Clones the current emitter and returns a copy of it
  58505. * @returns the new emitter
  58506. */
  58507. PointParticleEmitter.prototype.clone = function () {
  58508. var newOne = new PointParticleEmitter();
  58509. BABYLON.Tools.DeepCopy(this, newOne);
  58510. return newOne;
  58511. };
  58512. /**
  58513. * Called by the GPUParticleSystem to setup the update shader
  58514. * @param effect defines the update shader
  58515. */
  58516. PointParticleEmitter.prototype.applyToShader = function (effect) {
  58517. effect.setVector3("direction1", this.direction1);
  58518. effect.setVector3("direction2", this.direction2);
  58519. };
  58520. /**
  58521. * Returns a string to use to update the GPU particles update shader
  58522. * @returns a string containng the defines string
  58523. */
  58524. PointParticleEmitter.prototype.getEffectDefines = function () {
  58525. return "#define POINTEMITTER";
  58526. };
  58527. /**
  58528. * Returns the string "PointParticleEmitter"
  58529. * @returns a string containing the class name
  58530. */
  58531. PointParticleEmitter.prototype.getClassName = function () {
  58532. return "PointParticleEmitter";
  58533. };
  58534. /**
  58535. * Serializes the particle system to a JSON object.
  58536. * @returns the JSON object
  58537. */
  58538. PointParticleEmitter.prototype.serialize = function () {
  58539. var serializationObject = {};
  58540. serializationObject.type = this.getClassName();
  58541. serializationObject.direction1 = this.direction1.asArray();
  58542. serializationObject.direction2 = this.direction2.asArray();
  58543. return serializationObject;
  58544. };
  58545. /**
  58546. * Parse properties from a JSON object
  58547. * @param serializationObject defines the JSON object
  58548. */
  58549. PointParticleEmitter.prototype.parse = function (serializationObject) {
  58550. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  58551. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  58552. };
  58553. return PointParticleEmitter;
  58554. }());
  58555. BABYLON.PointParticleEmitter = PointParticleEmitter;
  58556. })(BABYLON || (BABYLON = {}));
  58557. //# sourceMappingURL=babylon.pointParticleEmitter.js.map
  58558. var BABYLON;
  58559. (function (BABYLON) {
  58560. // Adds the parsers to the scene parsers.
  58561. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  58562. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  58563. if (!individualParser) {
  58564. return;
  58565. }
  58566. // Particles Systems
  58567. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  58568. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  58569. var parsedParticleSystem = parsedData.particleSystems[index];
  58570. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  58571. }
  58572. }
  58573. });
  58574. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  58575. if (parsedParticleSystem.activeParticleCount) {
  58576. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  58577. return ps;
  58578. }
  58579. else {
  58580. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  58581. return ps;
  58582. }
  58583. });
  58584. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  58585. if (uniformsNames === void 0) { uniformsNames = []; }
  58586. if (samplers === void 0) { samplers = []; }
  58587. if (defines === void 0) { defines = ""; }
  58588. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  58589. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  58590. if (defines.indexOf(" BILLBOARD") === -1) {
  58591. defines += "\n#define BILLBOARD\n";
  58592. }
  58593. if (samplers.indexOf("diffuseSampler") === -1) {
  58594. samplers.push("diffuseSampler");
  58595. }
  58596. return this.createEffect({
  58597. vertex: "particles",
  58598. fragmentElement: fragmentName
  58599. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  58600. };
  58601. })(BABYLON || (BABYLON = {}));
  58602. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  58603. var BABYLON;
  58604. (function (BABYLON) {
  58605. var ShaderMaterial = /** @class */ (function (_super) {
  58606. __extends(ShaderMaterial, _super);
  58607. function ShaderMaterial(name, scene, shaderPath, options) {
  58608. var _this = _super.call(this, name, scene) || this;
  58609. _this._textures = {};
  58610. _this._textureArrays = {};
  58611. _this._floats = {};
  58612. _this._ints = {};
  58613. _this._floatsArrays = {};
  58614. _this._colors3 = {};
  58615. _this._colors3Arrays = {};
  58616. _this._colors4 = {};
  58617. _this._vectors2 = {};
  58618. _this._vectors3 = {};
  58619. _this._vectors4 = {};
  58620. _this._matrices = {};
  58621. _this._matrices3x3 = {};
  58622. _this._matrices2x2 = {};
  58623. _this._vectors2Arrays = {};
  58624. _this._vectors3Arrays = {};
  58625. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  58626. _this._shaderPath = shaderPath;
  58627. options.needAlphaBlending = options.needAlphaBlending || false;
  58628. options.needAlphaTesting = options.needAlphaTesting || false;
  58629. options.attributes = options.attributes || ["position", "normal", "uv"];
  58630. options.uniforms = options.uniforms || ["worldViewProjection"];
  58631. options.uniformBuffers = options.uniformBuffers || [];
  58632. options.samplers = options.samplers || [];
  58633. options.defines = options.defines || [];
  58634. _this._options = options;
  58635. return _this;
  58636. }
  58637. ShaderMaterial.prototype.getClassName = function () {
  58638. return "ShaderMaterial";
  58639. };
  58640. ShaderMaterial.prototype.needAlphaBlending = function () {
  58641. return this._options.needAlphaBlending;
  58642. };
  58643. ShaderMaterial.prototype.needAlphaTesting = function () {
  58644. return this._options.needAlphaTesting;
  58645. };
  58646. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  58647. if (this._options.uniforms.indexOf(uniformName) === -1) {
  58648. this._options.uniforms.push(uniformName);
  58649. }
  58650. };
  58651. ShaderMaterial.prototype.setTexture = function (name, texture) {
  58652. if (this._options.samplers.indexOf(name) === -1) {
  58653. this._options.samplers.push(name);
  58654. }
  58655. this._textures[name] = texture;
  58656. return this;
  58657. };
  58658. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  58659. if (this._options.samplers.indexOf(name) === -1) {
  58660. this._options.samplers.push(name);
  58661. }
  58662. this._checkUniform(name);
  58663. this._textureArrays[name] = textures;
  58664. return this;
  58665. };
  58666. ShaderMaterial.prototype.setFloat = function (name, value) {
  58667. this._checkUniform(name);
  58668. this._floats[name] = value;
  58669. return this;
  58670. };
  58671. ShaderMaterial.prototype.setInt = function (name, value) {
  58672. this._checkUniform(name);
  58673. this._ints[name] = value;
  58674. return this;
  58675. };
  58676. ShaderMaterial.prototype.setFloats = function (name, value) {
  58677. this._checkUniform(name);
  58678. this._floatsArrays[name] = value;
  58679. return this;
  58680. };
  58681. ShaderMaterial.prototype.setColor3 = function (name, value) {
  58682. this._checkUniform(name);
  58683. this._colors3[name] = value;
  58684. return this;
  58685. };
  58686. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  58687. this._checkUniform(name);
  58688. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  58689. color.toArray(arr, arr.length);
  58690. return arr;
  58691. }, []);
  58692. return this;
  58693. };
  58694. ShaderMaterial.prototype.setColor4 = function (name, value) {
  58695. this._checkUniform(name);
  58696. this._colors4[name] = value;
  58697. return this;
  58698. };
  58699. ShaderMaterial.prototype.setVector2 = function (name, value) {
  58700. this._checkUniform(name);
  58701. this._vectors2[name] = value;
  58702. return this;
  58703. };
  58704. ShaderMaterial.prototype.setVector3 = function (name, value) {
  58705. this._checkUniform(name);
  58706. this._vectors3[name] = value;
  58707. return this;
  58708. };
  58709. ShaderMaterial.prototype.setVector4 = function (name, value) {
  58710. this._checkUniform(name);
  58711. this._vectors4[name] = value;
  58712. return this;
  58713. };
  58714. ShaderMaterial.prototype.setMatrix = function (name, value) {
  58715. this._checkUniform(name);
  58716. this._matrices[name] = value;
  58717. return this;
  58718. };
  58719. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  58720. this._checkUniform(name);
  58721. this._matrices3x3[name] = value;
  58722. return this;
  58723. };
  58724. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  58725. this._checkUniform(name);
  58726. this._matrices2x2[name] = value;
  58727. return this;
  58728. };
  58729. ShaderMaterial.prototype.setArray2 = function (name, value) {
  58730. this._checkUniform(name);
  58731. this._vectors2Arrays[name] = value;
  58732. return this;
  58733. };
  58734. ShaderMaterial.prototype.setArray3 = function (name, value) {
  58735. this._checkUniform(name);
  58736. this._vectors3Arrays[name] = value;
  58737. return this;
  58738. };
  58739. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  58740. if (!mesh) {
  58741. return true;
  58742. }
  58743. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  58744. return false;
  58745. }
  58746. return false;
  58747. };
  58748. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  58749. var scene = this.getScene();
  58750. var engine = scene.getEngine();
  58751. if (!this.checkReadyOnEveryCall) {
  58752. if (this._renderId === scene.getRenderId()) {
  58753. if (this._checkCache(scene, mesh, useInstances)) {
  58754. return true;
  58755. }
  58756. }
  58757. }
  58758. // Instances
  58759. var defines = [];
  58760. var attribs = [];
  58761. var fallbacks = new BABYLON.EffectFallbacks();
  58762. if (useInstances) {
  58763. defines.push("#define INSTANCES");
  58764. }
  58765. for (var index = 0; index < this._options.defines.length; index++) {
  58766. defines.push(this._options.defines[index]);
  58767. }
  58768. for (var index = 0; index < this._options.attributes.length; index++) {
  58769. attribs.push(this._options.attributes[index]);
  58770. }
  58771. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  58772. attribs.push(BABYLON.VertexBuffer.ColorKind);
  58773. defines.push("#define VERTEXCOLOR");
  58774. }
  58775. // Bones
  58776. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  58777. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  58778. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  58779. if (mesh.numBoneInfluencers > 4) {
  58780. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  58781. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  58782. }
  58783. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  58784. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  58785. fallbacks.addCPUSkinningFallback(0, mesh);
  58786. if (this._options.uniforms.indexOf("mBones") === -1) {
  58787. this._options.uniforms.push("mBones");
  58788. }
  58789. }
  58790. else {
  58791. defines.push("#define NUM_BONE_INFLUENCERS 0");
  58792. }
  58793. // Textures
  58794. for (var name in this._textures) {
  58795. if (!this._textures[name].isReady()) {
  58796. return false;
  58797. }
  58798. }
  58799. // Alpha test
  58800. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  58801. defines.push("#define ALPHATEST");
  58802. }
  58803. var previousEffect = this._effect;
  58804. var join = defines.join("\n");
  58805. this._effect = engine.createEffect(this._shaderPath, {
  58806. attributes: attribs,
  58807. uniformsNames: this._options.uniforms,
  58808. uniformBuffersNames: this._options.uniformBuffers,
  58809. samplers: this._options.samplers,
  58810. defines: join,
  58811. fallbacks: fallbacks,
  58812. onCompiled: this.onCompiled,
  58813. onError: this.onError
  58814. }, engine);
  58815. if (!this._effect.isReady()) {
  58816. return false;
  58817. }
  58818. if (previousEffect !== this._effect) {
  58819. scene.resetCachedMaterial();
  58820. }
  58821. this._renderId = scene.getRenderId();
  58822. return true;
  58823. };
  58824. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  58825. var scene = this.getScene();
  58826. if (!this._effect) {
  58827. return;
  58828. }
  58829. if (this._options.uniforms.indexOf("world") !== -1) {
  58830. this._effect.setMatrix("world", world);
  58831. }
  58832. if (this._options.uniforms.indexOf("worldView") !== -1) {
  58833. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  58834. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  58835. }
  58836. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  58837. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  58838. }
  58839. };
  58840. ShaderMaterial.prototype.bind = function (world, mesh) {
  58841. // Std values
  58842. this.bindOnlyWorldMatrix(world);
  58843. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  58844. if (this._options.uniforms.indexOf("view") !== -1) {
  58845. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  58846. }
  58847. if (this._options.uniforms.indexOf("projection") !== -1) {
  58848. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  58849. }
  58850. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  58851. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  58852. }
  58853. // Bones
  58854. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  58855. var name;
  58856. // Texture
  58857. for (name in this._textures) {
  58858. this._effect.setTexture(name, this._textures[name]);
  58859. }
  58860. // Texture arrays
  58861. for (name in this._textureArrays) {
  58862. this._effect.setTextureArray(name, this._textureArrays[name]);
  58863. }
  58864. // Int
  58865. for (name in this._ints) {
  58866. this._effect.setInt(name, this._ints[name]);
  58867. }
  58868. // Float
  58869. for (name in this._floats) {
  58870. this._effect.setFloat(name, this._floats[name]);
  58871. }
  58872. // Floats
  58873. for (name in this._floatsArrays) {
  58874. this._effect.setArray(name, this._floatsArrays[name]);
  58875. }
  58876. // Color3
  58877. for (name in this._colors3) {
  58878. this._effect.setColor3(name, this._colors3[name]);
  58879. }
  58880. for (name in this._colors3Arrays) {
  58881. this._effect.setArray3(name, this._colors3Arrays[name]);
  58882. }
  58883. // Color4
  58884. for (name in this._colors4) {
  58885. var color = this._colors4[name];
  58886. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  58887. }
  58888. // Vector2
  58889. for (name in this._vectors2) {
  58890. this._effect.setVector2(name, this._vectors2[name]);
  58891. }
  58892. // Vector3
  58893. for (name in this._vectors3) {
  58894. this._effect.setVector3(name, this._vectors3[name]);
  58895. }
  58896. // Vector4
  58897. for (name in this._vectors4) {
  58898. this._effect.setVector4(name, this._vectors4[name]);
  58899. }
  58900. // Matrix
  58901. for (name in this._matrices) {
  58902. this._effect.setMatrix(name, this._matrices[name]);
  58903. }
  58904. // Matrix 3x3
  58905. for (name in this._matrices3x3) {
  58906. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  58907. }
  58908. // Matrix 2x2
  58909. for (name in this._matrices2x2) {
  58910. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  58911. }
  58912. // Vector2Array
  58913. for (name in this._vectors2Arrays) {
  58914. this._effect.setArray2(name, this._vectors2Arrays[name]);
  58915. }
  58916. // Vector3Array
  58917. for (name in this._vectors3Arrays) {
  58918. this._effect.setArray3(name, this._vectors3Arrays[name]);
  58919. }
  58920. }
  58921. this._afterBind(mesh);
  58922. };
  58923. ShaderMaterial.prototype.getActiveTextures = function () {
  58924. var activeTextures = _super.prototype.getActiveTextures.call(this);
  58925. for (var name in this._textures) {
  58926. activeTextures.push(this._textures[name]);
  58927. }
  58928. for (var name in this._textureArrays) {
  58929. var array = this._textureArrays[name];
  58930. for (var index = 0; index < array.length; index++) {
  58931. activeTextures.push(array[index]);
  58932. }
  58933. }
  58934. return activeTextures;
  58935. };
  58936. ShaderMaterial.prototype.hasTexture = function (texture) {
  58937. if (_super.prototype.hasTexture.call(this, texture)) {
  58938. return true;
  58939. }
  58940. for (var name in this._textures) {
  58941. if (this._textures[name] === texture) {
  58942. return true;
  58943. }
  58944. }
  58945. for (var name in this._textureArrays) {
  58946. var array = this._textureArrays[name];
  58947. for (var index = 0; index < array.length; index++) {
  58948. if (array[index] === texture) {
  58949. return true;
  58950. }
  58951. }
  58952. }
  58953. return false;
  58954. };
  58955. ShaderMaterial.prototype.clone = function (name) {
  58956. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  58957. return newShaderMaterial;
  58958. };
  58959. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  58960. if (forceDisposeTextures) {
  58961. var name;
  58962. for (name in this._textures) {
  58963. this._textures[name].dispose();
  58964. }
  58965. for (name in this._textureArrays) {
  58966. var array = this._textureArrays[name];
  58967. for (var index = 0; index < array.length; index++) {
  58968. array[index].dispose();
  58969. }
  58970. }
  58971. }
  58972. this._textures = {};
  58973. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  58974. };
  58975. ShaderMaterial.prototype.serialize = function () {
  58976. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  58977. serializationObject.customType = "BABYLON.ShaderMaterial";
  58978. serializationObject.options = this._options;
  58979. serializationObject.shaderPath = this._shaderPath;
  58980. var name;
  58981. // Texture
  58982. serializationObject.textures = {};
  58983. for (name in this._textures) {
  58984. serializationObject.textures[name] = this._textures[name].serialize();
  58985. }
  58986. // Texture arrays
  58987. serializationObject.textureArrays = {};
  58988. for (name in this._textureArrays) {
  58989. serializationObject.textureArrays[name] = [];
  58990. var array = this._textureArrays[name];
  58991. for (var index = 0; index < array.length; index++) {
  58992. serializationObject.textureArrays[name].push(array[index].serialize());
  58993. }
  58994. }
  58995. // Float
  58996. serializationObject.floats = {};
  58997. for (name in this._floats) {
  58998. serializationObject.floats[name] = this._floats[name];
  58999. }
  59000. // Float s
  59001. serializationObject.FloatArrays = {};
  59002. for (name in this._floatsArrays) {
  59003. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59004. }
  59005. // Color3
  59006. serializationObject.colors3 = {};
  59007. for (name in this._colors3) {
  59008. serializationObject.colors3[name] = this._colors3[name].asArray();
  59009. }
  59010. // Color3 array
  59011. serializationObject.colors3Arrays = {};
  59012. for (name in this._colors3Arrays) {
  59013. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59014. }
  59015. // Color4
  59016. serializationObject.colors4 = {};
  59017. for (name in this._colors4) {
  59018. serializationObject.colors4[name] = this._colors4[name].asArray();
  59019. }
  59020. // Vector2
  59021. serializationObject.vectors2 = {};
  59022. for (name in this._vectors2) {
  59023. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59024. }
  59025. // Vector3
  59026. serializationObject.vectors3 = {};
  59027. for (name in this._vectors3) {
  59028. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59029. }
  59030. // Vector4
  59031. serializationObject.vectors4 = {};
  59032. for (name in this._vectors4) {
  59033. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59034. }
  59035. // Matrix
  59036. serializationObject.matrices = {};
  59037. for (name in this._matrices) {
  59038. serializationObject.matrices[name] = this._matrices[name].asArray();
  59039. }
  59040. // Matrix 3x3
  59041. serializationObject.matrices3x3 = {};
  59042. for (name in this._matrices3x3) {
  59043. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59044. }
  59045. // Matrix 2x2
  59046. serializationObject.matrices2x2 = {};
  59047. for (name in this._matrices2x2) {
  59048. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59049. }
  59050. // Vector2Array
  59051. serializationObject.vectors2Arrays = {};
  59052. for (name in this._vectors2Arrays) {
  59053. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59054. }
  59055. // Vector3Array
  59056. serializationObject.vectors3Arrays = {};
  59057. for (name in this._vectors3Arrays) {
  59058. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  59059. }
  59060. return serializationObject;
  59061. };
  59062. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  59063. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  59064. var name;
  59065. // Texture
  59066. for (name in source.textures) {
  59067. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  59068. }
  59069. // Texture arrays
  59070. for (name in source.textureArrays) {
  59071. var array = source.textureArrays[name];
  59072. var textureArray = new Array();
  59073. for (var index = 0; index < array.length; index++) {
  59074. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  59075. }
  59076. material.setTextureArray(name, textureArray);
  59077. }
  59078. // Float
  59079. for (name in source.floats) {
  59080. material.setFloat(name, source.floats[name]);
  59081. }
  59082. // Float s
  59083. for (name in source.floatsArrays) {
  59084. material.setFloats(name, source.floatsArrays[name]);
  59085. }
  59086. // Color3
  59087. for (name in source.colors3) {
  59088. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  59089. }
  59090. // Color3 arrays
  59091. for (name in source.colors3Arrays) {
  59092. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  59093. if (i % 3 === 0) {
  59094. arr.push([num]);
  59095. }
  59096. else {
  59097. arr[arr.length - 1].push(num);
  59098. }
  59099. return arr;
  59100. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  59101. material.setColor3Array(name, colors);
  59102. }
  59103. // Color4
  59104. for (name in source.colors4) {
  59105. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  59106. }
  59107. // Vector2
  59108. for (name in source.vectors2) {
  59109. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  59110. }
  59111. // Vector3
  59112. for (name in source.vectors3) {
  59113. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59114. }
  59115. // Vector4
  59116. for (name in source.vectors4) {
  59117. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59118. }
  59119. // Matrix
  59120. for (name in source.matrices) {
  59121. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59122. }
  59123. // Matrix 3x3
  59124. for (name in source.matrices3x3) {
  59125. material.setMatrix3x3(name, source.matrices3x3[name]);
  59126. }
  59127. // Matrix 2x2
  59128. for (name in source.matrices2x2) {
  59129. material.setMatrix2x2(name, source.matrices2x2[name]);
  59130. }
  59131. // Vector2Array
  59132. for (name in source.vectors2Arrays) {
  59133. material.setArray2(name, source.vectors2Arrays[name]);
  59134. }
  59135. // Vector3Array
  59136. for (name in source.vectors3Arrays) {
  59137. material.setArray3(name, source.vectors3Arrays[name]);
  59138. }
  59139. return material;
  59140. };
  59141. return ShaderMaterial;
  59142. }(BABYLON.Material));
  59143. BABYLON.ShaderMaterial = ShaderMaterial;
  59144. })(BABYLON || (BABYLON = {}));
  59145. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59146. var BABYLON;
  59147. (function (BABYLON) {
  59148. var GroundMesh = /** @class */ (function (_super) {
  59149. __extends(GroundMesh, _super);
  59150. function GroundMesh(name, scene) {
  59151. var _this = _super.call(this, name, scene) || this;
  59152. _this.generateOctree = false;
  59153. return _this;
  59154. }
  59155. GroundMesh.prototype.getClassName = function () {
  59156. return "GroundMesh";
  59157. };
  59158. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59159. get: function () {
  59160. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59161. },
  59162. enumerable: true,
  59163. configurable: true
  59164. });
  59165. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59166. get: function () {
  59167. return this._subdivisionsX;
  59168. },
  59169. enumerable: true,
  59170. configurable: true
  59171. });
  59172. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  59173. get: function () {
  59174. return this._subdivisionsY;
  59175. },
  59176. enumerable: true,
  59177. configurable: true
  59178. });
  59179. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  59180. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  59181. this._subdivisionsX = chunksCount;
  59182. this._subdivisionsY = chunksCount;
  59183. this.subdivide(chunksCount);
  59184. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  59185. };
  59186. /**
  59187. * Returns a height (y) value in the Worl system :
  59188. * the ground altitude at the coordinates (x, z) expressed in the World system.
  59189. * Returns the ground y position if (x, z) are outside the ground surface.
  59190. */
  59191. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59192. var world = this.getWorldMatrix();
  59193. var invMat = BABYLON.Tmp.Matrix[5];
  59194. world.invertToRef(invMat);
  59195. var tmpVect = BABYLON.Tmp.Vector3[8];
  59196. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59197. x = tmpVect.x;
  59198. z = tmpVect.z;
  59199. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59200. return this.position.y;
  59201. }
  59202. if (!this._heightQuads || this._heightQuads.length == 0) {
  59203. this._initHeightQuads();
  59204. this._computeHeightQuads();
  59205. }
  59206. var facet = this._getFacetAt(x, z);
  59207. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  59208. // return y in the World system
  59209. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  59210. return tmpVect.y;
  59211. };
  59212. /**
  59213. * Returns a normalized vector (Vector3) orthogonal to the ground
  59214. * at the ground coordinates (x, z) expressed in the World system.
  59215. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  59216. */
  59217. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  59218. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  59219. this.getNormalAtCoordinatesToRef(x, z, normal);
  59220. return normal;
  59221. };
  59222. /**
  59223. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  59224. * at the ground coordinates (x, z) expressed in the World system.
  59225. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  59226. * Returns the GroundMesh.
  59227. */
  59228. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  59229. var world = this.getWorldMatrix();
  59230. var tmpMat = BABYLON.Tmp.Matrix[5];
  59231. world.invertToRef(tmpMat);
  59232. var tmpVect = BABYLON.Tmp.Vector3[8];
  59233. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  59234. x = tmpVect.x;
  59235. z = tmpVect.z;
  59236. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59237. return this;
  59238. }
  59239. if (!this._heightQuads || this._heightQuads.length == 0) {
  59240. this._initHeightQuads();
  59241. this._computeHeightQuads();
  59242. }
  59243. var facet = this._getFacetAt(x, z);
  59244. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  59245. return this;
  59246. };
  59247. /**
  59248. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  59249. * if the ground has been updated.
  59250. * This can be used in the render loop.
  59251. * Returns the GroundMesh.
  59252. */
  59253. GroundMesh.prototype.updateCoordinateHeights = function () {
  59254. if (!this._heightQuads || this._heightQuads.length == 0) {
  59255. this._initHeightQuads();
  59256. }
  59257. this._computeHeightQuads();
  59258. return this;
  59259. };
  59260. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  59261. GroundMesh.prototype._getFacetAt = function (x, z) {
  59262. // retrieve col and row from x, z coordinates in the ground local system
  59263. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  59264. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  59265. var quad = this._heightQuads[row * this._subdivisionsX + col];
  59266. var facet;
  59267. if (z < quad.slope.x * x + quad.slope.y) {
  59268. facet = quad.facet1;
  59269. }
  59270. else {
  59271. facet = quad.facet2;
  59272. }
  59273. return facet;
  59274. };
  59275. // Creates and populates the heightMap array with "facet" elements :
  59276. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  59277. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59278. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59279. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59280. // Returns the GroundMesh.
  59281. GroundMesh.prototype._initHeightQuads = function () {
  59282. var subdivisionsX = this._subdivisionsX;
  59283. var subdivisionsY = this._subdivisionsY;
  59284. this._heightQuads = new Array();
  59285. for (var row = 0; row < subdivisionsY; row++) {
  59286. for (var col = 0; col < subdivisionsX; col++) {
  59287. 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) };
  59288. this._heightQuads[row * subdivisionsX + col] = quad;
  59289. }
  59290. }
  59291. return this;
  59292. };
  59293. // Compute each quad element values and update the the heightMap array :
  59294. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59295. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59296. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59297. // Returns the GroundMesh.
  59298. GroundMesh.prototype._computeHeightQuads = function () {
  59299. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59300. if (!positions) {
  59301. return this;
  59302. }
  59303. var v1 = BABYLON.Tmp.Vector3[3];
  59304. var v2 = BABYLON.Tmp.Vector3[2];
  59305. var v3 = BABYLON.Tmp.Vector3[1];
  59306. var v4 = BABYLON.Tmp.Vector3[0];
  59307. var v1v2 = BABYLON.Tmp.Vector3[4];
  59308. var v1v3 = BABYLON.Tmp.Vector3[5];
  59309. var v1v4 = BABYLON.Tmp.Vector3[6];
  59310. var norm1 = BABYLON.Tmp.Vector3[7];
  59311. var norm2 = BABYLON.Tmp.Vector3[8];
  59312. var i = 0;
  59313. var j = 0;
  59314. var k = 0;
  59315. var cd = 0; // 2D slope coefficient : z = cd * x + h
  59316. var h = 0;
  59317. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  59318. var d2 = 0;
  59319. var subdivisionsX = this._subdivisionsX;
  59320. var subdivisionsY = this._subdivisionsY;
  59321. for (var row = 0; row < subdivisionsY; row++) {
  59322. for (var col = 0; col < subdivisionsX; col++) {
  59323. i = col * 3;
  59324. j = row * (subdivisionsX + 1) * 3;
  59325. k = (row + 1) * (subdivisionsX + 1) * 3;
  59326. v1.x = positions[j + i];
  59327. v1.y = positions[j + i + 1];
  59328. v1.z = positions[j + i + 2];
  59329. v2.x = positions[j + i + 3];
  59330. v2.y = positions[j + i + 4];
  59331. v2.z = positions[j + i + 5];
  59332. v3.x = positions[k + i];
  59333. v3.y = positions[k + i + 1];
  59334. v3.z = positions[k + i + 2];
  59335. v4.x = positions[k + i + 3];
  59336. v4.y = positions[k + i + 4];
  59337. v4.z = positions[k + i + 5];
  59338. // 2D slope V1V4
  59339. cd = (v4.z - v1.z) / (v4.x - v1.x);
  59340. h = v1.z - cd * v1.x; // v1 belongs to the slope
  59341. // facet equations :
  59342. // we compute each facet normal vector
  59343. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  59344. // we compute the value d by applying the equation to v1 which belongs to the plane
  59345. // then we store the facet equation in a Vector4
  59346. v2.subtractToRef(v1, v1v2);
  59347. v3.subtractToRef(v1, v1v3);
  59348. v4.subtractToRef(v1, v1v4);
  59349. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  59350. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  59351. norm1.normalize();
  59352. norm2.normalize();
  59353. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  59354. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  59355. var quad = this._heightQuads[row * subdivisionsX + col];
  59356. quad.slope.copyFromFloats(cd, h);
  59357. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  59358. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  59359. }
  59360. }
  59361. return this;
  59362. };
  59363. GroundMesh.prototype.serialize = function (serializationObject) {
  59364. _super.prototype.serialize.call(this, serializationObject);
  59365. serializationObject.subdivisionsX = this._subdivisionsX;
  59366. serializationObject.subdivisionsY = this._subdivisionsY;
  59367. serializationObject.minX = this._minX;
  59368. serializationObject.maxX = this._maxX;
  59369. serializationObject.minZ = this._minZ;
  59370. serializationObject.maxZ = this._maxZ;
  59371. serializationObject.width = this._width;
  59372. serializationObject.height = this._height;
  59373. };
  59374. GroundMesh.Parse = function (parsedMesh, scene) {
  59375. var result = new GroundMesh(parsedMesh.name, scene);
  59376. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  59377. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  59378. result._minX = parsedMesh.minX;
  59379. result._maxX = parsedMesh.maxX;
  59380. result._minZ = parsedMesh.minZ;
  59381. result._maxZ = parsedMesh.maxZ;
  59382. result._width = parsedMesh.width;
  59383. result._height = parsedMesh.height;
  59384. return result;
  59385. };
  59386. return GroundMesh;
  59387. }(BABYLON.Mesh));
  59388. BABYLON.GroundMesh = GroundMesh;
  59389. })(BABYLON || (BABYLON = {}));
  59390. //# sourceMappingURL=babylon.groundMesh.js.map
  59391. var BABYLON;
  59392. (function (BABYLON) {
  59393. /**
  59394. * Creates an instance based on a source mesh.
  59395. */
  59396. var InstancedMesh = /** @class */ (function (_super) {
  59397. __extends(InstancedMesh, _super);
  59398. function InstancedMesh(name, source) {
  59399. var _this = _super.call(this, name, source.getScene()) || this;
  59400. source.instances.push(_this);
  59401. _this._sourceMesh = source;
  59402. _this.position.copyFrom(source.position);
  59403. _this.rotation.copyFrom(source.rotation);
  59404. _this.scaling.copyFrom(source.scaling);
  59405. if (source.rotationQuaternion) {
  59406. _this.rotationQuaternion = source.rotationQuaternion.clone();
  59407. }
  59408. _this.infiniteDistance = source.infiniteDistance;
  59409. _this.setPivotMatrix(source.getPivotMatrix());
  59410. _this.refreshBoundingInfo();
  59411. _this._syncSubMeshes();
  59412. return _this;
  59413. }
  59414. /**
  59415. * Returns the string "InstancedMesh".
  59416. */
  59417. InstancedMesh.prototype.getClassName = function () {
  59418. return "InstancedMesh";
  59419. };
  59420. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  59421. // Methods
  59422. get: function () {
  59423. return this._sourceMesh.receiveShadows;
  59424. },
  59425. enumerable: true,
  59426. configurable: true
  59427. });
  59428. Object.defineProperty(InstancedMesh.prototype, "material", {
  59429. get: function () {
  59430. return this._sourceMesh.material;
  59431. },
  59432. enumerable: true,
  59433. configurable: true
  59434. });
  59435. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  59436. get: function () {
  59437. return this._sourceMesh.visibility;
  59438. },
  59439. enumerable: true,
  59440. configurable: true
  59441. });
  59442. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  59443. get: function () {
  59444. return this._sourceMesh.skeleton;
  59445. },
  59446. enumerable: true,
  59447. configurable: true
  59448. });
  59449. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  59450. get: function () {
  59451. return this._sourceMesh.renderingGroupId;
  59452. },
  59453. set: function (value) {
  59454. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  59455. return;
  59456. }
  59457. //no-op with warning
  59458. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  59459. },
  59460. enumerable: true,
  59461. configurable: true
  59462. });
  59463. /**
  59464. * Returns the total number of vertices (integer).
  59465. */
  59466. InstancedMesh.prototype.getTotalVertices = function () {
  59467. return this._sourceMesh.getTotalVertices();
  59468. };
  59469. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  59470. get: function () {
  59471. return this._sourceMesh;
  59472. },
  59473. enumerable: true,
  59474. configurable: true
  59475. });
  59476. /**
  59477. * Is this node ready to be used/rendered
  59478. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  59479. * @return {boolean} is it ready
  59480. */
  59481. InstancedMesh.prototype.isReady = function (completeCheck) {
  59482. if (completeCheck === void 0) { completeCheck = false; }
  59483. return this._sourceMesh.isReady(completeCheck, true);
  59484. };
  59485. /**
  59486. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  59487. */
  59488. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  59489. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  59490. };
  59491. /**
  59492. * Sets the vertex data of the mesh geometry for the requested `kind`.
  59493. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  59494. * The `data` are either a numeric array either a Float32Array.
  59495. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  59496. * 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).
  59497. * Note that a new underlying VertexBuffer object is created each call.
  59498. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  59499. *
  59500. * Possible `kind` values :
  59501. * - BABYLON.VertexBuffer.PositionKind
  59502. * - BABYLON.VertexBuffer.UVKind
  59503. * - BABYLON.VertexBuffer.UV2Kind
  59504. * - BABYLON.VertexBuffer.UV3Kind
  59505. * - BABYLON.VertexBuffer.UV4Kind
  59506. * - BABYLON.VertexBuffer.UV5Kind
  59507. * - BABYLON.VertexBuffer.UV6Kind
  59508. * - BABYLON.VertexBuffer.ColorKind
  59509. * - BABYLON.VertexBuffer.MatricesIndicesKind
  59510. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  59511. * - BABYLON.VertexBuffer.MatricesWeightsKind
  59512. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  59513. *
  59514. * Returns the Mesh.
  59515. */
  59516. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  59517. if (this.sourceMesh) {
  59518. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  59519. }
  59520. return this.sourceMesh;
  59521. };
  59522. /**
  59523. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  59524. * If the mesh has no geometry, it is simply returned as it is.
  59525. * The `data` are either a numeric array either a Float32Array.
  59526. * No new underlying VertexBuffer object is created.
  59527. * 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.
  59528. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  59529. *
  59530. * Possible `kind` values :
  59531. * - BABYLON.VertexBuffer.PositionKind
  59532. * - BABYLON.VertexBuffer.UVKind
  59533. * - BABYLON.VertexBuffer.UV2Kind
  59534. * - BABYLON.VertexBuffer.UV3Kind
  59535. * - BABYLON.VertexBuffer.UV4Kind
  59536. * - BABYLON.VertexBuffer.UV5Kind
  59537. * - BABYLON.VertexBuffer.UV6Kind
  59538. * - BABYLON.VertexBuffer.ColorKind
  59539. * - BABYLON.VertexBuffer.MatricesIndicesKind
  59540. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  59541. * - BABYLON.VertexBuffer.MatricesWeightsKind
  59542. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  59543. *
  59544. * Returns the Mesh.
  59545. */
  59546. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  59547. if (this.sourceMesh) {
  59548. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  59549. }
  59550. return this.sourceMesh;
  59551. };
  59552. /**
  59553. * Sets the mesh indices.
  59554. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  59555. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  59556. * This method creates a new index buffer each call.
  59557. * Returns the Mesh.
  59558. */
  59559. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  59560. if (totalVertices === void 0) { totalVertices = null; }
  59561. if (this.sourceMesh) {
  59562. this.sourceMesh.setIndices(indices, totalVertices);
  59563. }
  59564. return this.sourceMesh;
  59565. };
  59566. /**
  59567. * Boolean : True if the mesh owns the requested kind of data.
  59568. */
  59569. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  59570. return this._sourceMesh.isVerticesDataPresent(kind);
  59571. };
  59572. /**
  59573. * Returns an array of indices (IndicesArray).
  59574. */
  59575. InstancedMesh.prototype.getIndices = function () {
  59576. return this._sourceMesh.getIndices();
  59577. };
  59578. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  59579. get: function () {
  59580. return this._sourceMesh._positions;
  59581. },
  59582. enumerable: true,
  59583. configurable: true
  59584. });
  59585. /**
  59586. * Sets a new updated BoundingInfo to the mesh.
  59587. * Returns the mesh.
  59588. */
  59589. InstancedMesh.prototype.refreshBoundingInfo = function () {
  59590. var meshBB = this._sourceMesh.getBoundingInfo();
  59591. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  59592. this._updateBoundingInfo();
  59593. return this;
  59594. };
  59595. /** @hidden */
  59596. InstancedMesh.prototype._preActivate = function () {
  59597. if (this._currentLOD) {
  59598. this._currentLOD._preActivate();
  59599. }
  59600. return this;
  59601. };
  59602. /** @hidden */
  59603. InstancedMesh.prototype._activate = function (renderId) {
  59604. if (this._currentLOD) {
  59605. this._currentLOD._registerInstanceForRenderId(this, renderId);
  59606. }
  59607. return this;
  59608. };
  59609. /**
  59610. * Returns the current associated LOD AbstractMesh.
  59611. */
  59612. InstancedMesh.prototype.getLOD = function (camera) {
  59613. if (!camera) {
  59614. return this;
  59615. }
  59616. var boundingInfo = this.getBoundingInfo();
  59617. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  59618. if (this._currentLOD === this.sourceMesh) {
  59619. return this;
  59620. }
  59621. return this._currentLOD;
  59622. };
  59623. /** @hidden */
  59624. InstancedMesh.prototype._syncSubMeshes = function () {
  59625. this.releaseSubMeshes();
  59626. if (this._sourceMesh.subMeshes) {
  59627. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  59628. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  59629. }
  59630. }
  59631. return this;
  59632. };
  59633. /** @hidden */
  59634. InstancedMesh.prototype._generatePointsArray = function () {
  59635. return this._sourceMesh._generatePointsArray();
  59636. };
  59637. /**
  59638. * Creates a new InstancedMesh from the current mesh.
  59639. * - name (string) : the cloned mesh name
  59640. * - newParent (optional Node) : the optional Node to parent the clone to.
  59641. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  59642. *
  59643. * Returns the clone.
  59644. */
  59645. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  59646. var result = this._sourceMesh.createInstance(name);
  59647. // Deep copy
  59648. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  59649. // Bounding info
  59650. this.refreshBoundingInfo();
  59651. // Parent
  59652. if (newParent) {
  59653. result.parent = newParent;
  59654. }
  59655. if (!doNotCloneChildren) {
  59656. // Children
  59657. for (var index = 0; index < this.getScene().meshes.length; index++) {
  59658. var mesh = this.getScene().meshes[index];
  59659. if (mesh.parent === this) {
  59660. mesh.clone(mesh.name, result);
  59661. }
  59662. }
  59663. }
  59664. result.computeWorldMatrix(true);
  59665. return result;
  59666. };
  59667. /**
  59668. * Disposes the InstancedMesh.
  59669. * Returns nothing.
  59670. */
  59671. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  59672. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  59673. // Remove from mesh
  59674. var index = this._sourceMesh.instances.indexOf(this);
  59675. this._sourceMesh.instances.splice(index, 1);
  59676. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  59677. };
  59678. return InstancedMesh;
  59679. }(BABYLON.AbstractMesh));
  59680. BABYLON.InstancedMesh = InstancedMesh;
  59681. })(BABYLON || (BABYLON = {}));
  59682. //# sourceMappingURL=babylon.instancedMesh.js.map
  59683. var BABYLON;
  59684. (function (BABYLON) {
  59685. var LinesMesh = /** @class */ (function (_super) {
  59686. __extends(LinesMesh, _super);
  59687. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  59688. if (scene === void 0) { scene = null; }
  59689. if (parent === void 0) { parent = null; }
  59690. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  59691. _this.useVertexColor = useVertexColor;
  59692. _this.useVertexAlpha = useVertexAlpha;
  59693. _this.color = new BABYLON.Color3(1, 1, 1);
  59694. _this.alpha = 1;
  59695. if (source) {
  59696. _this.color = source.color.clone();
  59697. _this.alpha = source.alpha;
  59698. _this.useVertexColor = source.useVertexColor;
  59699. _this.useVertexAlpha = source.useVertexAlpha;
  59700. }
  59701. _this._intersectionThreshold = 0.1;
  59702. var defines = [];
  59703. var options = {
  59704. attributes: [BABYLON.VertexBuffer.PositionKind],
  59705. uniforms: ["world", "viewProjection"],
  59706. needAlphaBlending: true,
  59707. defines: defines
  59708. };
  59709. if (useVertexAlpha === false) {
  59710. options.needAlphaBlending = false;
  59711. }
  59712. if (!useVertexColor) {
  59713. options.uniforms.push("color");
  59714. }
  59715. else {
  59716. options.defines.push("#define VERTEXCOLOR");
  59717. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  59718. }
  59719. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  59720. return _this;
  59721. }
  59722. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  59723. /**
  59724. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  59725. * This margin is expressed in world space coordinates, so its value may vary.
  59726. * Default value is 0.1
  59727. * @returns the intersection Threshold value.
  59728. */
  59729. get: function () {
  59730. return this._intersectionThreshold;
  59731. },
  59732. /**
  59733. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  59734. * This margin is expressed in world space coordinates, so its value may vary.
  59735. * @param value the new threshold to apply
  59736. */
  59737. set: function (value) {
  59738. if (this._intersectionThreshold === value) {
  59739. return;
  59740. }
  59741. this._intersectionThreshold = value;
  59742. if (this.geometry) {
  59743. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  59744. }
  59745. },
  59746. enumerable: true,
  59747. configurable: true
  59748. });
  59749. /**
  59750. * Returns the string "LineMesh"
  59751. */
  59752. LinesMesh.prototype.getClassName = function () {
  59753. return "LinesMesh";
  59754. };
  59755. Object.defineProperty(LinesMesh.prototype, "material", {
  59756. /**
  59757. * @hidden
  59758. */
  59759. get: function () {
  59760. return this._colorShader;
  59761. },
  59762. /**
  59763. * @hidden
  59764. */
  59765. set: function (value) {
  59766. // Do nothing
  59767. },
  59768. enumerable: true,
  59769. configurable: true
  59770. });
  59771. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  59772. /**
  59773. * @hidden
  59774. */
  59775. get: function () {
  59776. return false;
  59777. },
  59778. enumerable: true,
  59779. configurable: true
  59780. });
  59781. LinesMesh.prototype.createInstance = function (name) {
  59782. throw new Error("LinesMeshes do not support createInstance.");
  59783. };
  59784. /** @hidden */
  59785. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  59786. if (!this._geometry) {
  59787. return this;
  59788. }
  59789. // VBOs
  59790. this._geometry._bind(this._colorShader.getEffect());
  59791. // Color
  59792. if (!this.useVertexColor) {
  59793. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  59794. }
  59795. return this;
  59796. };
  59797. /** @hidden */
  59798. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  59799. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  59800. return this;
  59801. }
  59802. var engine = this.getScene().getEngine();
  59803. // Draw order
  59804. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  59805. return this;
  59806. };
  59807. LinesMesh.prototype.dispose = function (doNotRecurse) {
  59808. this._colorShader.dispose();
  59809. _super.prototype.dispose.call(this, doNotRecurse);
  59810. };
  59811. /**
  59812. * Returns a new LineMesh object cloned from the current one.
  59813. */
  59814. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  59815. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  59816. };
  59817. /**
  59818. * Enables the edge rendering mode on the mesh.
  59819. * This mode makes the mesh edges visible
  59820. * @param epsilon defines the maximal distance between two angles to detect a face
  59821. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  59822. * @returns the currentAbstractMesh
  59823. * @see https://www.babylonjs-playground.com/#19O9TU#0
  59824. */
  59825. LinesMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  59826. if (epsilon === void 0) { epsilon = 0.95; }
  59827. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  59828. this.disableEdgesRendering();
  59829. this._edgesRenderer = new BABYLON.LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  59830. return this;
  59831. };
  59832. return LinesMesh;
  59833. }(BABYLON.Mesh));
  59834. BABYLON.LinesMesh = LinesMesh;
  59835. })(BABYLON || (BABYLON = {}));
  59836. //# sourceMappingURL=babylon.linesMesh.js.map
  59837. var BABYLON;
  59838. (function (BABYLON) {
  59839. /**
  59840. * This class implement a typical dictionary using a string as key and the generic type T as value.
  59841. * The underlying implementation relies on an associative array to ensure the best performances.
  59842. * The value can be anything including 'null' but except 'undefined'
  59843. */
  59844. var StringDictionary = /** @class */ (function () {
  59845. function StringDictionary() {
  59846. this._count = 0;
  59847. this._data = {};
  59848. }
  59849. /**
  59850. * This will clear this dictionary and copy the content from the 'source' one.
  59851. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  59852. * @param source the dictionary to take the content from and copy to this dictionary
  59853. */
  59854. StringDictionary.prototype.copyFrom = function (source) {
  59855. var _this = this;
  59856. this.clear();
  59857. source.forEach(function (t, v) { return _this.add(t, v); });
  59858. };
  59859. /**
  59860. * Get a value based from its key
  59861. * @param key the given key to get the matching value from
  59862. * @return the value if found, otherwise undefined is returned
  59863. */
  59864. StringDictionary.prototype.get = function (key) {
  59865. var val = this._data[key];
  59866. if (val !== undefined) {
  59867. return val;
  59868. }
  59869. return undefined;
  59870. };
  59871. /**
  59872. * Get a value from its key or add it if it doesn't exist.
  59873. * This method will ensure you that a given key/data will be present in the dictionary.
  59874. * @param key the given key to get the matching value from
  59875. * @param factory the factory that will create the value if the key is not present in the dictionary.
  59876. * The factory will only be invoked if there's no data for the given key.
  59877. * @return the value corresponding to the key.
  59878. */
  59879. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  59880. var val = this.get(key);
  59881. if (val !== undefined) {
  59882. return val;
  59883. }
  59884. val = factory(key);
  59885. if (val) {
  59886. this.add(key, val);
  59887. }
  59888. return val;
  59889. };
  59890. /**
  59891. * Get a value from its key if present in the dictionary otherwise add it
  59892. * @param key the key to get the value from
  59893. * @param val if there's no such key/value pair in the dictionary add it with this value
  59894. * @return the value corresponding to the key
  59895. */
  59896. StringDictionary.prototype.getOrAdd = function (key, val) {
  59897. var curVal = this.get(key);
  59898. if (curVal !== undefined) {
  59899. return curVal;
  59900. }
  59901. this.add(key, val);
  59902. return val;
  59903. };
  59904. /**
  59905. * Check if there's a given key in the dictionary
  59906. * @param key the key to check for
  59907. * @return true if the key is present, false otherwise
  59908. */
  59909. StringDictionary.prototype.contains = function (key) {
  59910. return this._data[key] !== undefined;
  59911. };
  59912. /**
  59913. * Add a new key and its corresponding value
  59914. * @param key the key to add
  59915. * @param value the value corresponding to the key
  59916. * @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
  59917. */
  59918. StringDictionary.prototype.add = function (key, value) {
  59919. if (this._data[key] !== undefined) {
  59920. return false;
  59921. }
  59922. this._data[key] = value;
  59923. ++this._count;
  59924. return true;
  59925. };
  59926. StringDictionary.prototype.set = function (key, value) {
  59927. if (this._data[key] === undefined) {
  59928. return false;
  59929. }
  59930. this._data[key] = value;
  59931. return true;
  59932. };
  59933. /**
  59934. * Get the element of the given key and remove it from the dictionary
  59935. * @param key
  59936. */
  59937. StringDictionary.prototype.getAndRemove = function (key) {
  59938. var val = this.get(key);
  59939. if (val !== undefined) {
  59940. delete this._data[key];
  59941. --this._count;
  59942. return val;
  59943. }
  59944. return null;
  59945. };
  59946. /**
  59947. * Remove a key/value from the dictionary.
  59948. * @param key the key to remove
  59949. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  59950. */
  59951. StringDictionary.prototype.remove = function (key) {
  59952. if (this.contains(key)) {
  59953. delete this._data[key];
  59954. --this._count;
  59955. return true;
  59956. }
  59957. return false;
  59958. };
  59959. /**
  59960. * Clear the whole content of the dictionary
  59961. */
  59962. StringDictionary.prototype.clear = function () {
  59963. this._data = {};
  59964. this._count = 0;
  59965. };
  59966. Object.defineProperty(StringDictionary.prototype, "count", {
  59967. get: function () {
  59968. return this._count;
  59969. },
  59970. enumerable: true,
  59971. configurable: true
  59972. });
  59973. /**
  59974. * Execute a callback on each key/val of the dictionary.
  59975. * Note that you can remove any element in this dictionary in the callback implementation
  59976. * @param callback the callback to execute on a given key/value pair
  59977. */
  59978. StringDictionary.prototype.forEach = function (callback) {
  59979. for (var cur in this._data) {
  59980. var val = this._data[cur];
  59981. callback(cur, val);
  59982. }
  59983. };
  59984. /**
  59985. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  59986. * If the callback returns null or undefined the method will iterate to the next key/value pair
  59987. * Note that you can remove any element in this dictionary in the callback implementation
  59988. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  59989. */
  59990. StringDictionary.prototype.first = function (callback) {
  59991. for (var cur in this._data) {
  59992. var val = this._data[cur];
  59993. var res = callback(cur, val);
  59994. if (res) {
  59995. return res;
  59996. }
  59997. }
  59998. return null;
  59999. };
  60000. return StringDictionary;
  60001. }());
  60002. BABYLON.StringDictionary = StringDictionary;
  60003. })(BABYLON || (BABYLON = {}));
  60004. //# sourceMappingURL=babylon.stringDictionary.js.map
  60005. var BABYLON;
  60006. (function (BABYLON) {
  60007. var Debug;
  60008. (function (Debug) {
  60009. /**
  60010. * Class used to render a debug view of a given skeleton
  60011. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  60012. */
  60013. var SkeletonViewer = /** @class */ (function () {
  60014. /**
  60015. * Creates a new SkeletonViewer
  60016. * @param skeleton defines the skeleton to render
  60017. * @param mesh defines the mesh attached to the skeleton
  60018. * @param scene defines the hosting scene
  60019. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  60020. * @param renderingGroupId defines the rendering group id to use with the viewer
  60021. */
  60022. function SkeletonViewer(
  60023. /** defines the skeleton to render */
  60024. skeleton,
  60025. /** defines the mesh attached to the skeleton */
  60026. mesh, scene,
  60027. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  60028. autoUpdateBonesMatrices,
  60029. /** defines the rendering group id to use with the viewer */
  60030. renderingGroupId) {
  60031. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  60032. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  60033. this.skeleton = skeleton;
  60034. this.mesh = mesh;
  60035. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  60036. this.renderingGroupId = renderingGroupId;
  60037. /** Gets or sets the color used to render the skeleton */
  60038. this.color = BABYLON.Color3.White();
  60039. this._debugLines = new Array();
  60040. this._isEnabled = false;
  60041. this._scene = scene;
  60042. this.update();
  60043. this._renderFunction = this.update.bind(this);
  60044. }
  60045. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  60046. get: function () {
  60047. return this._isEnabled;
  60048. },
  60049. /** Gets or sets a boolean indicating if the viewer is enabled */
  60050. set: function (value) {
  60051. if (this._isEnabled === value) {
  60052. return;
  60053. }
  60054. this._isEnabled = value;
  60055. if (value) {
  60056. this._scene.registerBeforeRender(this._renderFunction);
  60057. }
  60058. else {
  60059. this._scene.unregisterBeforeRender(this._renderFunction);
  60060. }
  60061. },
  60062. enumerable: true,
  60063. configurable: true
  60064. });
  60065. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  60066. if (x === void 0) { x = 0; }
  60067. if (y === void 0) { y = 0; }
  60068. if (z === void 0) { z = 0; }
  60069. var tmat = BABYLON.Tmp.Matrix[0];
  60070. var parentBone = bone.getParent();
  60071. tmat.copyFrom(bone.getLocalMatrix());
  60072. if (x !== 0 || y !== 0 || z !== 0) {
  60073. var tmat2 = BABYLON.Tmp.Matrix[1];
  60074. BABYLON.Matrix.IdentityToRef(tmat2);
  60075. tmat2.m[12] = x;
  60076. tmat2.m[13] = y;
  60077. tmat2.m[14] = z;
  60078. tmat2.multiplyToRef(tmat, tmat);
  60079. }
  60080. if (parentBone) {
  60081. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  60082. }
  60083. tmat.multiplyToRef(meshMat, tmat);
  60084. position.x = tmat.m[12];
  60085. position.y = tmat.m[13];
  60086. position.z = tmat.m[14];
  60087. };
  60088. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  60089. var len = bones.length;
  60090. var meshPos = this.mesh.position;
  60091. for (var i = 0; i < len; i++) {
  60092. var bone = bones[i];
  60093. var points = this._debugLines[i];
  60094. if (!points) {
  60095. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60096. this._debugLines[i] = points;
  60097. }
  60098. this._getBonePosition(points[0], bone, meshMat);
  60099. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  60100. points[0].subtractInPlace(meshPos);
  60101. points[1].subtractInPlace(meshPos);
  60102. }
  60103. };
  60104. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  60105. var len = bones.length;
  60106. var boneNum = 0;
  60107. var meshPos = this.mesh.position;
  60108. for (var i = len - 1; i >= 0; i--) {
  60109. var childBone = bones[i];
  60110. var parentBone = childBone.getParent();
  60111. if (!parentBone) {
  60112. continue;
  60113. }
  60114. var points = this._debugLines[boneNum];
  60115. if (!points) {
  60116. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60117. this._debugLines[boneNum] = points;
  60118. }
  60119. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  60120. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  60121. points[0].subtractInPlace(meshPos);
  60122. points[1].subtractInPlace(meshPos);
  60123. boneNum++;
  60124. }
  60125. };
  60126. /** Update the viewer to sync with current skeleton state */
  60127. SkeletonViewer.prototype.update = function () {
  60128. if (this.autoUpdateBonesMatrices) {
  60129. this.skeleton.computeAbsoluteTransforms();
  60130. }
  60131. if (this.skeleton.bones[0].length === undefined) {
  60132. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  60133. }
  60134. else {
  60135. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  60136. }
  60137. if (!this._debugMesh) {
  60138. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  60139. this._debugMesh.renderingGroupId = this.renderingGroupId;
  60140. }
  60141. else {
  60142. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  60143. }
  60144. this._debugMesh.position.copyFrom(this.mesh.position);
  60145. this._debugMesh.color = this.color;
  60146. };
  60147. /** Release associated resources */
  60148. SkeletonViewer.prototype.dispose = function () {
  60149. if (this._debugMesh) {
  60150. this.isEnabled = false;
  60151. this._debugMesh.dispose();
  60152. this._debugMesh = null;
  60153. }
  60154. };
  60155. return SkeletonViewer;
  60156. }());
  60157. Debug.SkeletonViewer = SkeletonViewer;
  60158. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60159. })(BABYLON || (BABYLON = {}));
  60160. //# sourceMappingURL=babylon.skeletonViewer.js.map
  60161. /**
  60162. * Module Debug contains the (visual) components to debug a scene correctly
  60163. */
  60164. var BABYLON;
  60165. (function (BABYLON) {
  60166. var Debug;
  60167. (function (Debug) {
  60168. /**
  60169. * The Axes viewer will show 3 axes in a specific point in space
  60170. */
  60171. var AxesViewer = /** @class */ (function () {
  60172. /**
  60173. * Creates a new AxesViewer
  60174. * @param scene defines the hosting scene
  60175. * @param scaleLines defines a number used to scale line length (1 by default)
  60176. */
  60177. function AxesViewer(scene, scaleLines) {
  60178. if (scaleLines === void 0) { scaleLines = 1; }
  60179. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60180. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60181. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60182. /**
  60183. * Gets or sets a number used to scale line length
  60184. */
  60185. this.scaleLines = 1;
  60186. this.scaleLines = scaleLines;
  60187. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  60188. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  60189. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  60190. this._xmesh.renderingGroupId = 2;
  60191. this._ymesh.renderingGroupId = 2;
  60192. this._zmesh.renderingGroupId = 2;
  60193. this._xmesh.material.checkReadyOnlyOnce = true;
  60194. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  60195. this._ymesh.material.checkReadyOnlyOnce = true;
  60196. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  60197. this._zmesh.material.checkReadyOnlyOnce = true;
  60198. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  60199. this.scene = scene;
  60200. }
  60201. /**
  60202. * Force the viewer to update
  60203. * @param position defines the position of the viewer
  60204. * @param xaxis defines the x axis of the viewer
  60205. * @param yaxis defines the y axis of the viewer
  60206. * @param zaxis defines the z axis of the viewer
  60207. */
  60208. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  60209. var scaleLines = this.scaleLines;
  60210. if (this._xmesh) {
  60211. this._xmesh.position.copyFrom(position);
  60212. }
  60213. if (this._ymesh) {
  60214. this._ymesh.position.copyFrom(position);
  60215. }
  60216. if (this._zmesh) {
  60217. this._zmesh.position.copyFrom(position);
  60218. }
  60219. var point2 = this._xline[1];
  60220. point2.x = xaxis.x * scaleLines;
  60221. point2.y = xaxis.y * scaleLines;
  60222. point2.z = xaxis.z * scaleLines;
  60223. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  60224. point2 = this._yline[1];
  60225. point2.x = yaxis.x * scaleLines;
  60226. point2.y = yaxis.y * scaleLines;
  60227. point2.z = yaxis.z * scaleLines;
  60228. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  60229. point2 = this._zline[1];
  60230. point2.x = zaxis.x * scaleLines;
  60231. point2.y = zaxis.y * scaleLines;
  60232. point2.z = zaxis.z * scaleLines;
  60233. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  60234. };
  60235. /** Releases resources */
  60236. AxesViewer.prototype.dispose = function () {
  60237. if (this._xmesh) {
  60238. this._xmesh.dispose();
  60239. }
  60240. if (this._ymesh) {
  60241. this._ymesh.dispose();
  60242. }
  60243. if (this._zmesh) {
  60244. this._zmesh.dispose();
  60245. }
  60246. this._xmesh = null;
  60247. this._ymesh = null;
  60248. this._zmesh = null;
  60249. this.scene = null;
  60250. };
  60251. return AxesViewer;
  60252. }());
  60253. Debug.AxesViewer = AxesViewer;
  60254. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60255. })(BABYLON || (BABYLON = {}));
  60256. //# sourceMappingURL=babylon.axesViewer.js.map
  60257. var BABYLON;
  60258. (function (BABYLON) {
  60259. var Debug;
  60260. (function (Debug) {
  60261. /**
  60262. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  60263. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  60264. */
  60265. var BoneAxesViewer = /** @class */ (function (_super) {
  60266. __extends(BoneAxesViewer, _super);
  60267. /**
  60268. * Creates a new BoneAxesViewer
  60269. * @param scene defines the hosting scene
  60270. * @param bone defines the target bone
  60271. * @param mesh defines the target mesh
  60272. * @param scaleLines defines a scaling factor for line length (1 by default)
  60273. */
  60274. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  60275. if (scaleLines === void 0) { scaleLines = 1; }
  60276. var _this = _super.call(this, scene, scaleLines) || this;
  60277. /** Gets current position */
  60278. _this.pos = BABYLON.Vector3.Zero();
  60279. /** Gets direction of X axis */
  60280. _this.xaxis = BABYLON.Vector3.Zero();
  60281. /** Gets direction of Y axis */
  60282. _this.yaxis = BABYLON.Vector3.Zero();
  60283. /** Gets direction of Z axis */
  60284. _this.zaxis = BABYLON.Vector3.Zero();
  60285. _this.mesh = mesh;
  60286. _this.bone = bone;
  60287. return _this;
  60288. }
  60289. /**
  60290. * Force the viewer to update
  60291. */
  60292. BoneAxesViewer.prototype.update = function () {
  60293. if (!this.mesh || !this.bone) {
  60294. return;
  60295. }
  60296. var bone = this.bone;
  60297. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  60298. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  60299. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  60300. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  60301. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  60302. };
  60303. /** Releases resources */
  60304. BoneAxesViewer.prototype.dispose = function () {
  60305. if (this.mesh) {
  60306. this.mesh = null;
  60307. this.bone = null;
  60308. _super.prototype.dispose.call(this);
  60309. }
  60310. };
  60311. return BoneAxesViewer;
  60312. }(Debug.AxesViewer));
  60313. Debug.BoneAxesViewer = BoneAxesViewer;
  60314. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60315. })(BABYLON || (BABYLON = {}));
  60316. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  60317. var BABYLON;
  60318. (function (BABYLON) {
  60319. var RayHelper = /** @class */ (function () {
  60320. function RayHelper(ray) {
  60321. this.ray = ray;
  60322. }
  60323. RayHelper.CreateAndShow = function (ray, scene, color) {
  60324. var helper = new RayHelper(ray);
  60325. helper.show(scene, color);
  60326. return helper;
  60327. };
  60328. RayHelper.prototype.show = function (scene, color) {
  60329. if (!this._renderFunction && this.ray) {
  60330. var ray = this.ray;
  60331. this._renderFunction = this._render.bind(this);
  60332. this._scene = scene;
  60333. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  60334. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  60335. if (this._renderFunction) {
  60336. this._scene.registerBeforeRender(this._renderFunction);
  60337. }
  60338. }
  60339. if (color && this._renderLine) {
  60340. this._renderLine.color.copyFrom(color);
  60341. }
  60342. };
  60343. RayHelper.prototype.hide = function () {
  60344. if (this._renderFunction && this._scene) {
  60345. this._scene.unregisterBeforeRender(this._renderFunction);
  60346. this._scene = null;
  60347. this._renderFunction = null;
  60348. if (this._renderLine) {
  60349. this._renderLine.dispose();
  60350. this._renderLine = null;
  60351. }
  60352. this._renderPoints = [];
  60353. }
  60354. };
  60355. RayHelper.prototype._render = function () {
  60356. var ray = this.ray;
  60357. if (!ray) {
  60358. return;
  60359. }
  60360. var point = this._renderPoints[1];
  60361. var len = Math.min(ray.length, 1000000);
  60362. point.copyFrom(ray.direction);
  60363. point.scaleInPlace(len);
  60364. point.addInPlace(ray.origin);
  60365. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  60366. };
  60367. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  60368. this._attachedToMesh = mesh;
  60369. var ray = this.ray;
  60370. if (!ray) {
  60371. return;
  60372. }
  60373. if (!ray.direction) {
  60374. ray.direction = BABYLON.Vector3.Zero();
  60375. }
  60376. if (!ray.origin) {
  60377. ray.origin = BABYLON.Vector3.Zero();
  60378. }
  60379. if (length) {
  60380. ray.length = length;
  60381. }
  60382. if (!meshSpaceOrigin) {
  60383. meshSpaceOrigin = BABYLON.Vector3.Zero();
  60384. }
  60385. if (!meshSpaceDirection) {
  60386. // -1 so that this will work with Mesh.lookAt
  60387. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  60388. }
  60389. if (!this._meshSpaceDirection) {
  60390. this._meshSpaceDirection = meshSpaceDirection.clone();
  60391. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  60392. }
  60393. else {
  60394. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  60395. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  60396. }
  60397. if (!this._updateToMeshFunction) {
  60398. this._updateToMeshFunction = this._updateToMesh.bind(this);
  60399. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  60400. }
  60401. this._updateToMesh();
  60402. };
  60403. RayHelper.prototype.detachFromMesh = function () {
  60404. if (this._attachedToMesh) {
  60405. if (this._updateToMeshFunction) {
  60406. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  60407. }
  60408. this._attachedToMesh = null;
  60409. this._updateToMeshFunction = null;
  60410. }
  60411. };
  60412. RayHelper.prototype._updateToMesh = function () {
  60413. var ray = this.ray;
  60414. if (!this._attachedToMesh || !ray) {
  60415. return;
  60416. }
  60417. if (this._attachedToMesh._isDisposed) {
  60418. this.detachFromMesh();
  60419. return;
  60420. }
  60421. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  60422. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  60423. };
  60424. RayHelper.prototype.dispose = function () {
  60425. this.hide();
  60426. this.detachFromMesh();
  60427. this.ray = null;
  60428. };
  60429. return RayHelper;
  60430. }());
  60431. BABYLON.RayHelper = RayHelper;
  60432. })(BABYLON || (BABYLON = {}));
  60433. //# sourceMappingURL=babylon.rayHelper.js.map
  60434. var BABYLON;
  60435. (function (BABYLON) {
  60436. // load the inspector using require, if not present in the global namespace.
  60437. var DebugLayer = /** @class */ (function () {
  60438. function DebugLayer(scene) {
  60439. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  60440. this.onPropertyChangedObservable = new BABYLON.Observable();
  60441. this._scene = scene;
  60442. }
  60443. /** Creates the inspector window. */
  60444. DebugLayer.prototype._createInspector = function (config) {
  60445. if (config === void 0) { config = {}; }
  60446. var popup = config.popup || false;
  60447. var initialTab = config.initialTab || 0;
  60448. var parentElement = config.parentElement || null;
  60449. if (!this._inspector) {
  60450. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  60451. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  60452. } // else nothing to do as instance is already created
  60453. };
  60454. DebugLayer.prototype.isVisible = function () {
  60455. if (!this._inspector) {
  60456. return false;
  60457. }
  60458. return true;
  60459. };
  60460. DebugLayer.prototype.hide = function () {
  60461. if (this._inspector) {
  60462. try {
  60463. this._inspector.dispose();
  60464. }
  60465. catch (e) {
  60466. // If the inspector has been removed directly from the inspector tool
  60467. }
  60468. this.onPropertyChangedObservable.clear();
  60469. this._inspector = null;
  60470. }
  60471. };
  60472. /**
  60473. *
  60474. * Launch the debugLayer.
  60475. *
  60476. * initialTab:
  60477. * | Value | Tab Name |
  60478. * | --- | --- |
  60479. * | 0 | Scene |
  60480. * | 1 | Console |
  60481. * | 2 | Stats |
  60482. * | 3 | Textures |
  60483. * | 4 | Mesh |
  60484. * | 5 | Light |
  60485. * | 6 | Material |
  60486. * | 7 | GLTF |
  60487. * | 8 | GUI |
  60488. * | 9 | Physics |
  60489. * | 10 | Camera |
  60490. * | 11 | Audio |
  60491. *
  60492. */
  60493. DebugLayer.prototype.show = function (config) {
  60494. if (config === void 0) { config = {}; }
  60495. if (typeof this.BJSINSPECTOR == 'undefined') {
  60496. // Load inspector and add it to the DOM
  60497. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  60498. }
  60499. else {
  60500. // Otherwise creates the inspector
  60501. this._createInspector(config);
  60502. }
  60503. };
  60504. /**
  60505. * Gets the active tab
  60506. * @return the index of the active tab or -1 if the inspector is hidden
  60507. */
  60508. DebugLayer.prototype.getActiveTab = function () {
  60509. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  60510. };
  60511. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  60512. return DebugLayer;
  60513. }());
  60514. BABYLON.DebugLayer = DebugLayer;
  60515. })(BABYLON || (BABYLON = {}));
  60516. //# sourceMappingURL=babylon.debugLayer.js.map
  60517. var BABYLON;
  60518. (function (BABYLON) {
  60519. var Debug;
  60520. (function (Debug) {
  60521. /**
  60522. * Used to show the physics impostor around the specific mesh
  60523. */
  60524. var PhysicsViewer = /** @class */ (function () {
  60525. /**
  60526. * Creates a new PhysicsViewer
  60527. * @param scene defines the hosting scene
  60528. */
  60529. function PhysicsViewer(scene) {
  60530. /** @hidden */
  60531. this._impostors = [];
  60532. /** @hidden */
  60533. this._meshes = [];
  60534. /** @hidden */
  60535. this._numMeshes = 0;
  60536. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  60537. var physicEngine = this._scene.getPhysicsEngine();
  60538. if (physicEngine) {
  60539. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  60540. }
  60541. }
  60542. /** @hidden */
  60543. PhysicsViewer.prototype._updateDebugMeshes = function () {
  60544. var plugin = this._physicsEnginePlugin;
  60545. for (var i = 0; i < this._numMeshes; i++) {
  60546. var impostor = this._impostors[i];
  60547. if (!impostor) {
  60548. continue;
  60549. }
  60550. if (impostor.isDisposed) {
  60551. this.hideImpostor(this._impostors[i--]);
  60552. }
  60553. else {
  60554. var mesh = this._meshes[i];
  60555. if (mesh && plugin) {
  60556. plugin.syncMeshWithImpostor(mesh, impostor);
  60557. }
  60558. }
  60559. }
  60560. };
  60561. /**
  60562. * Renders a specified physic impostor
  60563. * @param impostor defines the impostor to render
  60564. */
  60565. PhysicsViewer.prototype.showImpostor = function (impostor) {
  60566. if (!this._scene) {
  60567. return;
  60568. }
  60569. for (var i = 0; i < this._numMeshes; i++) {
  60570. if (this._impostors[i] == impostor) {
  60571. return;
  60572. }
  60573. }
  60574. var debugMesh = this._getDebugMesh(impostor, this._scene);
  60575. if (debugMesh) {
  60576. this._impostors[this._numMeshes] = impostor;
  60577. this._meshes[this._numMeshes] = debugMesh;
  60578. if (this._numMeshes === 0) {
  60579. this._renderFunction = this._updateDebugMeshes.bind(this);
  60580. this._scene.registerBeforeRender(this._renderFunction);
  60581. }
  60582. this._numMeshes++;
  60583. }
  60584. };
  60585. /**
  60586. * Hides a specified physic impostor
  60587. * @param impostor defines the impostor to hide
  60588. */
  60589. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  60590. if (!impostor || !this._scene) {
  60591. return;
  60592. }
  60593. var removed = false;
  60594. for (var i = 0; i < this._numMeshes; i++) {
  60595. if (this._impostors[i] == impostor) {
  60596. var mesh = this._meshes[i];
  60597. if (!mesh) {
  60598. continue;
  60599. }
  60600. this._scene.removeMesh(mesh);
  60601. mesh.dispose();
  60602. this._numMeshes--;
  60603. if (this._numMeshes > 0) {
  60604. this._meshes[i] = this._meshes[this._numMeshes];
  60605. this._impostors[i] = this._impostors[this._numMeshes];
  60606. this._meshes[this._numMeshes] = null;
  60607. this._impostors[this._numMeshes] = null;
  60608. }
  60609. else {
  60610. this._meshes[0] = null;
  60611. this._impostors[0] = null;
  60612. }
  60613. removed = true;
  60614. break;
  60615. }
  60616. }
  60617. if (removed && this._numMeshes === 0) {
  60618. this._scene.unregisterBeforeRender(this._renderFunction);
  60619. }
  60620. };
  60621. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  60622. if (!this._debugMaterial) {
  60623. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  60624. this._debugMaterial.wireframe = true;
  60625. }
  60626. return this._debugMaterial;
  60627. };
  60628. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  60629. if (!this._debugBoxMesh) {
  60630. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  60631. this._debugBoxMesh.renderingGroupId = 1;
  60632. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  60633. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  60634. scene.removeMesh(this._debugBoxMesh);
  60635. }
  60636. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  60637. };
  60638. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  60639. if (!this._debugSphereMesh) {
  60640. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  60641. this._debugSphereMesh.renderingGroupId = 1;
  60642. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  60643. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  60644. scene.removeMesh(this._debugSphereMesh);
  60645. }
  60646. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  60647. };
  60648. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  60649. var mesh = null;
  60650. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  60651. mesh = this._getDebugBoxMesh(scene);
  60652. impostor.getBoxSizeToRef(mesh.scaling);
  60653. }
  60654. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  60655. mesh = this._getDebugSphereMesh(scene);
  60656. var radius = impostor.getRadius();
  60657. mesh.scaling.x = radius * 2;
  60658. mesh.scaling.y = radius * 2;
  60659. mesh.scaling.z = radius * 2;
  60660. }
  60661. return mesh;
  60662. };
  60663. /** Releases all resources */
  60664. PhysicsViewer.prototype.dispose = function () {
  60665. for (var i = 0; i < this._numMeshes; i++) {
  60666. this.hideImpostor(this._impostors[i]);
  60667. }
  60668. if (this._debugBoxMesh) {
  60669. this._debugBoxMesh.dispose();
  60670. }
  60671. if (this._debugSphereMesh) {
  60672. this._debugSphereMesh.dispose();
  60673. }
  60674. if (this._debugMaterial) {
  60675. this._debugMaterial.dispose();
  60676. }
  60677. this._impostors.length = 0;
  60678. this._scene = null;
  60679. this._physicsEnginePlugin = null;
  60680. };
  60681. return PhysicsViewer;
  60682. }());
  60683. Debug.PhysicsViewer = PhysicsViewer;
  60684. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60685. })(BABYLON || (BABYLON = {}));
  60686. //# sourceMappingURL=babylon.physicsViewer.js.map
  60687. var BABYLON;
  60688. (function (BABYLON) {
  60689. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  60690. get: function () {
  60691. return this._forceShowBoundingBoxes || false;
  60692. },
  60693. set: function (value) {
  60694. this._forceShowBoundingBoxes = value;
  60695. // Lazyly creates a BB renderer if needed.
  60696. if (value) {
  60697. this.getBoundingBoxRenderer();
  60698. }
  60699. },
  60700. enumerable: true,
  60701. configurable: true
  60702. });
  60703. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  60704. if (!this._boundingBoxRenderer) {
  60705. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  60706. }
  60707. return this._boundingBoxRenderer;
  60708. };
  60709. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  60710. get: function () {
  60711. return this._showBoundingBox || false;
  60712. },
  60713. set: function (value) {
  60714. this._showBoundingBox = value;
  60715. // Lazyly creates a BB renderer if needed.
  60716. if (value) {
  60717. this.getScene().getBoundingBoxRenderer();
  60718. }
  60719. },
  60720. enumerable: true,
  60721. configurable: true
  60722. });
  60723. var BoundingBoxRenderer = /** @class */ (function () {
  60724. function BoundingBoxRenderer(scene) {
  60725. /**
  60726. * The component name helpfull to identify the component in the list of scene components.
  60727. */
  60728. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  60729. this.frontColor = new BABYLON.Color3(1, 1, 1);
  60730. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  60731. this.showBackLines = true;
  60732. this.renderList = new BABYLON.SmartArray(32);
  60733. this._vertexBuffers = {};
  60734. this.scene = scene;
  60735. scene._addComponent(this);
  60736. }
  60737. /**
  60738. * Registers the component in a given scene
  60739. */
  60740. BoundingBoxRenderer.prototype.register = function () {
  60741. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  60742. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  60743. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  60744. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER, this, this.render);
  60745. };
  60746. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  60747. if (mesh.showSubMeshesBoundingBox) {
  60748. var boundingInfo = subMesh.getBoundingInfo();
  60749. if (boundingInfo !== null && boundingInfo !== undefined) {
  60750. this.renderList.push(boundingInfo.boundingBox);
  60751. }
  60752. }
  60753. };
  60754. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  60755. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  60756. var boundingInfo = sourceMesh.getBoundingInfo();
  60757. this.renderList.push(boundingInfo.boundingBox);
  60758. }
  60759. };
  60760. BoundingBoxRenderer.prototype._prepareRessources = function () {
  60761. if (this._colorShader) {
  60762. return;
  60763. }
  60764. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  60765. attributes: [BABYLON.VertexBuffer.PositionKind],
  60766. uniforms: ["world", "viewProjection", "color"]
  60767. });
  60768. var engine = this.scene.getEngine();
  60769. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  60770. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  60771. this._createIndexBuffer();
  60772. };
  60773. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  60774. var engine = this.scene.getEngine();
  60775. 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]);
  60776. };
  60777. /**
  60778. * Rebuilds the elements related to this component in case of
  60779. * context lost for instance.
  60780. */
  60781. BoundingBoxRenderer.prototype.rebuild = function () {
  60782. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  60783. if (vb) {
  60784. vb._rebuild();
  60785. }
  60786. this._createIndexBuffer();
  60787. };
  60788. BoundingBoxRenderer.prototype.reset = function () {
  60789. this.renderList.reset();
  60790. };
  60791. BoundingBoxRenderer.prototype.render = function () {
  60792. if (this.renderList.length === 0) {
  60793. return;
  60794. }
  60795. this._prepareRessources();
  60796. if (!this._colorShader.isReady()) {
  60797. return;
  60798. }
  60799. var engine = this.scene.getEngine();
  60800. engine.setDepthWrite(false);
  60801. this._colorShader._preBind();
  60802. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  60803. var boundingBox = this.renderList.data[boundingBoxIndex];
  60804. var min = boundingBox.minimum;
  60805. var max = boundingBox.maximum;
  60806. var diff = max.subtract(min);
  60807. var median = min.add(diff.scale(0.5));
  60808. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  60809. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  60810. .multiply(boundingBox.getWorldMatrix());
  60811. // VBOs
  60812. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  60813. if (this.showBackLines) {
  60814. // Back
  60815. engine.setDepthFunctionToGreaterOrEqual();
  60816. this.scene.resetCachedMaterial();
  60817. this._colorShader.setColor4("color", this.backColor.toColor4());
  60818. this._colorShader.bind(worldMatrix);
  60819. // Draw order
  60820. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  60821. }
  60822. // Front
  60823. engine.setDepthFunctionToLess();
  60824. this.scene.resetCachedMaterial();
  60825. this._colorShader.setColor4("color", this.frontColor.toColor4());
  60826. this._colorShader.bind(worldMatrix);
  60827. // Draw order
  60828. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  60829. }
  60830. this._colorShader.unbind();
  60831. engine.setDepthFunctionToLessOrEqual();
  60832. engine.setDepthWrite(true);
  60833. };
  60834. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  60835. this._prepareRessources();
  60836. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  60837. return;
  60838. }
  60839. var engine = this.scene.getEngine();
  60840. engine.setDepthWrite(false);
  60841. engine.setColorWrite(false);
  60842. this._colorShader._preBind();
  60843. var boundingBox = mesh._boundingInfo.boundingBox;
  60844. var min = boundingBox.minimum;
  60845. var max = boundingBox.maximum;
  60846. var diff = max.subtract(min);
  60847. var median = min.add(diff.scale(0.5));
  60848. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  60849. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  60850. .multiply(boundingBox.getWorldMatrix());
  60851. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  60852. engine.setDepthFunctionToLess();
  60853. this.scene.resetCachedMaterial();
  60854. this._colorShader.bind(worldMatrix);
  60855. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  60856. this._colorShader.unbind();
  60857. engine.setDepthFunctionToLessOrEqual();
  60858. engine.setDepthWrite(true);
  60859. engine.setColorWrite(true);
  60860. };
  60861. BoundingBoxRenderer.prototype.dispose = function () {
  60862. if (!this._colorShader) {
  60863. return;
  60864. }
  60865. this.renderList.dispose();
  60866. this._colorShader.dispose();
  60867. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  60868. if (buffer) {
  60869. buffer.dispose();
  60870. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  60871. }
  60872. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  60873. };
  60874. return BoundingBoxRenderer;
  60875. }());
  60876. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  60877. })(BABYLON || (BABYLON = {}));
  60878. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  60879. var BABYLON;
  60880. (function (BABYLON) {
  60881. BABYLON.Engine.prototype.createTransformFeedback = function () {
  60882. return this._gl.createTransformFeedback();
  60883. };
  60884. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  60885. this._gl.deleteTransformFeedback(value);
  60886. };
  60887. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  60888. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  60889. };
  60890. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  60891. if (usePoints === void 0) { usePoints = true; }
  60892. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  60893. };
  60894. BABYLON.Engine.prototype.endTransformFeedback = function () {
  60895. this._gl.endTransformFeedback();
  60896. };
  60897. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  60898. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  60899. };
  60900. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  60901. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  60902. };
  60903. })(BABYLON || (BABYLON = {}));
  60904. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  60905. var BABYLON;
  60906. (function (BABYLON) {
  60907. /**
  60908. * This represents a GPU particle system in Babylon
  60909. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  60910. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  60911. */
  60912. var GPUParticleSystem = /** @class */ (function (_super) {
  60913. __extends(GPUParticleSystem, _super);
  60914. /**
  60915. * Instantiates a GPU particle system.
  60916. * 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.
  60917. * @param name The name of the particle system
  60918. * @param options The options used to create the system
  60919. * @param scene The scene the particle system belongs to
  60920. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  60921. */
  60922. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  60923. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  60924. var _this = _super.call(this, name) || this;
  60925. /**
  60926. * The layer mask we are rendering the particles through.
  60927. */
  60928. _this.layerMask = 0x0FFFFFFF;
  60929. _this._accumulatedCount = 0;
  60930. _this._targetIndex = 0;
  60931. _this._currentRenderId = -1;
  60932. _this._started = false;
  60933. _this._stopped = false;
  60934. _this._timeDelta = 0;
  60935. _this._attributesStrideSize = 21;
  60936. _this._actualFrame = 0;
  60937. _this._rawTextureWidth = 256;
  60938. /**
  60939. * An event triggered when the system is disposed.
  60940. */
  60941. _this.onDisposeObservable = new BABYLON.Observable();
  60942. /**
  60943. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  60944. * to override the particles.
  60945. */
  60946. _this.forceDepthWrite = false;
  60947. _this._preWarmDone = false;
  60948. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  60949. // Setup the default processing configuration to the scene.
  60950. _this._attachImageProcessingConfiguration(null);
  60951. _this._engine = _this._scene.getEngine();
  60952. if (!options.randomTextureSize) {
  60953. delete options.randomTextureSize;
  60954. }
  60955. var fullOptions = __assign({ capacity: 50000, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
  60956. var optionsAsNumber = options;
  60957. if (isFinite(optionsAsNumber)) {
  60958. fullOptions.capacity = optionsAsNumber;
  60959. }
  60960. _this._capacity = fullOptions.capacity;
  60961. _this._activeCount = fullOptions.capacity;
  60962. _this._currentActiveCount = 0;
  60963. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  60964. _this._scene.particleSystems.push(_this);
  60965. _this._updateEffectOptions = {
  60966. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex"],
  60967. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  60968. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  60969. "angleRange", "radiusRange", "cellInfos", "noiseStrength"],
  60970. uniformBuffersNames: [],
  60971. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "noiseSampler"],
  60972. defines: "",
  60973. fallbacks: null,
  60974. onCompiled: null,
  60975. onError: null,
  60976. indexParameters: null,
  60977. maxSimultaneousLights: 0,
  60978. transformFeedbackVaryings: []
  60979. };
  60980. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  60981. // Random data
  60982. var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  60983. var d = [];
  60984. for (var i = 0; i < maxTextureSize; ++i) {
  60985. d.push(Math.random());
  60986. d.push(Math.random());
  60987. d.push(Math.random());
  60988. d.push(Math.random());
  60989. }
  60990. _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);
  60991. _this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60992. _this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60993. d = [];
  60994. for (var i = 0; i < maxTextureSize; ++i) {
  60995. d.push(Math.random());
  60996. d.push(Math.random());
  60997. d.push(Math.random());
  60998. d.push(Math.random());
  60999. }
  61000. _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);
  61001. _this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  61002. _this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  61003. _this._randomTextureSize = maxTextureSize;
  61004. return _this;
  61005. }
  61006. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  61007. /**
  61008. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  61009. */
  61010. get: function () {
  61011. if (!BABYLON.Engine.LastCreatedEngine) {
  61012. return false;
  61013. }
  61014. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  61015. },
  61016. enumerable: true,
  61017. configurable: true
  61018. });
  61019. /**
  61020. * Gets the maximum number of particles active at the same time.
  61021. * @returns The max number of active particles.
  61022. */
  61023. GPUParticleSystem.prototype.getCapacity = function () {
  61024. return this._capacity;
  61025. };
  61026. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  61027. /**
  61028. * Gets or set the number of active particles
  61029. */
  61030. get: function () {
  61031. return this._activeCount;
  61032. },
  61033. set: function (value) {
  61034. this._activeCount = Math.min(value, this._capacity);
  61035. },
  61036. enumerable: true,
  61037. configurable: true
  61038. });
  61039. /**
  61040. * Is this system ready to be used/rendered
  61041. * @return true if the system is ready
  61042. */
  61043. GPUParticleSystem.prototype.isReady = function () {
  61044. if (!this._updateEffect) {
  61045. this._recreateUpdateEffect();
  61046. this._recreateRenderEffect();
  61047. return false;
  61048. }
  61049. if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  61050. return false;
  61051. }
  61052. return true;
  61053. };
  61054. /**
  61055. * Gets if the system has been started. (Note: this will still be true after stop is called)
  61056. * @returns True if it has been started, otherwise false.
  61057. */
  61058. GPUParticleSystem.prototype.isStarted = function () {
  61059. return this._started;
  61060. };
  61061. /**
  61062. * Starts the particle system and begins to emit
  61063. * @param delay defines the delay in milliseconds before starting the system (0 by default)
  61064. */
  61065. GPUParticleSystem.prototype.start = function (delay) {
  61066. var _this = this;
  61067. if (delay === void 0) { delay = 0; }
  61068. if (delay) {
  61069. setTimeout(function () {
  61070. _this.start(0);
  61071. }, delay);
  61072. return;
  61073. }
  61074. this._started = true;
  61075. this._stopped = false;
  61076. this._preWarmDone = false;
  61077. };
  61078. /**
  61079. * Stops the particle system.
  61080. */
  61081. GPUParticleSystem.prototype.stop = function () {
  61082. this._stopped = true;
  61083. };
  61084. /**
  61085. * Remove all active particles
  61086. */
  61087. GPUParticleSystem.prototype.reset = function () {
  61088. this._releaseBuffers();
  61089. this._releaseVAOs();
  61090. this._currentActiveCount = 0;
  61091. this._targetIndex = 0;
  61092. };
  61093. /**
  61094. * Returns the string "GPUParticleSystem"
  61095. * @returns a string containing the class name
  61096. */
  61097. GPUParticleSystem.prototype.getClassName = function () {
  61098. return "GPUParticleSystem";
  61099. };
  61100. GPUParticleSystem.prototype._removeGradient = function (gradient, gradients, texture) {
  61101. if (!gradients) {
  61102. return this;
  61103. }
  61104. var index = 0;
  61105. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  61106. var valueGradient = gradients_1[_i];
  61107. if (valueGradient.gradient === gradient) {
  61108. gradients.splice(index, 1);
  61109. break;
  61110. }
  61111. index++;
  61112. }
  61113. if (texture) {
  61114. texture.dispose();
  61115. }
  61116. this._releaseBuffers();
  61117. return this;
  61118. };
  61119. /**
  61120. * Adds a new color gradient
  61121. * @param gradient defines the gradient to use (between 0 and 1)
  61122. * @param color defines the color to affect to the specified gradient
  61123. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  61124. * @returns the current particle system
  61125. */
  61126. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  61127. if (!this._colorGradients) {
  61128. this._colorGradients = [];
  61129. }
  61130. var colorGradient = new BABYLON.ColorGradient();
  61131. colorGradient.gradient = gradient;
  61132. colorGradient.color1 = color1;
  61133. this._colorGradients.push(colorGradient);
  61134. this._colorGradients.sort(function (a, b) {
  61135. if (a.gradient < b.gradient) {
  61136. return -1;
  61137. }
  61138. else if (a.gradient > b.gradient) {
  61139. return 1;
  61140. }
  61141. return 0;
  61142. });
  61143. if (this._colorGradientsTexture) {
  61144. this._colorGradientsTexture.dispose();
  61145. this._colorGradientsTexture = null;
  61146. }
  61147. this._releaseBuffers();
  61148. return this;
  61149. };
  61150. /**
  61151. * Remove a specific color gradient
  61152. * @param gradient defines the gradient to remove
  61153. * @returns the current particle system
  61154. */
  61155. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  61156. this._removeGradient(gradient, this._colorGradients, this._colorGradientsTexture);
  61157. this._colorGradientsTexture = null;
  61158. return this;
  61159. };
  61160. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  61161. var valueGradient = new BABYLON.FactorGradient();
  61162. valueGradient.gradient = gradient;
  61163. valueGradient.factor1 = factor;
  61164. factorGradients.push(valueGradient);
  61165. factorGradients.sort(function (a, b) {
  61166. if (a.gradient < b.gradient) {
  61167. return -1;
  61168. }
  61169. else if (a.gradient > b.gradient) {
  61170. return 1;
  61171. }
  61172. return 0;
  61173. });
  61174. this._releaseBuffers();
  61175. };
  61176. /**
  61177. * Adds a new size gradient
  61178. * @param gradient defines the gradient to use (between 0 and 1)
  61179. * @param factor defines the size factor to affect to the specified gradient
  61180. * @returns the current particle system
  61181. */
  61182. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  61183. if (!this._sizeGradients) {
  61184. this._sizeGradients = [];
  61185. }
  61186. this._addFactorGradient(this._sizeGradients, gradient, factor);
  61187. if (this._sizeGradientsTexture) {
  61188. this._sizeGradientsTexture.dispose();
  61189. this._sizeGradientsTexture = null;
  61190. }
  61191. this._releaseBuffers();
  61192. return this;
  61193. };
  61194. /**
  61195. * Remove a specific size gradient
  61196. * @param gradient defines the gradient to remove
  61197. * @returns the current particle system
  61198. */
  61199. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  61200. this._removeGradient(gradient, this._sizeGradients, this._sizeGradientsTexture);
  61201. this._sizeGradientsTexture = null;
  61202. return this;
  61203. };
  61204. /**
  61205. * Adds a new angular speed gradient
  61206. * @param gradient defines the gradient to use (between 0 and 1)
  61207. * @param factor defines the angular speed to affect to the specified gradient
  61208. * @returns the current particle system
  61209. */
  61210. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  61211. if (!this._angularSpeedGradients) {
  61212. this._angularSpeedGradients = [];
  61213. }
  61214. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  61215. if (this._angularSpeedGradientsTexture) {
  61216. this._angularSpeedGradientsTexture.dispose();
  61217. this._angularSpeedGradientsTexture = null;
  61218. }
  61219. this._releaseBuffers();
  61220. return this;
  61221. };
  61222. /**
  61223. * Remove a specific angular speed gradient
  61224. * @param gradient defines the gradient to remove
  61225. * @returns the current particle system
  61226. */
  61227. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  61228. this._removeGradient(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  61229. this._angularSpeedGradientsTexture = null;
  61230. return this;
  61231. };
  61232. /**
  61233. * Adds a new velocity gradient
  61234. * @param gradient defines the gradient to use (between 0 and 1)
  61235. * @param factor defines the velocity to affect to the specified gradient
  61236. * @returns the current particle system
  61237. */
  61238. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  61239. if (!this._velocityGradients) {
  61240. this._velocityGradients = [];
  61241. }
  61242. this._addFactorGradient(this._velocityGradients, gradient, factor);
  61243. if (this._velocityGradientsTexture) {
  61244. this._velocityGradientsTexture.dispose();
  61245. this._velocityGradientsTexture = null;
  61246. }
  61247. this._releaseBuffers();
  61248. return this;
  61249. };
  61250. /**
  61251. * Remove a specific velocity gradient
  61252. * @param gradient defines the gradient to remove
  61253. * @returns the current particle system
  61254. */
  61255. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  61256. this._removeGradient(gradient, this._velocityGradients, this._velocityGradientsTexture);
  61257. this._velocityGradientsTexture = null;
  61258. return this;
  61259. };
  61260. /**
  61261. * Adds a new limit velocity gradient
  61262. * @param gradient defines the gradient to use (between 0 and 1)
  61263. * @param factor defines the limit velocity value to affect to the specified gradient
  61264. * @returns the current particle system
  61265. */
  61266. GPUParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor) {
  61267. if (!this._limitVelocityGradients) {
  61268. this._limitVelocityGradients = [];
  61269. }
  61270. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  61271. if (this._limitVelocityGradientsTexture) {
  61272. this._limitVelocityGradientsTexture.dispose();
  61273. this._limitVelocityGradientsTexture = null;
  61274. }
  61275. this._releaseBuffers();
  61276. return this;
  61277. };
  61278. /**
  61279. * Remove a specific limit velocity gradient
  61280. * @param gradient defines the gradient to remove
  61281. * @returns the current particle system
  61282. */
  61283. GPUParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  61284. this._removeGradient(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  61285. this._limitVelocityGradientsTexture = null;
  61286. return this;
  61287. };
  61288. /**
  61289. * Adds a new drag gradient
  61290. * @param gradient defines the gradient to use (between 0 and 1)
  61291. * @param factor defines the drag value to affect to the specified gradient
  61292. * @returns the current particle system
  61293. */
  61294. GPUParticleSystem.prototype.addDragGradient = function (gradient, factor) {
  61295. if (!this._dragGradients) {
  61296. this._dragGradients = [];
  61297. }
  61298. this._addFactorGradient(this._dragGradients, gradient, factor);
  61299. if (this._dragGradientsTexture) {
  61300. this._dragGradientsTexture.dispose();
  61301. this._dragGradientsTexture = null;
  61302. }
  61303. this._releaseBuffers();
  61304. return this;
  61305. };
  61306. /**
  61307. * Remove a specific drag gradient
  61308. * @param gradient defines the gradient to remove
  61309. * @returns the current particle system
  61310. */
  61311. GPUParticleSystem.prototype.removeDragGradient = function (gradient) {
  61312. this._removeGradient(gradient, this._dragGradients, this._dragGradientsTexture);
  61313. this._dragGradientsTexture = null;
  61314. return this;
  61315. };
  61316. /**
  61317. * Not supported by GPUParticleSystem
  61318. * @param gradient defines the gradient to use (between 0 and 1)
  61319. * @param factor defines the emit rate value to affect to the specified gradient
  61320. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  61321. * @returns the current particle system
  61322. */
  61323. GPUParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  61324. // Do nothing as emit rate is not supported by GPUParticleSystem
  61325. return this;
  61326. };
  61327. /**
  61328. * Not supported by GPUParticleSystem
  61329. * @param gradient defines the gradient to remove
  61330. * @returns the current particle system
  61331. */
  61332. GPUParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  61333. // Do nothing as emit rate is not supported by GPUParticleSystem
  61334. return this;
  61335. };
  61336. GPUParticleSystem.prototype._reset = function () {
  61337. this._releaseBuffers();
  61338. };
  61339. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  61340. var updateVertexBuffers = {};
  61341. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  61342. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  61343. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  61344. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  61345. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  61346. var offset = 12;
  61347. if (!this._colorGradientsTexture) {
  61348. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  61349. offset += 4;
  61350. }
  61351. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  61352. offset += 3;
  61353. if (!this._isBillboardBased) {
  61354. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  61355. offset += 3;
  61356. }
  61357. if (this._angularSpeedGradientsTexture) {
  61358. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  61359. offset += 1;
  61360. }
  61361. else {
  61362. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  61363. offset += 2;
  61364. }
  61365. if (this._isAnimationSheetEnabled) {
  61366. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  61367. offset += 1;
  61368. }
  61369. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  61370. this._engine.bindArrayBuffer(null);
  61371. return vao;
  61372. };
  61373. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  61374. var renderVertexBuffers = {};
  61375. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  61376. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  61377. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  61378. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  61379. var offset = 12;
  61380. if (!this._colorGradientsTexture) {
  61381. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  61382. offset += 4;
  61383. }
  61384. offset += 3; // Direction
  61385. if (!this._isBillboardBased) {
  61386. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  61387. offset += 3;
  61388. }
  61389. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  61390. if (this._angularSpeedGradientsTexture) {
  61391. offset++;
  61392. }
  61393. else {
  61394. offset += 2;
  61395. }
  61396. if (this._isAnimationSheetEnabled) {
  61397. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  61398. offset += 1;
  61399. }
  61400. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  61401. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  61402. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  61403. this._engine.bindArrayBuffer(null);
  61404. return vao;
  61405. };
  61406. GPUParticleSystem.prototype._initialize = function (force) {
  61407. if (force === void 0) { force = false; }
  61408. if (this._buffer0 && !force) {
  61409. return;
  61410. }
  61411. var engine = this._scene.getEngine();
  61412. var data = new Array();
  61413. if (!this.isBillboardBased) {
  61414. this._attributesStrideSize += 3;
  61415. }
  61416. if (this._colorGradientsTexture) {
  61417. this._attributesStrideSize -= 4;
  61418. }
  61419. if (this._angularSpeedGradientsTexture) {
  61420. this._attributesStrideSize -= 1;
  61421. }
  61422. if (this._isAnimationSheetEnabled) {
  61423. this._attributesStrideSize += 1;
  61424. }
  61425. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  61426. // position
  61427. data.push(0.0);
  61428. data.push(0.0);
  61429. data.push(0.0);
  61430. // Age and life
  61431. data.push(0.0); // create the particle as a dead one to create a new one at start
  61432. data.push(0.0);
  61433. // Seed
  61434. data.push(Math.random());
  61435. data.push(Math.random());
  61436. data.push(Math.random());
  61437. data.push(Math.random());
  61438. // Size
  61439. data.push(0.0);
  61440. data.push(0.0);
  61441. data.push(0.0);
  61442. if (!this._colorGradientsTexture) {
  61443. // color
  61444. data.push(0.0);
  61445. data.push(0.0);
  61446. data.push(0.0);
  61447. data.push(0.0);
  61448. }
  61449. // direction
  61450. data.push(0.0);
  61451. data.push(0.0);
  61452. data.push(0.0);
  61453. if (!this.isBillboardBased) {
  61454. // initialDirection
  61455. data.push(0.0);
  61456. data.push(0.0);
  61457. data.push(0.0);
  61458. }
  61459. // angle
  61460. data.push(0.0);
  61461. if (!this._angularSpeedGradientsTexture) {
  61462. data.push(0.0);
  61463. }
  61464. if (this._isAnimationSheetEnabled) {
  61465. data.push(0.0);
  61466. }
  61467. }
  61468. // Sprite data
  61469. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  61470. -0.5, 0.5, 0, 1,
  61471. -0.5, -0.5, 0, 0,
  61472. 0.5, -0.5, 1, 0]);
  61473. // Buffers
  61474. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  61475. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  61476. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  61477. // Update VAO
  61478. this._updateVAO = [];
  61479. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  61480. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  61481. // Render VAO
  61482. this._renderVAO = [];
  61483. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  61484. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  61485. // Links
  61486. this._sourceBuffer = this._buffer0;
  61487. this._targetBuffer = this._buffer1;
  61488. };
  61489. /** @hidden */
  61490. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  61491. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  61492. if (this._isBillboardBased) {
  61493. defines += "\n#define BILLBOARD";
  61494. }
  61495. if (this._colorGradientsTexture) {
  61496. defines += "\n#define COLORGRADIENTS";
  61497. }
  61498. if (this._sizeGradientsTexture) {
  61499. defines += "\n#define SIZEGRADIENTS";
  61500. }
  61501. if (this._angularSpeedGradientsTexture) {
  61502. defines += "\n#define ANGULARSPEEDGRADIENTS";
  61503. }
  61504. if (this._velocityGradientsTexture) {
  61505. defines += "\n#define VELOCITYGRADIENTS";
  61506. }
  61507. if (this.isAnimationSheetEnabled) {
  61508. defines += "\n#define ANIMATESHEET";
  61509. }
  61510. if (this.noiseTexture) {
  61511. defines += "\n#define NOISE";
  61512. }
  61513. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  61514. return;
  61515. }
  61516. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  61517. if (!this._colorGradientsTexture) {
  61518. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  61519. }
  61520. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  61521. if (!this._isBillboardBased) {
  61522. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  61523. }
  61524. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  61525. if (this.isAnimationSheetEnabled) {
  61526. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  61527. }
  61528. this._updateEffectOptions.defines = defines;
  61529. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  61530. };
  61531. /** @hidden */
  61532. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  61533. var defines = "";
  61534. if (this._scene.clipPlane) {
  61535. defines = "\n#define CLIPPLANE";
  61536. }
  61537. if (this._scene.clipPlane2) {
  61538. defines = "\n#define CLIPPLANE2";
  61539. }
  61540. if (this._scene.clipPlane3) {
  61541. defines = "\n#define CLIPPLANE3";
  61542. }
  61543. if (this._scene.clipPlane4) {
  61544. defines = "\n#define CLIPPLANE4";
  61545. }
  61546. if (this._isBillboardBased) {
  61547. defines += "\n#define BILLBOARD";
  61548. switch (this.billboardMode) {
  61549. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  61550. defines += "\n#define BILLBOARDY";
  61551. break;
  61552. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  61553. default:
  61554. break;
  61555. }
  61556. }
  61557. if (this._colorGradientsTexture) {
  61558. defines += "\n#define COLORGRADIENTS";
  61559. }
  61560. if (this.isAnimationSheetEnabled) {
  61561. defines += "\n#define ANIMATESHEET";
  61562. }
  61563. if (this._imageProcessingConfiguration) {
  61564. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  61565. defines += "\n" + this._imageProcessingConfigurationDefines.toString();
  61566. }
  61567. if (this._renderEffect && this._renderEffect.defines === defines) {
  61568. return;
  61569. }
  61570. var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "sheetInfos", "translationPivot", "eyePosition"];
  61571. var samplers = ["textureSampler", "colorGradientSampler"];
  61572. if (BABYLON.ImageProcessingConfiguration) {
  61573. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  61574. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  61575. }
  61576. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "initialDirection", "angle", "cellIndex"], uniforms, samplers, this._scene.getEngine(), defines);
  61577. };
  61578. /**
  61579. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  61580. * @param preWarm defines if we are in the pre-warmimg phase
  61581. */
  61582. GPUParticleSystem.prototype.animate = function (preWarm) {
  61583. if (preWarm === void 0) { preWarm = false; }
  61584. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  61585. this._actualFrame += this._timeDelta;
  61586. if (!this._stopped) {
  61587. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  61588. this.stop();
  61589. }
  61590. }
  61591. };
  61592. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  61593. var texture = this[textureName];
  61594. if (!factorGradients || !factorGradients.length || texture) {
  61595. return;
  61596. }
  61597. var data = new Float32Array(this._rawTextureWidth);
  61598. for (var x = 0; x < this._rawTextureWidth; x++) {
  61599. var ratio = x / this._rawTextureWidth;
  61600. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  61601. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  61602. });
  61603. }
  61604. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  61605. };
  61606. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  61607. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  61608. };
  61609. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  61610. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  61611. };
  61612. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  61613. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  61614. };
  61615. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  61616. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  61617. return;
  61618. }
  61619. var data = new Uint8Array(this._rawTextureWidth * 4);
  61620. var tmpColor = BABYLON.Tmp.Color4[0];
  61621. for (var x = 0; x < this._rawTextureWidth; x++) {
  61622. var ratio = x / this._rawTextureWidth;
  61623. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  61624. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  61625. data[x * 4] = tmpColor.r * 255;
  61626. data[x * 4 + 1] = tmpColor.g * 255;
  61627. data[x * 4 + 2] = tmpColor.b * 255;
  61628. data[x * 4 + 3] = tmpColor.a * 255;
  61629. });
  61630. }
  61631. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  61632. };
  61633. /**
  61634. * Renders the particle system in its current state
  61635. * @param preWarm defines if the system should only update the particles but not render them
  61636. * @returns the current number of particles
  61637. */
  61638. GPUParticleSystem.prototype.render = function (preWarm) {
  61639. if (preWarm === void 0) { preWarm = false; }
  61640. if (!this._started) {
  61641. return 0;
  61642. }
  61643. this._createColorGradientTexture();
  61644. this._createSizeGradientTexture();
  61645. this._createAngularSpeedGradientTexture();
  61646. this._createVelocityGradientTexture();
  61647. this._recreateUpdateEffect();
  61648. this._recreateRenderEffect();
  61649. if (!this.isReady()) {
  61650. return 0;
  61651. }
  61652. if (!preWarm) {
  61653. if (!this._preWarmDone && this.preWarmCycles) {
  61654. for (var index = 0; index < this.preWarmCycles; index++) {
  61655. this.animate(true);
  61656. this.render(true);
  61657. }
  61658. this._preWarmDone = true;
  61659. }
  61660. if (this._currentRenderId === this._scene.getRenderId()) {
  61661. return 0;
  61662. }
  61663. this._currentRenderId = this._scene.getRenderId();
  61664. }
  61665. // Get everything ready to render
  61666. this._initialize();
  61667. this._accumulatedCount += this.emitRate * this._timeDelta;
  61668. if (this._accumulatedCount > 1) {
  61669. var intPart = this._accumulatedCount | 0;
  61670. this._accumulatedCount -= intPart;
  61671. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  61672. }
  61673. if (!this._currentActiveCount) {
  61674. return 0;
  61675. }
  61676. // Enable update effect
  61677. this._engine.enableEffect(this._updateEffect);
  61678. this._engine.setState(false);
  61679. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  61680. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  61681. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  61682. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  61683. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  61684. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  61685. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  61686. if (!this._colorGradientsTexture) {
  61687. this._updateEffect.setDirectColor4("color1", this.color1);
  61688. this._updateEffect.setDirectColor4("color2", this.color2);
  61689. }
  61690. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  61691. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  61692. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  61693. this._updateEffect.setVector3("gravity", this.gravity);
  61694. if (this._sizeGradientsTexture) {
  61695. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  61696. }
  61697. if (this._angularSpeedGradientsTexture) {
  61698. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  61699. }
  61700. if (this._velocityGradientsTexture) {
  61701. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  61702. }
  61703. if (this.particleEmitterType) {
  61704. this.particleEmitterType.applyToShader(this._updateEffect);
  61705. }
  61706. if (this._isAnimationSheetEnabled) {
  61707. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  61708. }
  61709. if (this.noiseTexture) {
  61710. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  61711. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  61712. }
  61713. var emitterWM;
  61714. if (this.emitter.position) {
  61715. var emitterMesh = this.emitter;
  61716. emitterWM = emitterMesh.getWorldMatrix();
  61717. }
  61718. else {
  61719. var emitterPosition = this.emitter;
  61720. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  61721. }
  61722. this._updateEffect.setMatrix("emitterWM", emitterWM);
  61723. // Bind source VAO
  61724. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  61725. // Update
  61726. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  61727. this._engine.setRasterizerState(false);
  61728. this._engine.beginTransformFeedback(true);
  61729. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  61730. this._engine.endTransformFeedback();
  61731. this._engine.setRasterizerState(true);
  61732. this._engine.bindTransformFeedbackBuffer(null);
  61733. if (!preWarm) {
  61734. // Enable render effect
  61735. this._engine.enableEffect(this._renderEffect);
  61736. var viewMatrix = this._scene.getViewMatrix();
  61737. this._renderEffect.setMatrix("view", viewMatrix);
  61738. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  61739. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  61740. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  61741. if (this._colorGradientsTexture) {
  61742. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  61743. }
  61744. else {
  61745. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  61746. }
  61747. if (this._isAnimationSheetEnabled && this.particleTexture) {
  61748. var baseSize = this.particleTexture.getBaseSize();
  61749. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  61750. }
  61751. if (this._isBillboardBased) {
  61752. var camera = this._scene.activeCamera;
  61753. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  61754. }
  61755. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  61756. var invView = viewMatrix.clone();
  61757. invView.invert();
  61758. this._renderEffect.setMatrix("invView", invView);
  61759. BABYLON.MaterialHelper.BindClipPlane(this._renderEffect, this._scene);
  61760. }
  61761. // image processing
  61762. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  61763. this._imageProcessingConfiguration.bind(this._renderEffect);
  61764. }
  61765. // Draw order
  61766. switch (this.blendMode) {
  61767. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  61768. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  61769. break;
  61770. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  61771. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  61772. break;
  61773. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  61774. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  61775. break;
  61776. case BABYLON.ParticleSystem.BLENDMODE_MULTIPLY:
  61777. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  61778. break;
  61779. }
  61780. if (this.forceDepthWrite) {
  61781. this._engine.setDepthWrite(true);
  61782. }
  61783. // Bind source VAO
  61784. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  61785. // Render
  61786. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  61787. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  61788. }
  61789. // Switch VAOs
  61790. this._targetIndex++;
  61791. if (this._targetIndex === 2) {
  61792. this._targetIndex = 0;
  61793. }
  61794. // Switch buffers
  61795. var tmpBuffer = this._sourceBuffer;
  61796. this._sourceBuffer = this._targetBuffer;
  61797. this._targetBuffer = tmpBuffer;
  61798. return this._currentActiveCount;
  61799. };
  61800. /**
  61801. * Rebuilds the particle system
  61802. */
  61803. GPUParticleSystem.prototype.rebuild = function () {
  61804. this._initialize(true);
  61805. };
  61806. GPUParticleSystem.prototype._releaseBuffers = function () {
  61807. if (this._buffer0) {
  61808. this._buffer0.dispose();
  61809. this._buffer0 = null;
  61810. }
  61811. if (this._buffer1) {
  61812. this._buffer1.dispose();
  61813. this._buffer1 = null;
  61814. }
  61815. if (this._spriteBuffer) {
  61816. this._spriteBuffer.dispose();
  61817. this._spriteBuffer = null;
  61818. }
  61819. };
  61820. GPUParticleSystem.prototype._releaseVAOs = function () {
  61821. if (!this._updateVAO) {
  61822. return;
  61823. }
  61824. for (var index = 0; index < this._updateVAO.length; index++) {
  61825. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  61826. }
  61827. this._updateVAO = [];
  61828. for (var index = 0; index < this._renderVAO.length; index++) {
  61829. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  61830. }
  61831. this._renderVAO = [];
  61832. };
  61833. /**
  61834. * Disposes the particle system and free the associated resources
  61835. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  61836. */
  61837. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  61838. if (disposeTexture === void 0) { disposeTexture = true; }
  61839. var index = this._scene.particleSystems.indexOf(this);
  61840. if (index > -1) {
  61841. this._scene.particleSystems.splice(index, 1);
  61842. }
  61843. this._releaseBuffers();
  61844. this._releaseVAOs();
  61845. if (this._colorGradientsTexture) {
  61846. this._colorGradientsTexture.dispose();
  61847. this._colorGradientsTexture = null;
  61848. }
  61849. if (this._sizeGradientsTexture) {
  61850. this._sizeGradientsTexture.dispose();
  61851. this._sizeGradientsTexture = null;
  61852. }
  61853. if (this._angularSpeedGradientsTexture) {
  61854. this._angularSpeedGradientsTexture.dispose();
  61855. this._angularSpeedGradientsTexture = null;
  61856. }
  61857. if (this._velocityGradientsTexture) {
  61858. this._velocityGradientsTexture.dispose();
  61859. this._velocityGradientsTexture = null;
  61860. }
  61861. if (this._limitVelocityGradientsTexture) {
  61862. this._limitVelocityGradientsTexture.dispose();
  61863. this._limitVelocityGradientsTexture = null;
  61864. }
  61865. if (this._randomTexture) {
  61866. this._randomTexture.dispose();
  61867. this._randomTexture = null;
  61868. }
  61869. if (this._randomTexture2) {
  61870. this._randomTexture2.dispose();
  61871. this._randomTexture2 = null;
  61872. }
  61873. if (disposeTexture && this.particleTexture) {
  61874. this.particleTexture.dispose();
  61875. this.particleTexture = null;
  61876. }
  61877. if (disposeTexture && this.noiseTexture) {
  61878. this.noiseTexture.dispose();
  61879. this.noiseTexture = null;
  61880. }
  61881. // Callback
  61882. this.onDisposeObservable.notifyObservers(this);
  61883. this.onDisposeObservable.clear();
  61884. };
  61885. /**
  61886. * Clones the particle system.
  61887. * @param name The name of the cloned object
  61888. * @param newEmitter The new emitter to use
  61889. * @returns the cloned particle system
  61890. */
  61891. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  61892. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  61893. BABYLON.Tools.DeepCopy(this, result);
  61894. if (newEmitter === undefined) {
  61895. newEmitter = this.emitter;
  61896. }
  61897. result.emitter = newEmitter;
  61898. if (this.particleTexture) {
  61899. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  61900. }
  61901. return result;
  61902. };
  61903. /**
  61904. * Serializes the particle system to a JSON object.
  61905. * @returns the JSON object
  61906. */
  61907. GPUParticleSystem.prototype.serialize = function () {
  61908. var serializationObject = {};
  61909. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  61910. serializationObject.activeParticleCount = this.activeParticleCount;
  61911. return serializationObject;
  61912. };
  61913. /**
  61914. * Parses a JSON object to create a GPU particle system.
  61915. * @param parsedParticleSystem The JSON object to parse
  61916. * @param scene The scene to create the particle system in
  61917. * @param rootUrl The root url to use to load external dependencies like texture
  61918. * @returns the parsed GPU particle system
  61919. */
  61920. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  61921. var name = parsedParticleSystem.name;
  61922. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  61923. if (parsedParticleSystem.activeParticleCount) {
  61924. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  61925. }
  61926. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  61927. return particleSystem;
  61928. };
  61929. return GPUParticleSystem;
  61930. }(BABYLON.BaseParticleSystem));
  61931. BABYLON.GPUParticleSystem = GPUParticleSystem;
  61932. })(BABYLON || (BABYLON = {}));
  61933. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  61934. var BABYLON;
  61935. (function (BABYLON) {
  61936. /**
  61937. * Represents one particle of a solid particle system.
  61938. */
  61939. var SolidParticle = /** @class */ (function () {
  61940. /**
  61941. * Creates a Solid Particle object.
  61942. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  61943. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  61944. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  61945. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  61946. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  61947. * @param shapeId (integer) is the model shape identifier in the SPS.
  61948. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  61949. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  61950. */
  61951. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  61952. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  61953. /**
  61954. * particle global index
  61955. */
  61956. this.idx = 0;
  61957. /**
  61958. * The color of the particle
  61959. */
  61960. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  61961. /**
  61962. * The world space position of the particle.
  61963. */
  61964. this.position = BABYLON.Vector3.Zero();
  61965. /**
  61966. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  61967. */
  61968. this.rotation = BABYLON.Vector3.Zero();
  61969. /**
  61970. * The scaling of the particle.
  61971. */
  61972. this.scaling = BABYLON.Vector3.One();
  61973. /**
  61974. * The uvs of the particle.
  61975. */
  61976. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  61977. /**
  61978. * The current speed of the particle.
  61979. */
  61980. this.velocity = BABYLON.Vector3.Zero();
  61981. /**
  61982. * The pivot point in the particle local space.
  61983. */
  61984. this.pivot = BABYLON.Vector3.Zero();
  61985. /**
  61986. * Must the particle be translated from its pivot point in its local space ?
  61987. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  61988. * Default : false
  61989. */
  61990. this.translateFromPivot = false;
  61991. /**
  61992. * Is the particle active or not ?
  61993. */
  61994. this.alive = true;
  61995. /**
  61996. * Is the particle visible or not ?
  61997. */
  61998. this.isVisible = true;
  61999. /**
  62000. * Index of this particle in the global "positions" array (Internal use)
  62001. * @hidden
  62002. */
  62003. this._pos = 0;
  62004. /**
  62005. * @hidden Index of this particle in the global "indices" array (Internal use)
  62006. */
  62007. this._ind = 0;
  62008. /**
  62009. * ModelShape id of this particle
  62010. */
  62011. this.shapeId = 0;
  62012. /**
  62013. * Index of the particle in its shape id (Internal use)
  62014. */
  62015. this.idxInShape = 0;
  62016. /**
  62017. * @hidden Still set as invisible in order to skip useless computations (Internal use)
  62018. */
  62019. this._stillInvisible = false;
  62020. /**
  62021. * @hidden Last computed particle rotation matrix
  62022. */
  62023. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  62024. /**
  62025. * Parent particle Id, if any.
  62026. * Default null.
  62027. */
  62028. this.parentId = null;
  62029. /**
  62030. * @hidden Internal global position in the SPS.
  62031. */
  62032. this._globalPosition = BABYLON.Vector3.Zero();
  62033. this.idx = particleIndex;
  62034. this._pos = positionIndex;
  62035. this._ind = indiceIndex;
  62036. this._model = model;
  62037. this.shapeId = shapeId;
  62038. this.idxInShape = idxInShape;
  62039. this._sps = sps;
  62040. if (modelBoundingInfo) {
  62041. this._modelBoundingInfo = modelBoundingInfo;
  62042. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  62043. }
  62044. }
  62045. Object.defineProperty(SolidParticle.prototype, "scale", {
  62046. /**
  62047. * Legacy support, changed scale to scaling
  62048. */
  62049. get: function () {
  62050. return this.scaling;
  62051. },
  62052. /**
  62053. * Legacy support, changed scale to scaling
  62054. */
  62055. set: function (scale) {
  62056. this.scaling = scale;
  62057. },
  62058. enumerable: true,
  62059. configurable: true
  62060. });
  62061. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  62062. /**
  62063. * Legacy support, changed quaternion to rotationQuaternion
  62064. */
  62065. get: function () {
  62066. return this.rotationQuaternion;
  62067. },
  62068. /**
  62069. * Legacy support, changed quaternion to rotationQuaternion
  62070. */
  62071. set: function (q) {
  62072. this.rotationQuaternion = q;
  62073. },
  62074. enumerable: true,
  62075. configurable: true
  62076. });
  62077. /**
  62078. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  62079. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  62080. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  62081. * @returns true if it intersects
  62082. */
  62083. SolidParticle.prototype.intersectsMesh = function (target) {
  62084. if (!this._boundingInfo || !target._boundingInfo) {
  62085. return false;
  62086. }
  62087. if (this._sps._bSphereOnly) {
  62088. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  62089. }
  62090. return this._boundingInfo.intersects(target._boundingInfo, false);
  62091. };
  62092. return SolidParticle;
  62093. }());
  62094. BABYLON.SolidParticle = SolidParticle;
  62095. /**
  62096. * Represents the shape of the model used by one particle of a solid particle system.
  62097. * SPS internal tool, don't use it manually.
  62098. */
  62099. var ModelShape = /** @class */ (function () {
  62100. /**
  62101. * 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.
  62102. * SPS internal tool, don't use it manually.
  62103. * @hidden
  62104. */
  62105. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  62106. /**
  62107. * length of the shape in the model indices array (internal use)
  62108. * @hidden
  62109. */
  62110. this._indicesLength = 0;
  62111. this.shapeID = id;
  62112. this._shape = shape;
  62113. this._indicesLength = indicesLength;
  62114. this._shapeUV = shapeUV;
  62115. this._positionFunction = posFunction;
  62116. this._vertexFunction = vtxFunction;
  62117. }
  62118. return ModelShape;
  62119. }());
  62120. BABYLON.ModelShape = ModelShape;
  62121. /**
  62122. * Represents a Depth Sorted Particle in the solid particle system.
  62123. */
  62124. var DepthSortedParticle = /** @class */ (function () {
  62125. function DepthSortedParticle() {
  62126. /**
  62127. * Index of the particle in the "indices" array
  62128. */
  62129. this.ind = 0;
  62130. /**
  62131. * Length of the particle shape in the "indices" array
  62132. */
  62133. this.indicesLength = 0;
  62134. /**
  62135. * Squared distance from the particle to the camera
  62136. */
  62137. this.sqDistance = 0.0;
  62138. }
  62139. return DepthSortedParticle;
  62140. }());
  62141. BABYLON.DepthSortedParticle = DepthSortedParticle;
  62142. })(BABYLON || (BABYLON = {}));
  62143. //# sourceMappingURL=babylon.solidParticle.js.map
  62144. var BABYLON;
  62145. (function (BABYLON) {
  62146. /**
  62147. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  62148. *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.
  62149. * The SPS is also a particle system. It provides some methods to manage the particles.
  62150. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  62151. *
  62152. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  62153. */
  62154. var SolidParticleSystem = /** @class */ (function () {
  62155. /**
  62156. * Creates a SPS (Solid Particle System) object.
  62157. * @param name (String) is the SPS name, this will be the underlying mesh name.
  62158. * @param scene (Scene) is the scene in which the SPS is added.
  62159. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  62160. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  62161. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  62162. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  62163. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  62164. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  62165. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  62166. */
  62167. function SolidParticleSystem(name, scene, options) {
  62168. /**
  62169. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  62170. * Example : var p = SPS.particles[i];
  62171. */
  62172. this.particles = new Array();
  62173. /**
  62174. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  62175. */
  62176. this.nbParticles = 0;
  62177. /**
  62178. * If the particles must ever face the camera (default false). Useful for planar particles.
  62179. */
  62180. this.billboard = false;
  62181. /**
  62182. * Recompute normals when adding a shape
  62183. */
  62184. this.recomputeNormals = true;
  62185. /**
  62186. * This a counter ofr your own usage. It's not set by any SPS functions.
  62187. */
  62188. this.counter = 0;
  62189. /**
  62190. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  62191. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  62192. */
  62193. this.vars = {};
  62194. /**
  62195. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  62196. * @hidden
  62197. */
  62198. this._bSphereOnly = false;
  62199. /**
  62200. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  62201. * @hidden
  62202. */
  62203. this._bSphereRadiusFactor = 1.0;
  62204. this._positions = new Array();
  62205. this._indices = new Array();
  62206. this._normals = new Array();
  62207. this._colors = new Array();
  62208. this._uvs = new Array();
  62209. this._index = 0; // indices index
  62210. this._updatable = true;
  62211. this._pickable = false;
  62212. this._isVisibilityBoxLocked = false;
  62213. this._alwaysVisible = false;
  62214. this._depthSort = false;
  62215. this._shapeCounter = 0;
  62216. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  62217. this._color = new BABYLON.Color4(0, 0, 0, 0);
  62218. this._computeParticleColor = true;
  62219. this._computeParticleTexture = true;
  62220. this._computeParticleRotation = true;
  62221. this._computeParticleVertex = false;
  62222. this._computeBoundingBox = false;
  62223. this._depthSortParticles = true;
  62224. this._cam_axisZ = BABYLON.Vector3.Zero();
  62225. this._cam_axisY = BABYLON.Vector3.Zero();
  62226. this._cam_axisX = BABYLON.Vector3.Zero();
  62227. this._axisZ = BABYLON.Axis.Z;
  62228. this._camDir = BABYLON.Vector3.Zero();
  62229. this._camInvertedPosition = BABYLON.Vector3.Zero();
  62230. this._rotMatrix = new BABYLON.Matrix();
  62231. this._invertMatrix = new BABYLON.Matrix();
  62232. this._rotated = BABYLON.Vector3.Zero();
  62233. this._quaternion = new BABYLON.Quaternion();
  62234. this._vertex = BABYLON.Vector3.Zero();
  62235. this._normal = BABYLON.Vector3.Zero();
  62236. this._yaw = 0.0;
  62237. this._pitch = 0.0;
  62238. this._roll = 0.0;
  62239. this._halfroll = 0.0;
  62240. this._halfpitch = 0.0;
  62241. this._halfyaw = 0.0;
  62242. this._sinRoll = 0.0;
  62243. this._cosRoll = 0.0;
  62244. this._sinPitch = 0.0;
  62245. this._cosPitch = 0.0;
  62246. this._sinYaw = 0.0;
  62247. this._cosYaw = 0.0;
  62248. this._mustUnrotateFixedNormals = false;
  62249. this._minimum = BABYLON.Vector3.Zero();
  62250. this._maximum = BABYLON.Vector3.Zero();
  62251. this._minBbox = BABYLON.Vector3.Zero();
  62252. this._maxBbox = BABYLON.Vector3.Zero();
  62253. this._particlesIntersect = false;
  62254. this._depthSortFunction = function (p1, p2) {
  62255. return (p2.sqDistance - p1.sqDistance);
  62256. };
  62257. this._needs32Bits = false;
  62258. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  62259. this._scaledPivot = BABYLON.Vector3.Zero();
  62260. this._particleHasParent = false;
  62261. this.name = name;
  62262. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  62263. this._camera = scene.activeCamera;
  62264. this._pickable = options ? options.isPickable : false;
  62265. this._depthSort = options ? options.enableDepthSort : false;
  62266. this._particlesIntersect = options ? options.particleIntersection : false;
  62267. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  62268. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  62269. if (options && options.updatable !== undefined) {
  62270. this._updatable = options.updatable;
  62271. }
  62272. else {
  62273. this._updatable = true;
  62274. }
  62275. if (this._pickable) {
  62276. this.pickedParticles = [];
  62277. }
  62278. if (this._depthSort) {
  62279. this.depthSortedParticles = [];
  62280. }
  62281. }
  62282. /**
  62283. * Builds the SPS underlying mesh. Returns a standard Mesh.
  62284. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  62285. * @returns the created mesh
  62286. */
  62287. SolidParticleSystem.prototype.buildMesh = function () {
  62288. if (this.nbParticles === 0) {
  62289. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  62290. this.addShape(triangle, 1);
  62291. triangle.dispose();
  62292. }
  62293. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  62294. this._positions32 = new Float32Array(this._positions);
  62295. this._uvs32 = new Float32Array(this._uvs);
  62296. this._colors32 = new Float32Array(this._colors);
  62297. if (this.recomputeNormals) {
  62298. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  62299. }
  62300. this._normals32 = new Float32Array(this._normals);
  62301. this._fixedNormal32 = new Float32Array(this._normals);
  62302. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  62303. this._unrotateFixedNormals();
  62304. }
  62305. var vertexData = new BABYLON.VertexData();
  62306. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  62307. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  62308. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  62309. if (this._uvs32.length > 0) {
  62310. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  62311. }
  62312. if (this._colors32.length > 0) {
  62313. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  62314. }
  62315. var mesh = new BABYLON.Mesh(this.name, this._scene);
  62316. vertexData.applyToMesh(mesh, this._updatable);
  62317. this.mesh = mesh;
  62318. this.mesh.isPickable = this._pickable;
  62319. // free memory
  62320. if (!this._depthSort) {
  62321. this._indices = null;
  62322. }
  62323. this._positions = null;
  62324. this._normals = null;
  62325. this._uvs = null;
  62326. this._colors = null;
  62327. if (!this._updatable) {
  62328. this.particles.length = 0;
  62329. }
  62330. return mesh;
  62331. };
  62332. /**
  62333. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  62334. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  62335. * Thus the particles generated from `digest()` have their property `position` set yet.
  62336. * @param mesh ( Mesh ) is the mesh to be digested
  62337. * @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
  62338. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  62339. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  62340. * @returns the current SPS
  62341. */
  62342. SolidParticleSystem.prototype.digest = function (mesh, options) {
  62343. var size = (options && options.facetNb) || 1;
  62344. var number = (options && options.number) || 0;
  62345. var delta = (options && options.delta) || 0;
  62346. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62347. var meshInd = mesh.getIndices();
  62348. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  62349. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  62350. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  62351. var f = 0; // facet counter
  62352. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  62353. // compute size from number
  62354. if (number) {
  62355. number = (number > totalFacets) ? totalFacets : number;
  62356. size = Math.round(totalFacets / number);
  62357. delta = 0;
  62358. }
  62359. else {
  62360. size = (size > totalFacets) ? totalFacets : size;
  62361. }
  62362. var facetPos = []; // submesh positions
  62363. var facetInd = []; // submesh indices
  62364. var facetUV = []; // submesh UV
  62365. var facetCol = []; // submesh colors
  62366. var barycenter = BABYLON.Vector3.Zero();
  62367. var sizeO = size;
  62368. while (f < totalFacets) {
  62369. size = sizeO + Math.floor((1 + delta) * Math.random());
  62370. if (f > totalFacets - size) {
  62371. size = totalFacets - f;
  62372. }
  62373. // reset temp arrays
  62374. facetPos.length = 0;
  62375. facetInd.length = 0;
  62376. facetUV.length = 0;
  62377. facetCol.length = 0;
  62378. // iterate over "size" facets
  62379. var fi = 0;
  62380. for (var j = f * 3; j < (f + size) * 3; j++) {
  62381. facetInd.push(fi);
  62382. var i = meshInd[j];
  62383. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  62384. if (meshUV) {
  62385. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  62386. }
  62387. if (meshCol) {
  62388. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  62389. }
  62390. fi++;
  62391. }
  62392. // create a model shape for each single particle
  62393. var idx = this.nbParticles;
  62394. var shape = this._posToShape(facetPos);
  62395. var shapeUV = this._uvsToShapeUV(facetUV);
  62396. // compute the barycenter of the shape
  62397. var v;
  62398. for (v = 0; v < shape.length; v++) {
  62399. barycenter.addInPlace(shape[v]);
  62400. }
  62401. barycenter.scaleInPlace(1 / shape.length);
  62402. // shift the shape from its barycenter to the origin
  62403. for (v = 0; v < shape.length; v++) {
  62404. shape[v].subtractInPlace(barycenter);
  62405. }
  62406. var bInfo;
  62407. if (this._particlesIntersect) {
  62408. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  62409. }
  62410. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  62411. // add the particle in the SPS
  62412. var currentPos = this._positions.length;
  62413. var currentInd = this._indices.length;
  62414. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  62415. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  62416. // initialize the particle position
  62417. this.particles[this.nbParticles].position.addInPlace(barycenter);
  62418. this._index += shape.length;
  62419. idx++;
  62420. this.nbParticles++;
  62421. this._shapeCounter++;
  62422. f += size;
  62423. }
  62424. return this;
  62425. };
  62426. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  62427. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  62428. var index = 0;
  62429. var idx = 0;
  62430. for (var p = 0; p < this.particles.length; p++) {
  62431. this._particle = this.particles[p];
  62432. this._shape = this._particle._model._shape;
  62433. if (this._particle.rotationQuaternion) {
  62434. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  62435. }
  62436. else {
  62437. this._yaw = this._particle.rotation.y;
  62438. this._pitch = this._particle.rotation.x;
  62439. this._roll = this._particle.rotation.z;
  62440. this._quaternionRotationYPR();
  62441. }
  62442. this._quaternionToRotationMatrix();
  62443. this._rotMatrix.invertToRef(this._invertMatrix);
  62444. for (var pt = 0; pt < this._shape.length; pt++) {
  62445. idx = index + pt * 3;
  62446. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  62447. this._fixedNormal32[idx] = this._normal.x;
  62448. this._fixedNormal32[idx + 1] = this._normal.y;
  62449. this._fixedNormal32[idx + 2] = this._normal.z;
  62450. }
  62451. index = idx + 3;
  62452. }
  62453. };
  62454. //reset copy
  62455. SolidParticleSystem.prototype._resetCopy = function () {
  62456. this._copy.position.x = 0;
  62457. this._copy.position.y = 0;
  62458. this._copy.position.z = 0;
  62459. this._copy.rotation.x = 0;
  62460. this._copy.rotation.y = 0;
  62461. this._copy.rotation.z = 0;
  62462. this._copy.rotationQuaternion = null;
  62463. this._copy.scaling.x = 1.0;
  62464. this._copy.scaling.y = 1.0;
  62465. this._copy.scaling.z = 1.0;
  62466. this._copy.uvs.x = 0;
  62467. this._copy.uvs.y = 0;
  62468. this._copy.uvs.z = 1.0;
  62469. this._copy.uvs.w = 1.0;
  62470. this._copy.color = null;
  62471. this._copy.translateFromPivot = false;
  62472. };
  62473. // _meshBuilder : inserts the shape model in the global SPS mesh
  62474. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  62475. var i;
  62476. var u = 0;
  62477. var c = 0;
  62478. var n = 0;
  62479. this._resetCopy();
  62480. if (options && options.positionFunction) { // call to custom positionFunction
  62481. options.positionFunction(this._copy, idx, idxInShape);
  62482. this._mustUnrotateFixedNormals = true;
  62483. }
  62484. if (this._copy.rotationQuaternion) {
  62485. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  62486. }
  62487. else {
  62488. this._yaw = this._copy.rotation.y;
  62489. this._pitch = this._copy.rotation.x;
  62490. this._roll = this._copy.rotation.z;
  62491. this._quaternionRotationYPR();
  62492. }
  62493. this._quaternionToRotationMatrix();
  62494. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  62495. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  62496. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  62497. if (this._copy.translateFromPivot) {
  62498. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  62499. }
  62500. else {
  62501. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  62502. }
  62503. for (i = 0; i < shape.length; i++) {
  62504. this._vertex.x = shape[i].x;
  62505. this._vertex.y = shape[i].y;
  62506. this._vertex.z = shape[i].z;
  62507. if (options && options.vertexFunction) {
  62508. options.vertexFunction(this._copy, this._vertex, i);
  62509. }
  62510. this._vertex.x *= this._copy.scaling.x;
  62511. this._vertex.y *= this._copy.scaling.y;
  62512. this._vertex.z *= this._copy.scaling.z;
  62513. this._vertex.x -= this._scaledPivot.x;
  62514. this._vertex.y -= this._scaledPivot.y;
  62515. this._vertex.z -= this._scaledPivot.z;
  62516. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  62517. this._rotated.addInPlace(this._pivotBackTranslation);
  62518. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  62519. if (meshUV) {
  62520. 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);
  62521. u += 2;
  62522. }
  62523. if (this._copy.color) {
  62524. this._color = this._copy.color;
  62525. }
  62526. else if (meshCol && meshCol[c] !== undefined) {
  62527. this._color.r = meshCol[c];
  62528. this._color.g = meshCol[c + 1];
  62529. this._color.b = meshCol[c + 2];
  62530. this._color.a = meshCol[c + 3];
  62531. }
  62532. else {
  62533. this._color.r = 1.0;
  62534. this._color.g = 1.0;
  62535. this._color.b = 1.0;
  62536. this._color.a = 1.0;
  62537. }
  62538. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  62539. c += 4;
  62540. if (!this.recomputeNormals && meshNor) {
  62541. this._normal.x = meshNor[n];
  62542. this._normal.y = meshNor[n + 1];
  62543. this._normal.z = meshNor[n + 2];
  62544. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  62545. normals.push(this._normal.x, this._normal.y, this._normal.z);
  62546. n += 3;
  62547. }
  62548. }
  62549. for (i = 0; i < meshInd.length; i++) {
  62550. var current_ind = p + meshInd[i];
  62551. indices.push(current_ind);
  62552. if (current_ind > 65535) {
  62553. this._needs32Bits = true;
  62554. }
  62555. }
  62556. if (this._pickable) {
  62557. var nbfaces = meshInd.length / 3;
  62558. for (i = 0; i < nbfaces; i++) {
  62559. this.pickedParticles.push({ idx: idx, faceId: i });
  62560. }
  62561. }
  62562. if (this._depthSort) {
  62563. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  62564. }
  62565. return this._copy;
  62566. };
  62567. // returns a shape array from positions array
  62568. SolidParticleSystem.prototype._posToShape = function (positions) {
  62569. var shape = [];
  62570. for (var i = 0; i < positions.length; i += 3) {
  62571. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  62572. }
  62573. return shape;
  62574. };
  62575. // returns a shapeUV array from a Vector4 uvs
  62576. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  62577. var shapeUV = [];
  62578. if (uvs) {
  62579. for (var i = 0; i < uvs.length; i++)
  62580. shapeUV.push(uvs[i]);
  62581. }
  62582. return shapeUV;
  62583. };
  62584. // adds a new particle object in the particles array
  62585. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  62586. if (bInfo === void 0) { bInfo = null; }
  62587. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  62588. this.particles.push(sp);
  62589. return sp;
  62590. };
  62591. /**
  62592. * Adds some particles to the SPS from the model shape. Returns the shape id.
  62593. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  62594. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  62595. * @param nb (positive integer) the number of particles to be created from this model
  62596. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  62597. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  62598. * @returns the number of shapes in the system
  62599. */
  62600. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  62601. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62602. var meshInd = mesh.getIndices();
  62603. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  62604. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  62605. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  62606. var bbInfo;
  62607. if (this._particlesIntersect) {
  62608. bbInfo = mesh.getBoundingInfo();
  62609. }
  62610. var shape = this._posToShape(meshPos);
  62611. var shapeUV = this._uvsToShapeUV(meshUV);
  62612. var posfunc = options ? options.positionFunction : null;
  62613. var vtxfunc = options ? options.vertexFunction : null;
  62614. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  62615. // particles
  62616. var sp;
  62617. var currentCopy;
  62618. var idx = this.nbParticles;
  62619. for (var i = 0; i < nb; i++) {
  62620. var currentPos = this._positions.length;
  62621. var currentInd = this._indices.length;
  62622. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  62623. if (this._updatable) {
  62624. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  62625. sp.position.copyFrom(currentCopy.position);
  62626. sp.rotation.copyFrom(currentCopy.rotation);
  62627. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  62628. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  62629. }
  62630. if (currentCopy.color && sp.color) {
  62631. sp.color.copyFrom(currentCopy.color);
  62632. }
  62633. sp.scaling.copyFrom(currentCopy.scaling);
  62634. sp.uvs.copyFrom(currentCopy.uvs);
  62635. }
  62636. this._index += shape.length;
  62637. idx++;
  62638. }
  62639. this.nbParticles += nb;
  62640. this._shapeCounter++;
  62641. return this._shapeCounter - 1;
  62642. };
  62643. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  62644. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  62645. this._resetCopy();
  62646. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  62647. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  62648. }
  62649. if (this._copy.rotationQuaternion) {
  62650. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  62651. }
  62652. else {
  62653. this._yaw = this._copy.rotation.y;
  62654. this._pitch = this._copy.rotation.x;
  62655. this._roll = this._copy.rotation.z;
  62656. this._quaternionRotationYPR();
  62657. }
  62658. this._quaternionToRotationMatrix();
  62659. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  62660. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  62661. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  62662. if (this._copy.translateFromPivot) {
  62663. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  62664. }
  62665. else {
  62666. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  62667. }
  62668. this._shape = particle._model._shape;
  62669. for (var pt = 0; pt < this._shape.length; pt++) {
  62670. this._vertex.x = this._shape[pt].x;
  62671. this._vertex.y = this._shape[pt].y;
  62672. this._vertex.z = this._shape[pt].z;
  62673. if (particle._model._vertexFunction) {
  62674. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  62675. }
  62676. this._vertex.x *= this._copy.scaling.x;
  62677. this._vertex.y *= this._copy.scaling.y;
  62678. this._vertex.z *= this._copy.scaling.z;
  62679. this._vertex.x -= this._scaledPivot.x;
  62680. this._vertex.y -= this._scaledPivot.y;
  62681. this._vertex.z -= this._scaledPivot.z;
  62682. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  62683. this._rotated.addInPlace(this._pivotBackTranslation);
  62684. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  62685. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  62686. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  62687. }
  62688. particle.position.x = 0.0;
  62689. particle.position.y = 0.0;
  62690. particle.position.z = 0.0;
  62691. particle.rotation.x = 0.0;
  62692. particle.rotation.y = 0.0;
  62693. particle.rotation.z = 0.0;
  62694. particle.rotationQuaternion = null;
  62695. particle.scaling.x = 1.0;
  62696. particle.scaling.y = 1.0;
  62697. particle.scaling.z = 1.0;
  62698. particle.uvs.x = 0.0;
  62699. particle.uvs.y = 0.0;
  62700. particle.uvs.z = 1.0;
  62701. particle.uvs.w = 1.0;
  62702. particle.pivot.x = 0.0;
  62703. particle.pivot.y = 0.0;
  62704. particle.pivot.z = 0.0;
  62705. particle.translateFromPivot = false;
  62706. particle.parentId = null;
  62707. };
  62708. /**
  62709. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  62710. * @returns the SPS.
  62711. */
  62712. SolidParticleSystem.prototype.rebuildMesh = function () {
  62713. for (var p = 0; p < this.particles.length; p++) {
  62714. this._rebuildParticle(this.particles[p]);
  62715. }
  62716. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  62717. return this;
  62718. };
  62719. /**
  62720. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  62721. * This method calls `updateParticle()` for each particle of the SPS.
  62722. * For an animated SPS, it is usually called within the render loop.
  62723. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  62724. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  62725. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  62726. * @returns the SPS.
  62727. */
  62728. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  62729. if (start === void 0) { start = 0; }
  62730. if (end === void 0) { end = this.nbParticles - 1; }
  62731. if (update === void 0) { update = true; }
  62732. if (!this._updatable) {
  62733. return this;
  62734. }
  62735. // custom beforeUpdate
  62736. this.beforeUpdateParticles(start, end, update);
  62737. this._cam_axisX.x = 1.0;
  62738. this._cam_axisX.y = 0.0;
  62739. this._cam_axisX.z = 0.0;
  62740. this._cam_axisY.x = 0.0;
  62741. this._cam_axisY.y = 1.0;
  62742. this._cam_axisY.z = 0.0;
  62743. this._cam_axisZ.x = 0.0;
  62744. this._cam_axisZ.y = 0.0;
  62745. this._cam_axisZ.z = 1.0;
  62746. // cases when the World Matrix is to be computed first
  62747. if (this.billboard || this._depthSort) {
  62748. this.mesh.computeWorldMatrix(true);
  62749. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  62750. }
  62751. // if the particles will always face the camera
  62752. if (this.billboard) {
  62753. // compute the camera position and un-rotate it by the current mesh rotation
  62754. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  62755. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  62756. this._cam_axisZ.normalize();
  62757. // same for camera up vector extracted from the cam view matrix
  62758. var view = this._camera.getViewMatrix(true);
  62759. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  62760. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  62761. this._cam_axisY.normalize();
  62762. this._cam_axisX.normalize();
  62763. }
  62764. // if depthSort, compute the camera global position in the mesh local system
  62765. if (this._depthSort) {
  62766. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  62767. }
  62768. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  62769. var idx = 0; // current position index in the global array positions32
  62770. var index = 0; // position start index in the global array positions32 of the current particle
  62771. var colidx = 0; // current color index in the global array colors32
  62772. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  62773. var uvidx = 0; // current uv index in the global array uvs32
  62774. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  62775. var pt = 0; // current index in the particle model shape
  62776. if (this.mesh.isFacetDataEnabled) {
  62777. this._computeBoundingBox = true;
  62778. }
  62779. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  62780. if (this._computeBoundingBox) {
  62781. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  62782. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  62783. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  62784. }
  62785. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  62786. if (this.mesh._boundingInfo) {
  62787. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  62788. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  62789. }
  62790. }
  62791. }
  62792. // particle loop
  62793. index = this.particles[start]._pos;
  62794. var vpos = (index / 3) | 0;
  62795. colorIndex = vpos * 4;
  62796. uvIndex = vpos * 2;
  62797. for (var p = start; p <= end; p++) {
  62798. this._particle = this.particles[p];
  62799. this._shape = this._particle._model._shape;
  62800. this._shapeUV = this._particle._model._shapeUV;
  62801. // call to custom user function to update the particle properties
  62802. this.updateParticle(this._particle);
  62803. // camera-particle distance for depth sorting
  62804. if (this._depthSort && this._depthSortParticles) {
  62805. var dsp = this.depthSortedParticles[p];
  62806. dsp.ind = this._particle._ind;
  62807. dsp.indicesLength = this._particle._model._indicesLength;
  62808. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  62809. }
  62810. // skip the computations for inactive or already invisible particles
  62811. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  62812. // increment indexes for the next particle
  62813. pt = this._shape.length;
  62814. index += pt * 3;
  62815. colorIndex += pt * 4;
  62816. uvIndex += pt * 2;
  62817. continue;
  62818. }
  62819. if (this._particle.isVisible) {
  62820. this._particle._stillInvisible = false; // un-mark permanent invisibility
  62821. this._particleHasParent = (this._particle.parentId !== null);
  62822. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  62823. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  62824. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  62825. // particle rotation matrix
  62826. if (this.billboard) {
  62827. this._particle.rotation.x = 0.0;
  62828. this._particle.rotation.y = 0.0;
  62829. }
  62830. if (this._computeParticleRotation || this.billboard) {
  62831. if (this._particle.rotationQuaternion) {
  62832. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  62833. }
  62834. else {
  62835. this._yaw = this._particle.rotation.y;
  62836. this._pitch = this._particle.rotation.x;
  62837. this._roll = this._particle.rotation.z;
  62838. this._quaternionRotationYPR();
  62839. }
  62840. this._quaternionToRotationMatrix();
  62841. }
  62842. if (this._particleHasParent) {
  62843. this._parent = this.particles[this._particle.parentId];
  62844. 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];
  62845. 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];
  62846. 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];
  62847. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  62848. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  62849. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  62850. if (this._computeParticleRotation || this.billboard) {
  62851. 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];
  62852. 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];
  62853. 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];
  62854. 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];
  62855. 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];
  62856. 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];
  62857. 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];
  62858. 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];
  62859. 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];
  62860. }
  62861. }
  62862. else {
  62863. this._particle._globalPosition.x = this._particle.position.x;
  62864. this._particle._globalPosition.y = this._particle.position.y;
  62865. this._particle._globalPosition.z = this._particle.position.z;
  62866. if (this._computeParticleRotation || this.billboard) {
  62867. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  62868. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  62869. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  62870. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  62871. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  62872. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  62873. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  62874. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  62875. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  62876. }
  62877. }
  62878. if (this._particle.translateFromPivot) {
  62879. this._pivotBackTranslation.x = 0.0;
  62880. this._pivotBackTranslation.y = 0.0;
  62881. this._pivotBackTranslation.z = 0.0;
  62882. }
  62883. else {
  62884. this._pivotBackTranslation.x = this._scaledPivot.x;
  62885. this._pivotBackTranslation.y = this._scaledPivot.y;
  62886. this._pivotBackTranslation.z = this._scaledPivot.z;
  62887. }
  62888. // particle vertex loop
  62889. for (pt = 0; pt < this._shape.length; pt++) {
  62890. idx = index + pt * 3;
  62891. colidx = colorIndex + pt * 4;
  62892. uvidx = uvIndex + pt * 2;
  62893. this._vertex.x = this._shape[pt].x;
  62894. this._vertex.y = this._shape[pt].y;
  62895. this._vertex.z = this._shape[pt].z;
  62896. if (this._computeParticleVertex) {
  62897. this.updateParticleVertex(this._particle, this._vertex, pt);
  62898. }
  62899. // positions
  62900. this._vertex.x *= this._particle.scaling.x;
  62901. this._vertex.y *= this._particle.scaling.y;
  62902. this._vertex.z *= this._particle.scaling.z;
  62903. this._vertex.x -= this._scaledPivot.x;
  62904. this._vertex.y -= this._scaledPivot.y;
  62905. this._vertex.z -= this._scaledPivot.z;
  62906. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  62907. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  62908. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  62909. this._rotated.x += this._pivotBackTranslation.x;
  62910. this._rotated.y += this._pivotBackTranslation.y;
  62911. this._rotated.z += this._pivotBackTranslation.z;
  62912. 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;
  62913. 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;
  62914. 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;
  62915. if (this._computeBoundingBox) {
  62916. if (this._positions32[idx] < this._minimum.x) {
  62917. this._minimum.x = this._positions32[idx];
  62918. }
  62919. if (this._positions32[idx] > this._maximum.x) {
  62920. this._maximum.x = this._positions32[idx];
  62921. }
  62922. if (this._positions32[idx + 1] < this._minimum.y) {
  62923. this._minimum.y = this._positions32[idx + 1];
  62924. }
  62925. if (this._positions32[idx + 1] > this._maximum.y) {
  62926. this._maximum.y = this._positions32[idx + 1];
  62927. }
  62928. if (this._positions32[idx + 2] < this._minimum.z) {
  62929. this._minimum.z = this._positions32[idx + 2];
  62930. }
  62931. if (this._positions32[idx + 2] > this._maximum.z) {
  62932. this._maximum.z = this._positions32[idx + 2];
  62933. }
  62934. }
  62935. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  62936. if (!this._computeParticleVertex) {
  62937. this._normal.x = this._fixedNormal32[idx];
  62938. this._normal.y = this._fixedNormal32[idx + 1];
  62939. this._normal.z = this._fixedNormal32[idx + 2];
  62940. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  62941. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  62942. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  62943. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  62944. 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;
  62945. 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;
  62946. }
  62947. if (this._computeParticleColor && this._particle.color) {
  62948. this._colors32[colidx] = this._particle.color.r;
  62949. this._colors32[colidx + 1] = this._particle.color.g;
  62950. this._colors32[colidx + 2] = this._particle.color.b;
  62951. this._colors32[colidx + 3] = this._particle.color.a;
  62952. }
  62953. if (this._computeParticleTexture) {
  62954. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  62955. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  62956. }
  62957. }
  62958. }
  62959. // particle just set invisible : scaled to zero and positioned at the origin
  62960. else {
  62961. this._particle._stillInvisible = true; // mark the particle as invisible
  62962. for (pt = 0; pt < this._shape.length; pt++) {
  62963. idx = index + pt * 3;
  62964. colidx = colorIndex + pt * 4;
  62965. uvidx = uvIndex + pt * 2;
  62966. this._positions32[idx] = 0.0;
  62967. this._positions32[idx + 1] = 0.0;
  62968. this._positions32[idx + 2] = 0.0;
  62969. this._normals32[idx] = 0.0;
  62970. this._normals32[idx + 1] = 0.0;
  62971. this._normals32[idx + 2] = 0.0;
  62972. if (this._computeParticleColor && this._particle.color) {
  62973. this._colors32[colidx] = this._particle.color.r;
  62974. this._colors32[colidx + 1] = this._particle.color.g;
  62975. this._colors32[colidx + 2] = this._particle.color.b;
  62976. this._colors32[colidx + 3] = this._particle.color.a;
  62977. }
  62978. if (this._computeParticleTexture) {
  62979. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  62980. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  62981. }
  62982. }
  62983. }
  62984. // if the particle intersections must be computed : update the bbInfo
  62985. if (this._particlesIntersect) {
  62986. var bInfo = this._particle._boundingInfo;
  62987. var bBox = bInfo.boundingBox;
  62988. var bSphere = bInfo.boundingSphere;
  62989. if (!this._bSphereOnly) {
  62990. // place, scale and rotate the particle bbox within the SPS local system, then update it
  62991. for (var b = 0; b < bBox.vectors.length; b++) {
  62992. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  62993. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  62994. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  62995. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  62996. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  62997. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  62998. 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;
  62999. 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;
  63000. 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;
  63001. }
  63002. bBox._update(this.mesh._worldMatrix);
  63003. }
  63004. // place and scale the particle bouding sphere in the SPS local system, then update it
  63005. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  63006. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  63007. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  63008. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  63009. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  63010. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  63011. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  63012. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  63013. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  63014. 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));
  63015. bSphere._update(this.mesh._worldMatrix);
  63016. }
  63017. // increment indexes for the next particle
  63018. index = idx + 3;
  63019. colorIndex = colidx + 4;
  63020. uvIndex = uvidx + 2;
  63021. }
  63022. // if the VBO must be updated
  63023. if (update) {
  63024. if (this._computeParticleColor) {
  63025. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  63026. }
  63027. if (this._computeParticleTexture) {
  63028. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  63029. }
  63030. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  63031. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  63032. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  63033. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  63034. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  63035. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  63036. for (var i = 0; i < this._normals32.length; i++) {
  63037. this._fixedNormal32[i] = this._normals32[i];
  63038. }
  63039. }
  63040. if (!this.mesh.areNormalsFrozen) {
  63041. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  63042. }
  63043. }
  63044. if (this._depthSort && this._depthSortParticles) {
  63045. this.depthSortedParticles.sort(this._depthSortFunction);
  63046. var dspl = this.depthSortedParticles.length;
  63047. var sorted = 0;
  63048. var lind = 0;
  63049. var sind = 0;
  63050. var sid = 0;
  63051. for (sorted = 0; sorted < dspl; sorted++) {
  63052. lind = this.depthSortedParticles[sorted].indicesLength;
  63053. sind = this.depthSortedParticles[sorted].ind;
  63054. for (var i = 0; i < lind; i++) {
  63055. this._indices32[sid] = this._indices[sind + i];
  63056. sid++;
  63057. }
  63058. }
  63059. this.mesh.updateIndices(this._indices32);
  63060. }
  63061. }
  63062. if (this._computeBoundingBox) {
  63063. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  63064. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  63065. }
  63066. this.afterUpdateParticles(start, end, update);
  63067. return this;
  63068. };
  63069. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  63070. this._halfroll = this._roll * 0.5;
  63071. this._halfpitch = this._pitch * 0.5;
  63072. this._halfyaw = this._yaw * 0.5;
  63073. this._sinRoll = Math.sin(this._halfroll);
  63074. this._cosRoll = Math.cos(this._halfroll);
  63075. this._sinPitch = Math.sin(this._halfpitch);
  63076. this._cosPitch = Math.cos(this._halfpitch);
  63077. this._sinYaw = Math.sin(this._halfyaw);
  63078. this._cosYaw = Math.cos(this._halfyaw);
  63079. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  63080. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  63081. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  63082. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  63083. };
  63084. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  63085. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  63086. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  63087. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  63088. this._rotMatrix.m[3] = 0;
  63089. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  63090. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  63091. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  63092. this._rotMatrix.m[7] = 0;
  63093. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  63094. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  63095. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  63096. this._rotMatrix.m[11] = 0;
  63097. this._rotMatrix.m[12] = 0;
  63098. this._rotMatrix.m[13] = 0;
  63099. this._rotMatrix.m[14] = 0;
  63100. this._rotMatrix.m[15] = 1.0;
  63101. };
  63102. /**
  63103. * Disposes the SPS.
  63104. */
  63105. SolidParticleSystem.prototype.dispose = function () {
  63106. this.mesh.dispose();
  63107. this.vars = null;
  63108. // drop references to internal big arrays for the GC
  63109. this._positions = null;
  63110. this._indices = null;
  63111. this._normals = null;
  63112. this._uvs = null;
  63113. this._colors = null;
  63114. this._indices32 = null;
  63115. this._positions32 = null;
  63116. this._normals32 = null;
  63117. this._fixedNormal32 = null;
  63118. this._uvs32 = null;
  63119. this._colors32 = null;
  63120. this.pickedParticles = null;
  63121. };
  63122. /**
  63123. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  63124. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63125. * @returns the SPS.
  63126. */
  63127. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  63128. if (!this._isVisibilityBoxLocked) {
  63129. this.mesh.refreshBoundingInfo();
  63130. }
  63131. return this;
  63132. };
  63133. /**
  63134. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  63135. * @param size the size (float) of the visibility box
  63136. * note : this doesn't lock the SPS mesh bounding box.
  63137. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63138. */
  63139. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  63140. var vis = size / 2;
  63141. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  63142. };
  63143. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  63144. /**
  63145. * Gets whether the SPS as always visible or not
  63146. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63147. */
  63148. get: function () {
  63149. return this._alwaysVisible;
  63150. },
  63151. /**
  63152. * Sets the SPS as always visible or not
  63153. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63154. */
  63155. set: function (val) {
  63156. this._alwaysVisible = val;
  63157. this.mesh.alwaysSelectAsActiveMesh = val;
  63158. },
  63159. enumerable: true,
  63160. configurable: true
  63161. });
  63162. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  63163. /**
  63164. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  63165. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63166. */
  63167. get: function () {
  63168. return this._isVisibilityBoxLocked;
  63169. },
  63170. /**
  63171. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  63172. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63173. */
  63174. set: function (val) {
  63175. this._isVisibilityBoxLocked = val;
  63176. var boundingInfo = this.mesh.getBoundingInfo();
  63177. boundingInfo.isLocked = val;
  63178. },
  63179. enumerable: true,
  63180. configurable: true
  63181. });
  63182. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  63183. /**
  63184. * Gets if `setParticles()` computes the particle rotations or not.
  63185. * Default value : true. The SPS is faster when it's set to false.
  63186. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  63187. */
  63188. get: function () {
  63189. return this._computeParticleRotation;
  63190. },
  63191. /**
  63192. * Tells to `setParticles()` to compute the particle rotations or not.
  63193. * Default value : true. The SPS is faster when it's set to false.
  63194. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  63195. */
  63196. set: function (val) {
  63197. this._computeParticleRotation = val;
  63198. },
  63199. enumerable: true,
  63200. configurable: true
  63201. });
  63202. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  63203. /**
  63204. * Gets if `setParticles()` computes the particle colors or not.
  63205. * Default value : true. The SPS is faster when it's set to false.
  63206. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  63207. */
  63208. get: function () {
  63209. return this._computeParticleColor;
  63210. },
  63211. /**
  63212. * Tells to `setParticles()` to compute the particle colors or not.
  63213. * Default value : true. The SPS is faster when it's set to false.
  63214. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  63215. */
  63216. set: function (val) {
  63217. this._computeParticleColor = val;
  63218. },
  63219. enumerable: true,
  63220. configurable: true
  63221. });
  63222. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  63223. /**
  63224. * Gets if `setParticles()` computes the particle textures or not.
  63225. * Default value : true. The SPS is faster when it's set to false.
  63226. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  63227. */
  63228. get: function () {
  63229. return this._computeParticleTexture;
  63230. },
  63231. set: function (val) {
  63232. this._computeParticleTexture = val;
  63233. },
  63234. enumerable: true,
  63235. configurable: true
  63236. });
  63237. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  63238. /**
  63239. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  63240. * Default value : false. The SPS is faster when it's set to false.
  63241. * Note : the particle custom vertex positions aren't stored values.
  63242. */
  63243. get: function () {
  63244. return this._computeParticleVertex;
  63245. },
  63246. /**
  63247. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  63248. * Default value : false. The SPS is faster when it's set to false.
  63249. * Note : the particle custom vertex positions aren't stored values.
  63250. */
  63251. set: function (val) {
  63252. this._computeParticleVertex = val;
  63253. },
  63254. enumerable: true,
  63255. configurable: true
  63256. });
  63257. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  63258. /**
  63259. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  63260. */
  63261. get: function () {
  63262. return this._computeBoundingBox;
  63263. },
  63264. /**
  63265. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  63266. */
  63267. set: function (val) {
  63268. this._computeBoundingBox = val;
  63269. },
  63270. enumerable: true,
  63271. configurable: true
  63272. });
  63273. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  63274. /**
  63275. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  63276. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  63277. * Default : `true`
  63278. */
  63279. get: function () {
  63280. return this._depthSortParticles;
  63281. },
  63282. /**
  63283. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  63284. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  63285. * Default : `true`
  63286. */
  63287. set: function (val) {
  63288. this._depthSortParticles = val;
  63289. },
  63290. enumerable: true,
  63291. configurable: true
  63292. });
  63293. // =======================================================================
  63294. // Particle behavior logic
  63295. // these following methods may be overwritten by the user to fit his needs
  63296. /**
  63297. * This function does nothing. It may be overwritten to set all the particle first values.
  63298. * The SPS doesn't call this function, you may have to call it by your own.
  63299. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  63300. */
  63301. SolidParticleSystem.prototype.initParticles = function () {
  63302. };
  63303. /**
  63304. * This function does nothing. It may be overwritten to recycle a particle.
  63305. * The SPS doesn't call this function, you may have to call it by your own.
  63306. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  63307. * @param particle The particle to recycle
  63308. * @returns the recycled particle
  63309. */
  63310. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  63311. return particle;
  63312. };
  63313. /**
  63314. * Updates a particle : this function should be overwritten by the user.
  63315. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  63316. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  63317. * @example : just set a particle position or velocity and recycle conditions
  63318. * @param particle The particle to update
  63319. * @returns the updated particle
  63320. */
  63321. SolidParticleSystem.prototype.updateParticle = function (particle) {
  63322. return particle;
  63323. };
  63324. /**
  63325. * Updates a vertex of a particle : it can be overwritten by the user.
  63326. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  63327. * @param particle the current particle
  63328. * @param vertex the current index of the current particle
  63329. * @param pt the index of the current vertex in the particle shape
  63330. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  63331. * @example : just set a vertex particle position
  63332. * @returns the updated vertex
  63333. */
  63334. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  63335. return vertex;
  63336. };
  63337. /**
  63338. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  63339. * This does nothing and may be overwritten by the user.
  63340. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  63341. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  63342. * @param update the boolean update value actually passed to setParticles()
  63343. */
  63344. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  63345. };
  63346. /**
  63347. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  63348. * This will be passed three parameters.
  63349. * This does nothing and may be overwritten by the user.
  63350. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  63351. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  63352. * @param update the boolean update value actually passed to setParticles()
  63353. */
  63354. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  63355. };
  63356. return SolidParticleSystem;
  63357. }());
  63358. BABYLON.SolidParticleSystem = SolidParticleSystem;
  63359. })(BABYLON || (BABYLON = {}));
  63360. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  63361. var BABYLON;
  63362. (function (BABYLON) {
  63363. /**
  63364. * Class containing static functions to help procedurally build meshes
  63365. */
  63366. var MeshBuilder = /** @class */ (function () {
  63367. function MeshBuilder() {
  63368. }
  63369. MeshBuilder.updateSideOrientation = function (orientation) {
  63370. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  63371. return BABYLON.Mesh.DOUBLESIDE;
  63372. }
  63373. if (orientation === undefined || orientation === null) {
  63374. return BABYLON.Mesh.FRONTSIDE;
  63375. }
  63376. return orientation;
  63377. };
  63378. /**
  63379. * Creates a box mesh
  63380. * * The parameter `size` sets the size (float) of each box side (default 1)
  63381. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  63382. * * 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)
  63383. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  63384. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63385. * * 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
  63386. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63387. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  63388. * @param name defines the name of the mesh
  63389. * @param options defines the options used to create the mesh
  63390. * @param scene defines the hosting scene
  63391. * @returns the box mesh
  63392. */
  63393. MeshBuilder.CreateBox = function (name, options, scene) {
  63394. if (scene === void 0) { scene = null; }
  63395. var box = new BABYLON.Mesh(name, scene);
  63396. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63397. box._originalBuilderSideOrientation = options.sideOrientation;
  63398. var vertexData = BABYLON.VertexData.CreateBox(options);
  63399. vertexData.applyToMesh(box, options.updatable);
  63400. return box;
  63401. };
  63402. /**
  63403. * Creates a sphere mesh
  63404. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  63405. * * 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`)
  63406. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  63407. * * 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
  63408. * * 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)
  63409. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63410. * * 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
  63411. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63412. * @param name defines the name of the mesh
  63413. * @param options defines the options used to create the mesh
  63414. * @param scene defines the hosting scene
  63415. * @returns the sphere mesh
  63416. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  63417. */
  63418. MeshBuilder.CreateSphere = function (name, options, scene) {
  63419. var sphere = new BABYLON.Mesh(name, scene);
  63420. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63421. sphere._originalBuilderSideOrientation = options.sideOrientation;
  63422. var vertexData = BABYLON.VertexData.CreateSphere(options);
  63423. vertexData.applyToMesh(sphere, options.updatable);
  63424. return sphere;
  63425. };
  63426. /**
  63427. * Creates a plane polygonal mesh. By default, this is a disc
  63428. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  63429. * * 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
  63430. * * 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
  63431. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63432. * * 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
  63433. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63434. * @param name defines the name of the mesh
  63435. * @param options defines the options used to create the mesh
  63436. * @param scene defines the hosting scene
  63437. * @returns the plane polygonal mesh
  63438. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  63439. */
  63440. MeshBuilder.CreateDisc = function (name, options, scene) {
  63441. if (scene === void 0) { scene = null; }
  63442. var disc = new BABYLON.Mesh(name, scene);
  63443. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63444. disc._originalBuilderSideOrientation = options.sideOrientation;
  63445. var vertexData = BABYLON.VertexData.CreateDisc(options);
  63446. vertexData.applyToMesh(disc, options.updatable);
  63447. return disc;
  63448. };
  63449. /**
  63450. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  63451. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  63452. * * 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`)
  63453. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  63454. * * 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
  63455. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63456. * * 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
  63457. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63458. * @param name defines the name of the mesh
  63459. * @param options defines the options used to create the mesh
  63460. * @param scene defines the hosting scene
  63461. * @returns the icosahedron mesh
  63462. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  63463. */
  63464. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  63465. var sphere = new BABYLON.Mesh(name, scene);
  63466. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63467. sphere._originalBuilderSideOrientation = options.sideOrientation;
  63468. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  63469. vertexData.applyToMesh(sphere, options.updatable);
  63470. return sphere;
  63471. };
  63472. ;
  63473. /**
  63474. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  63475. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  63476. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  63477. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  63478. * * 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
  63479. * * 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
  63480. * * 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
  63481. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63482. * * 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
  63483. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  63484. * * 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
  63485. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  63486. * * 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
  63487. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  63488. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63489. * @param name defines the name of the mesh
  63490. * @param options defines the options used to create the mesh
  63491. * @param scene defines the hosting scene
  63492. * @returns the ribbon mesh
  63493. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  63494. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  63495. */
  63496. MeshBuilder.CreateRibbon = function (name, options, scene) {
  63497. if (scene === void 0) { scene = null; }
  63498. var pathArray = options.pathArray;
  63499. var closeArray = options.closeArray;
  63500. var closePath = options.closePath;
  63501. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63502. var instance = options.instance;
  63503. var updatable = options.updatable;
  63504. if (instance) { // existing ribbon instance update
  63505. // positionFunction : ribbon case
  63506. // only pathArray and sideOrientation parameters are taken into account for positions update
  63507. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  63508. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  63509. var positionFunction = function (positions) {
  63510. var minlg = pathArray[0].length;
  63511. var i = 0;
  63512. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  63513. for (var si = 1; si <= ns; si++) {
  63514. for (var p = 0; p < pathArray.length; p++) {
  63515. var path = pathArray[p];
  63516. var l = path.length;
  63517. minlg = (minlg < l) ? minlg : l;
  63518. var j = 0;
  63519. while (j < minlg) {
  63520. positions[i] = path[j].x;
  63521. positions[i + 1] = path[j].y;
  63522. positions[i + 2] = path[j].z;
  63523. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  63524. BABYLON.Tmp.Vector3[0].x = path[j].x;
  63525. }
  63526. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  63527. BABYLON.Tmp.Vector3[1].x = path[j].x;
  63528. }
  63529. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  63530. BABYLON.Tmp.Vector3[0].y = path[j].y;
  63531. }
  63532. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  63533. BABYLON.Tmp.Vector3[1].y = path[j].y;
  63534. }
  63535. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  63536. BABYLON.Tmp.Vector3[0].z = path[j].z;
  63537. }
  63538. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  63539. BABYLON.Tmp.Vector3[1].z = path[j].z;
  63540. }
  63541. j++;
  63542. i += 3;
  63543. }
  63544. if (instance._closePath) {
  63545. positions[i] = path[0].x;
  63546. positions[i + 1] = path[0].y;
  63547. positions[i + 2] = path[0].z;
  63548. i += 3;
  63549. }
  63550. }
  63551. }
  63552. };
  63553. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  63554. positionFunction(positions);
  63555. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  63556. instance._boundingInfo.update(instance._worldMatrix);
  63557. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  63558. if (options.colors) {
  63559. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  63560. for (var c = 0; c < options.colors.length; c++) {
  63561. colors[c * 4] = options.colors[c].r;
  63562. colors[c * 4 + 1] = options.colors[c].g;
  63563. colors[c * 4 + 2] = options.colors[c].b;
  63564. colors[c * 4 + 3] = options.colors[c].a;
  63565. }
  63566. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  63567. }
  63568. if (options.uvs) {
  63569. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  63570. for (var i = 0; i < options.uvs.length; i++) {
  63571. uvs[i * 2] = options.uvs[i].x;
  63572. uvs[i * 2 + 1] = options.uvs[i].y;
  63573. }
  63574. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  63575. }
  63576. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  63577. var indices = instance.getIndices();
  63578. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  63579. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  63580. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  63581. if (instance._closePath) {
  63582. var indexFirst = 0;
  63583. var indexLast = 0;
  63584. for (var p = 0; p < pathArray.length; p++) {
  63585. indexFirst = instance._idx[p] * 3;
  63586. if (p + 1 < pathArray.length) {
  63587. indexLast = (instance._idx[p + 1] - 1) * 3;
  63588. }
  63589. else {
  63590. indexLast = normals.length - 3;
  63591. }
  63592. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  63593. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  63594. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  63595. normals[indexLast] = normals[indexFirst];
  63596. normals[indexLast + 1] = normals[indexFirst + 1];
  63597. normals[indexLast + 2] = normals[indexFirst + 2];
  63598. }
  63599. }
  63600. if (!(instance.areNormalsFrozen)) {
  63601. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  63602. }
  63603. }
  63604. return instance;
  63605. }
  63606. else { // new ribbon creation
  63607. var ribbon = new BABYLON.Mesh(name, scene);
  63608. ribbon._originalBuilderSideOrientation = sideOrientation;
  63609. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  63610. if (closePath) {
  63611. ribbon._idx = vertexData._idx;
  63612. }
  63613. ribbon._closePath = closePath;
  63614. ribbon._closeArray = closeArray;
  63615. vertexData.applyToMesh(ribbon, updatable);
  63616. return ribbon;
  63617. }
  63618. };
  63619. /**
  63620. * Creates a cylinder or a cone mesh
  63621. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  63622. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  63623. * * 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.
  63624. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  63625. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  63626. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  63627. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  63628. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  63629. * * 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).
  63630. * * 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
  63631. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  63632. * * 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
  63633. * * 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.
  63634. * * If `enclose` is false, a ring surface is one element.
  63635. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  63636. * * 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
  63637. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63638. * * 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
  63639. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63640. * @param name defines the name of the mesh
  63641. * @param options defines the options used to create the mesh
  63642. * @param scene defines the hosting scene
  63643. * @returns the cylinder mesh
  63644. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  63645. */
  63646. MeshBuilder.CreateCylinder = function (name, options, scene) {
  63647. var cylinder = new BABYLON.Mesh(name, scene);
  63648. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63649. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  63650. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  63651. vertexData.applyToMesh(cylinder, options.updatable);
  63652. return cylinder;
  63653. };
  63654. /**
  63655. * Creates a torus mesh
  63656. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  63657. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  63658. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  63659. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63660. * * 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
  63661. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63662. * @param name defines the name of the mesh
  63663. * @param options defines the options used to create the mesh
  63664. * @param scene defines the hosting scene
  63665. * @returns the torus mesh
  63666. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  63667. */
  63668. MeshBuilder.CreateTorus = function (name, options, scene) {
  63669. var torus = new BABYLON.Mesh(name, scene);
  63670. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63671. torus._originalBuilderSideOrientation = options.sideOrientation;
  63672. var vertexData = BABYLON.VertexData.CreateTorus(options);
  63673. vertexData.applyToMesh(torus, options.updatable);
  63674. return torus;
  63675. };
  63676. /**
  63677. * Creates a torus knot mesh
  63678. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  63679. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  63680. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  63681. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  63682. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63683. * * 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
  63684. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63685. * @param name defines the name of the mesh
  63686. * @param options defines the options used to create the mesh
  63687. * @param scene defines the hosting scene
  63688. * @returns the torus knot mesh
  63689. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  63690. */
  63691. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  63692. var torusKnot = new BABYLON.Mesh(name, scene);
  63693. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63694. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  63695. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  63696. vertexData.applyToMesh(torusKnot, options.updatable);
  63697. return torusKnot;
  63698. };
  63699. /**
  63700. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  63701. * * 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
  63702. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  63703. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  63704. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  63705. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  63706. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  63707. * * 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
  63708. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  63709. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63710. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  63711. * @param name defines the name of the new line system
  63712. * @param options defines the options used to create the line system
  63713. * @param scene defines the hosting scene
  63714. * @returns a new line system mesh
  63715. */
  63716. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  63717. var instance = options.instance;
  63718. var lines = options.lines;
  63719. var colors = options.colors;
  63720. if (instance) { // lines update
  63721. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  63722. var vertexColor;
  63723. var lineColors;
  63724. if (colors) {
  63725. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  63726. }
  63727. var i = 0;
  63728. var c = 0;
  63729. for (var l = 0; l < lines.length; l++) {
  63730. var points = lines[l];
  63731. for (var p = 0; p < points.length; p++) {
  63732. positions[i] = points[p].x;
  63733. positions[i + 1] = points[p].y;
  63734. positions[i + 2] = points[p].z;
  63735. if (colors && vertexColor) {
  63736. lineColors = colors[l];
  63737. vertexColor[c] = lineColors[p].r;
  63738. vertexColor[c + 1] = lineColors[p].g;
  63739. vertexColor[c + 2] = lineColors[p].b;
  63740. vertexColor[c + 3] = lineColors[p].a;
  63741. c += 4;
  63742. }
  63743. i += 3;
  63744. }
  63745. }
  63746. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  63747. if (colors && vertexColor) {
  63748. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  63749. }
  63750. return instance;
  63751. }
  63752. // line system creation
  63753. var useVertexColor = (colors) ? true : false;
  63754. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  63755. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  63756. vertexData.applyToMesh(lineSystem, options.updatable);
  63757. return lineSystem;
  63758. };
  63759. /**
  63760. * Creates a line mesh
  63761. * 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
  63762. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  63763. * * The parameter `points` is an array successive Vector3
  63764. * * 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
  63765. * * The optional parameter `colors` is an array of successive Color4, one per line point
  63766. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  63767. * * When updating an instance, remember that only point positions can change, not the number of points
  63768. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63769. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  63770. * @param name defines the name of the new line system
  63771. * @param options defines the options used to create the line system
  63772. * @param scene defines the hosting scene
  63773. * @returns a new line mesh
  63774. */
  63775. MeshBuilder.CreateLines = function (name, options, scene) {
  63776. if (scene === void 0) { scene = null; }
  63777. var colors = (options.colors) ? [options.colors] : null;
  63778. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  63779. return lines;
  63780. };
  63781. /**
  63782. * Creates a dashed line mesh
  63783. * * 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
  63784. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  63785. * * The parameter `points` is an array successive Vector3
  63786. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  63787. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  63788. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  63789. * * 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
  63790. * * When updating an instance, remember that only point positions can change, not the number of points
  63791. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63792. * @param name defines the name of the mesh
  63793. * @param options defines the options used to create the mesh
  63794. * @param scene defines the hosting scene
  63795. * @returns the dashed line mesh
  63796. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  63797. */
  63798. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  63799. if (scene === void 0) { scene = null; }
  63800. var points = options.points;
  63801. var instance = options.instance;
  63802. var gapSize = options.gapSize || 1;
  63803. var dashSize = options.dashSize || 3;
  63804. if (instance) { // dashed lines update
  63805. var positionFunction = function (positions) {
  63806. var curvect = BABYLON.Vector3.Zero();
  63807. var nbSeg = positions.length / 6;
  63808. var lg = 0;
  63809. var nb = 0;
  63810. var shft = 0;
  63811. var dashshft = 0;
  63812. var curshft = 0;
  63813. var p = 0;
  63814. var i = 0;
  63815. var j = 0;
  63816. for (i = 0; i < points.length - 1; i++) {
  63817. points[i + 1].subtractToRef(points[i], curvect);
  63818. lg += curvect.length();
  63819. }
  63820. shft = lg / nbSeg;
  63821. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  63822. for (i = 0; i < points.length - 1; i++) {
  63823. points[i + 1].subtractToRef(points[i], curvect);
  63824. nb = Math.floor(curvect.length() / shft);
  63825. curvect.normalize();
  63826. j = 0;
  63827. while (j < nb && p < positions.length) {
  63828. curshft = shft * j;
  63829. positions[p] = points[i].x + curshft * curvect.x;
  63830. positions[p + 1] = points[i].y + curshft * curvect.y;
  63831. positions[p + 2] = points[i].z + curshft * curvect.z;
  63832. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  63833. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  63834. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  63835. p += 6;
  63836. j++;
  63837. }
  63838. }
  63839. while (p < positions.length) {
  63840. positions[p] = points[i].x;
  63841. positions[p + 1] = points[i].y;
  63842. positions[p + 2] = points[i].z;
  63843. p += 3;
  63844. }
  63845. };
  63846. instance.updateMeshPositions(positionFunction, false);
  63847. return instance;
  63848. }
  63849. // dashed lines creation
  63850. var dashedLines = new BABYLON.LinesMesh(name, scene);
  63851. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  63852. vertexData.applyToMesh(dashedLines, options.updatable);
  63853. dashedLines.dashSize = dashSize;
  63854. dashedLines.gapSize = gapSize;
  63855. return dashedLines;
  63856. };
  63857. /**
  63858. * 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.
  63859. * * 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.
  63860. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  63861. * * 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.
  63862. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  63863. * * 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
  63864. * * 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
  63865. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  63866. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63867. * * 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
  63868. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  63869. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63870. * @param name defines the name of the mesh
  63871. * @param options defines the options used to create the mesh
  63872. * @param scene defines the hosting scene
  63873. * @returns the extruded shape mesh
  63874. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  63875. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  63876. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  63877. */
  63878. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  63879. if (scene === void 0) { scene = null; }
  63880. var path = options.path;
  63881. var shape = options.shape;
  63882. var scale = options.scale || 1;
  63883. var rotation = options.rotation || 0;
  63884. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  63885. var updatable = options.updatable;
  63886. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63887. var instance = options.instance || null;
  63888. var invertUV = options.invertUV || false;
  63889. 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);
  63890. };
  63891. /**
  63892. * Creates an custom extruded shape mesh.
  63893. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  63894. * * 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.
  63895. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  63896. * * 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
  63897. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  63898. * * 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
  63899. * * It must returns a float value that will be the scale value applied to the shape on each path point
  63900. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  63901. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  63902. * * 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
  63903. * * 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
  63904. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  63905. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63906. * * 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
  63907. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  63908. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63909. * @param name defines the name of the mesh
  63910. * @param options defines the options used to create the mesh
  63911. * @param scene defines the hosting scene
  63912. * @returns the custom extruded shape mesh
  63913. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  63914. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  63915. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  63916. */
  63917. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  63918. var path = options.path;
  63919. var shape = options.shape;
  63920. var scaleFunction = options.scaleFunction || (function () { return 1; });
  63921. var rotationFunction = options.rotationFunction || (function () { return 0; });
  63922. var ribbonCloseArray = options.ribbonCloseArray || false;
  63923. var ribbonClosePath = options.ribbonClosePath || false;
  63924. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  63925. var updatable = options.updatable;
  63926. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63927. var instance = options.instance;
  63928. var invertUV = options.invertUV || false;
  63929. 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);
  63930. };
  63931. /**
  63932. * Creates lathe mesh.
  63933. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  63934. * * 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
  63935. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  63936. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  63937. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  63938. * * 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
  63939. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  63940. * * 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
  63941. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63942. * * 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
  63943. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  63944. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63945. * @param name defines the name of the mesh
  63946. * @param options defines the options used to create the mesh
  63947. * @param scene defines the hosting scene
  63948. * @returns the lathe mesh
  63949. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  63950. */
  63951. MeshBuilder.CreateLathe = function (name, options, scene) {
  63952. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  63953. var closed = (options.closed === undefined) ? true : options.closed;
  63954. var shape = options.shape;
  63955. var radius = options.radius || 1;
  63956. var tessellation = options.tessellation || 64;
  63957. var clip = options.clip || 0;
  63958. var updatable = options.updatable;
  63959. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63960. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  63961. var pi2 = Math.PI * 2;
  63962. var paths = new Array();
  63963. var invertUV = options.invertUV || false;
  63964. var i = 0;
  63965. var p = 0;
  63966. var step = pi2 / tessellation * arc;
  63967. var rotated;
  63968. var path = new Array();
  63969. for (i = 0; i <= tessellation - clip; i++) {
  63970. var path = [];
  63971. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  63972. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  63973. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  63974. }
  63975. for (p = 0; p < shape.length; p++) {
  63976. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  63977. path.push(rotated);
  63978. }
  63979. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  63980. 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));
  63981. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  63982. }
  63983. paths.push(path);
  63984. }
  63985. // lathe ribbon
  63986. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  63987. return lathe;
  63988. };
  63989. /**
  63990. * Creates a plane mesh
  63991. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  63992. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  63993. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  63994. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63995. * * 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
  63996. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63997. * @param name defines the name of the mesh
  63998. * @param options defines the options used to create the mesh
  63999. * @param scene defines the hosting scene
  64000. * @returns the plane mesh
  64001. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  64002. */
  64003. MeshBuilder.CreatePlane = function (name, options, scene) {
  64004. var plane = new BABYLON.Mesh(name, scene);
  64005. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64006. plane._originalBuilderSideOrientation = options.sideOrientation;
  64007. var vertexData = BABYLON.VertexData.CreatePlane(options);
  64008. vertexData.applyToMesh(plane, options.updatable);
  64009. if (options.sourcePlane) {
  64010. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  64011. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  64012. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  64013. plane.rotate(vectorProduct, product);
  64014. }
  64015. return plane;
  64016. };
  64017. /**
  64018. * Creates a ground mesh
  64019. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  64020. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  64021. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64022. * @param name defines the name of the mesh
  64023. * @param options defines the options used to create the mesh
  64024. * @param scene defines the hosting scene
  64025. * @returns the ground mesh
  64026. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  64027. */
  64028. MeshBuilder.CreateGround = function (name, options, scene) {
  64029. var ground = new BABYLON.GroundMesh(name, scene);
  64030. ground._setReady(false);
  64031. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  64032. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  64033. ground._width = options.width || 1;
  64034. ground._height = options.height || 1;
  64035. ground._maxX = ground._width / 2;
  64036. ground._maxZ = ground._height / 2;
  64037. ground._minX = -ground._maxX;
  64038. ground._minZ = -ground._maxZ;
  64039. var vertexData = BABYLON.VertexData.CreateGround(options);
  64040. vertexData.applyToMesh(ground, options.updatable);
  64041. ground._setReady(true);
  64042. return ground;
  64043. };
  64044. /**
  64045. * Creates a tiled ground mesh
  64046. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  64047. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  64048. * * 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
  64049. * * 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
  64050. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64051. * @param name defines the name of the mesh
  64052. * @param options defines the options used to create the mesh
  64053. * @param scene defines the hosting scene
  64054. * @returns the tiled ground mesh
  64055. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  64056. */
  64057. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  64058. var tiledGround = new BABYLON.Mesh(name, scene);
  64059. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  64060. vertexData.applyToMesh(tiledGround, options.updatable);
  64061. return tiledGround;
  64062. };
  64063. /**
  64064. * Creates a ground mesh from a height map
  64065. * * The parameter `url` sets the URL of the height map image resource.
  64066. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  64067. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  64068. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  64069. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  64070. * * 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.
  64071. * * 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).
  64072. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64073. * @param name defines the name of the mesh
  64074. * @param url defines the url to the height map
  64075. * @param options defines the options used to create the mesh
  64076. * @param scene defines the hosting scene
  64077. * @returns the ground mesh
  64078. * @see http://doc.babylonjs.com/babylon101/height_map
  64079. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  64080. */
  64081. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  64082. var width = options.width || 10.0;
  64083. var height = options.height || 10.0;
  64084. var subdivisions = options.subdivisions || 1 | 0;
  64085. var minHeight = options.minHeight || 0.0;
  64086. var maxHeight = options.maxHeight || 1.0;
  64087. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  64088. var updatable = options.updatable;
  64089. var onReady = options.onReady;
  64090. var ground = new BABYLON.GroundMesh(name, scene);
  64091. ground._subdivisionsX = subdivisions;
  64092. ground._subdivisionsY = subdivisions;
  64093. ground._width = width;
  64094. ground._height = height;
  64095. ground._maxX = ground._width / 2.0;
  64096. ground._maxZ = ground._height / 2.0;
  64097. ground._minX = -ground._maxX;
  64098. ground._minZ = -ground._maxZ;
  64099. ground._setReady(false);
  64100. var onload = function (img) {
  64101. // Getting height map data
  64102. var canvas = document.createElement("canvas");
  64103. var context = canvas.getContext("2d");
  64104. if (!context) {
  64105. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  64106. }
  64107. if (scene.isDisposed) {
  64108. return;
  64109. }
  64110. var bufferWidth = img.width;
  64111. var bufferHeight = img.height;
  64112. canvas.width = bufferWidth;
  64113. canvas.height = bufferHeight;
  64114. context.drawImage(img, 0, 0);
  64115. // Create VertexData from map data
  64116. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  64117. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  64118. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  64119. width: width, height: height,
  64120. subdivisions: subdivisions,
  64121. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  64122. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  64123. });
  64124. vertexData.applyToMesh(ground, updatable);
  64125. //execute ready callback, if set
  64126. if (onReady) {
  64127. onReady(ground);
  64128. }
  64129. ground._setReady(true);
  64130. };
  64131. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  64132. return ground;
  64133. };
  64134. /**
  64135. * Creates a polygon mesh
  64136. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  64137. * * 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
  64138. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64139. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64140. * * 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)
  64141. * * Remember you can only change the shape positions, not their number when updating a polygon
  64142. * @param name defines the name of the mesh
  64143. * @param options defines the options used to create the mesh
  64144. * @param scene defines the hosting scene
  64145. * @returns the polygon mesh
  64146. */
  64147. MeshBuilder.CreatePolygon = function (name, options, scene) {
  64148. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64149. var shape = options.shape;
  64150. var holes = options.holes || [];
  64151. var depth = options.depth || 0;
  64152. var contours = [];
  64153. var hole = [];
  64154. for (var i = 0; i < shape.length; i++) {
  64155. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  64156. }
  64157. var epsilon = 0.00000001;
  64158. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  64159. contours.pop();
  64160. }
  64161. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  64162. for (var hNb = 0; hNb < holes.length; hNb++) {
  64163. hole = [];
  64164. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  64165. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  64166. }
  64167. polygonTriangulation.addHole(hole);
  64168. }
  64169. var polygon = polygonTriangulation.build(options.updatable, depth);
  64170. polygon._originalBuilderSideOrientation = options.sideOrientation;
  64171. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  64172. vertexData.applyToMesh(polygon, options.updatable);
  64173. return polygon;
  64174. };
  64175. ;
  64176. /**
  64177. * Creates an extruded polygon mesh, with depth in the Y direction.
  64178. * * 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)
  64179. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  64180. * @param name defines the name of the mesh
  64181. * @param options defines the options used to create the mesh
  64182. * @param scene defines the hosting scene
  64183. * @returns the polygon mesh
  64184. */
  64185. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  64186. return MeshBuilder.CreatePolygon(name, options, scene);
  64187. };
  64188. ;
  64189. /**
  64190. * Creates a tube mesh.
  64191. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  64192. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  64193. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  64194. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  64195. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  64196. * * 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)
  64197. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  64198. * * 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
  64199. * * 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
  64200. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64201. * * 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
  64202. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  64203. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64204. * @param name defines the name of the mesh
  64205. * @param options defines the options used to create the mesh
  64206. * @param scene defines the hosting scene
  64207. * @returns the tube mesh
  64208. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  64209. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  64210. */
  64211. MeshBuilder.CreateTube = function (name, options, scene) {
  64212. var path = options.path;
  64213. var instance = options.instance;
  64214. var radius = 1.0;
  64215. if (instance) {
  64216. radius = instance.radius;
  64217. }
  64218. if (options.radius !== undefined) {
  64219. radius = options.radius;
  64220. }
  64221. ;
  64222. var tessellation = options.tessellation || 64 | 0;
  64223. var radiusFunction = options.radiusFunction || null;
  64224. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  64225. var invertUV = options.invertUV || false;
  64226. var updatable = options.updatable;
  64227. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64228. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  64229. // tube geometry
  64230. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  64231. var tangents = path3D.getTangents();
  64232. var normals = path3D.getNormals();
  64233. var distances = path3D.getDistances();
  64234. var pi2 = Math.PI * 2;
  64235. var step = pi2 / tessellation * arc;
  64236. var returnRadius = function () { return radius; };
  64237. var radiusFunctionFinal = radiusFunction || returnRadius;
  64238. var circlePath;
  64239. var rad;
  64240. var normal;
  64241. var rotated;
  64242. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  64243. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  64244. for (var i = 0; i < path.length; i++) {
  64245. rad = radiusFunctionFinal(i, distances[i]); // current radius
  64246. circlePath = Array(); // current circle array
  64247. normal = normals[i]; // current normal
  64248. for (var t = 0; t < tessellation; t++) {
  64249. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  64250. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  64251. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  64252. rotated.scaleInPlace(rad).addInPlace(path[i]);
  64253. circlePath[t] = rotated;
  64254. }
  64255. circlePaths[index] = circlePath;
  64256. index++;
  64257. }
  64258. // cap
  64259. var capPath = function (nbPoints, pathIndex) {
  64260. var pointCap = Array();
  64261. for (var i = 0; i < nbPoints; i++) {
  64262. pointCap.push(path[pathIndex]);
  64263. }
  64264. return pointCap;
  64265. };
  64266. switch (cap) {
  64267. case BABYLON.Mesh.NO_CAP:
  64268. break;
  64269. case BABYLON.Mesh.CAP_START:
  64270. circlePaths[0] = capPath(tessellation, 0);
  64271. circlePaths[1] = circlePaths[2].slice(0);
  64272. break;
  64273. case BABYLON.Mesh.CAP_END:
  64274. circlePaths[index] = circlePaths[index - 1].slice(0);
  64275. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  64276. break;
  64277. case BABYLON.Mesh.CAP_ALL:
  64278. circlePaths[0] = capPath(tessellation, 0);
  64279. circlePaths[1] = circlePaths[2].slice(0);
  64280. circlePaths[index] = circlePaths[index - 1].slice(0);
  64281. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  64282. break;
  64283. default:
  64284. break;
  64285. }
  64286. return circlePaths;
  64287. };
  64288. var path3D;
  64289. var pathArray;
  64290. if (instance) { // tube update
  64291. var arc = options.arc || instance.arc;
  64292. path3D = (instance.path3D).update(path);
  64293. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  64294. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  64295. instance.path3D = path3D;
  64296. instance.pathArray = pathArray;
  64297. instance.arc = arc;
  64298. instance.radius = radius;
  64299. return instance;
  64300. }
  64301. // tube creation
  64302. path3D = new BABYLON.Path3D(path);
  64303. var newPathArray = new Array();
  64304. cap = (cap < 0 || cap > 3) ? 0 : cap;
  64305. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  64306. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  64307. tube.pathArray = pathArray;
  64308. tube.path3D = path3D;
  64309. tube.tessellation = tessellation;
  64310. tube.cap = cap;
  64311. tube.arc = options.arc;
  64312. tube.radius = radius;
  64313. return tube;
  64314. };
  64315. /**
  64316. * Creates a polyhedron mesh
  64317. * * 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
  64318. * * The parameter `size` (positive float, default 1) sets the polygon size
  64319. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  64320. * * 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`
  64321. * * 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
  64322. * * 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)`)
  64323. * * 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
  64324. * * 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
  64325. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64326. * * 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
  64327. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64328. * @param name defines the name of the mesh
  64329. * @param options defines the options used to create the mesh
  64330. * @param scene defines the hosting scene
  64331. * @returns the polyhedron mesh
  64332. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  64333. */
  64334. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  64335. var polyhedron = new BABYLON.Mesh(name, scene);
  64336. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64337. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  64338. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  64339. vertexData.applyToMesh(polyhedron, options.updatable);
  64340. return polyhedron;
  64341. };
  64342. /**
  64343. * Creates a decal mesh.
  64344. * 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
  64345. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  64346. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  64347. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  64348. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  64349. * @param name defines the name of the mesh
  64350. * @param sourceMesh defines the mesh where the decal must be applied
  64351. * @param options defines the options used to create the mesh
  64352. * @param scene defines the hosting scene
  64353. * @returns the decal mesh
  64354. * @see http://doc.babylonjs.com/how_to/decals
  64355. */
  64356. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  64357. var indices = sourceMesh.getIndices();
  64358. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64359. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  64360. var position = options.position || BABYLON.Vector3.Zero();
  64361. var normal = options.normal || BABYLON.Vector3.Up();
  64362. var size = options.size || BABYLON.Vector3.One();
  64363. var angle = options.angle || 0;
  64364. // Getting correct rotation
  64365. if (!normal) {
  64366. var target = new BABYLON.Vector3(0, 0, 1);
  64367. var camera = sourceMesh.getScene().activeCamera;
  64368. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  64369. normal = camera.globalPosition.subtract(cameraWorldTarget);
  64370. }
  64371. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  64372. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  64373. var pitch = Math.atan2(normal.y, len);
  64374. // Matrix
  64375. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  64376. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  64377. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  64378. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  64379. var vertexData = new BABYLON.VertexData();
  64380. vertexData.indices = [];
  64381. vertexData.positions = [];
  64382. vertexData.normals = [];
  64383. vertexData.uvs = [];
  64384. var currentVertexDataIndex = 0;
  64385. var extractDecalVector3 = function (indexId) {
  64386. var result = new BABYLON.PositionNormalVertex();
  64387. if (!indices || !positions || !normals) {
  64388. return result;
  64389. }
  64390. var vertexId = indices[indexId];
  64391. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  64392. // Send vector to decal local world
  64393. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  64394. // Get normal
  64395. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  64396. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  64397. return result;
  64398. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  64399. var clip = function (vertices, axis) {
  64400. if (vertices.length === 0) {
  64401. return vertices;
  64402. }
  64403. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  64404. var clipVertices = function (v0, v1) {
  64405. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  64406. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  64407. };
  64408. var result = new Array();
  64409. for (var index = 0; index < vertices.length; index += 3) {
  64410. var v1Out;
  64411. var v2Out;
  64412. var v3Out;
  64413. var total = 0;
  64414. var nV1 = null;
  64415. var nV2 = null;
  64416. var nV3 = null;
  64417. var nV4 = null;
  64418. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  64419. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  64420. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  64421. v1Out = d1 > 0;
  64422. v2Out = d2 > 0;
  64423. v3Out = d3 > 0;
  64424. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  64425. switch (total) {
  64426. case 0:
  64427. result.push(vertices[index]);
  64428. result.push(vertices[index + 1]);
  64429. result.push(vertices[index + 2]);
  64430. break;
  64431. case 1:
  64432. if (v1Out) {
  64433. nV1 = vertices[index + 1];
  64434. nV2 = vertices[index + 2];
  64435. nV3 = clipVertices(vertices[index], nV1);
  64436. nV4 = clipVertices(vertices[index], nV2);
  64437. }
  64438. if (v2Out) {
  64439. nV1 = vertices[index];
  64440. nV2 = vertices[index + 2];
  64441. nV3 = clipVertices(vertices[index + 1], nV1);
  64442. nV4 = clipVertices(vertices[index + 1], nV2);
  64443. result.push(nV3);
  64444. result.push(nV2.clone());
  64445. result.push(nV1.clone());
  64446. result.push(nV2.clone());
  64447. result.push(nV3.clone());
  64448. result.push(nV4);
  64449. break;
  64450. }
  64451. if (v3Out) {
  64452. nV1 = vertices[index];
  64453. nV2 = vertices[index + 1];
  64454. nV3 = clipVertices(vertices[index + 2], nV1);
  64455. nV4 = clipVertices(vertices[index + 2], nV2);
  64456. }
  64457. if (nV1 && nV2 && nV3 && nV4) {
  64458. result.push(nV1.clone());
  64459. result.push(nV2.clone());
  64460. result.push(nV3);
  64461. result.push(nV4);
  64462. result.push(nV3.clone());
  64463. result.push(nV2.clone());
  64464. }
  64465. break;
  64466. case 2:
  64467. if (!v1Out) {
  64468. nV1 = vertices[index].clone();
  64469. nV2 = clipVertices(nV1, vertices[index + 1]);
  64470. nV3 = clipVertices(nV1, vertices[index + 2]);
  64471. result.push(nV1);
  64472. result.push(nV2);
  64473. result.push(nV3);
  64474. }
  64475. if (!v2Out) {
  64476. nV1 = vertices[index + 1].clone();
  64477. nV2 = clipVertices(nV1, vertices[index + 2]);
  64478. nV3 = clipVertices(nV1, vertices[index]);
  64479. result.push(nV1);
  64480. result.push(nV2);
  64481. result.push(nV3);
  64482. }
  64483. if (!v3Out) {
  64484. nV1 = vertices[index + 2].clone();
  64485. nV2 = clipVertices(nV1, vertices[index]);
  64486. nV3 = clipVertices(nV1, vertices[index + 1]);
  64487. result.push(nV1);
  64488. result.push(nV2);
  64489. result.push(nV3);
  64490. }
  64491. break;
  64492. case 3:
  64493. break;
  64494. }
  64495. }
  64496. return result;
  64497. };
  64498. for (var index = 0; index < indices.length; index += 3) {
  64499. var faceVertices = new Array();
  64500. faceVertices.push(extractDecalVector3(index));
  64501. faceVertices.push(extractDecalVector3(index + 1));
  64502. faceVertices.push(extractDecalVector3(index + 2));
  64503. // Clip
  64504. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  64505. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  64506. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  64507. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  64508. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  64509. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  64510. if (faceVertices.length === 0) {
  64511. continue;
  64512. }
  64513. // Add UVs and get back to world
  64514. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  64515. var vertex = faceVertices[vIndex];
  64516. //TODO check for Int32Array | Uint32Array | Uint16Array
  64517. vertexData.indices.push(currentVertexDataIndex);
  64518. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  64519. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  64520. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  64521. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  64522. currentVertexDataIndex++;
  64523. }
  64524. }
  64525. // Return mesh
  64526. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  64527. vertexData.applyToMesh(decal);
  64528. decal.position = position.clone();
  64529. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  64530. return decal;
  64531. };
  64532. // Privates
  64533. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  64534. // extrusion geometry
  64535. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  64536. var tangents = path3D.getTangents();
  64537. var normals = path3D.getNormals();
  64538. var binormals = path3D.getBinormals();
  64539. var distances = path3D.getDistances();
  64540. var angle = 0;
  64541. var returnScale = function () { return scale !== null ? scale : 1; };
  64542. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  64543. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  64544. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  64545. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  64546. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  64547. for (var i = 0; i < curve.length; i++) {
  64548. var shapePath = new Array();
  64549. var angleStep = rotate(i, distances[i]);
  64550. var scaleRatio = scl(i, distances[i]);
  64551. for (var p = 0; p < shape.length; p++) {
  64552. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  64553. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  64554. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  64555. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  64556. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  64557. shapePath[p] = rotated;
  64558. }
  64559. shapePaths[index] = shapePath;
  64560. angle += angleStep;
  64561. index++;
  64562. }
  64563. // cap
  64564. var capPath = function (shapePath) {
  64565. var pointCap = Array();
  64566. var barycenter = BABYLON.Vector3.Zero();
  64567. var i;
  64568. for (i = 0; i < shapePath.length; i++) {
  64569. barycenter.addInPlace(shapePath[i]);
  64570. }
  64571. barycenter.scaleInPlace(1.0 / shapePath.length);
  64572. for (i = 0; i < shapePath.length; i++) {
  64573. pointCap.push(barycenter);
  64574. }
  64575. return pointCap;
  64576. };
  64577. switch (cap) {
  64578. case BABYLON.Mesh.NO_CAP:
  64579. break;
  64580. case BABYLON.Mesh.CAP_START:
  64581. shapePaths[0] = capPath(shapePaths[2]);
  64582. shapePaths[1] = shapePaths[2];
  64583. break;
  64584. case BABYLON.Mesh.CAP_END:
  64585. shapePaths[index] = shapePaths[index - 1];
  64586. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  64587. break;
  64588. case BABYLON.Mesh.CAP_ALL:
  64589. shapePaths[0] = capPath(shapePaths[2]);
  64590. shapePaths[1] = shapePaths[2];
  64591. shapePaths[index] = shapePaths[index - 1];
  64592. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  64593. break;
  64594. default:
  64595. break;
  64596. }
  64597. return shapePaths;
  64598. };
  64599. var path3D;
  64600. var pathArray;
  64601. if (instance) { // instance update
  64602. path3D = (instance.path3D).update(curve);
  64603. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  64604. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  64605. return instance;
  64606. }
  64607. // extruded shape creation
  64608. path3D = new BABYLON.Path3D(curve);
  64609. var newShapePaths = new Array();
  64610. cap = (cap < 0 || cap > 3) ? 0 : cap;
  64611. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  64612. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  64613. extrudedGeneric.pathArray = pathArray;
  64614. extrudedGeneric.path3D = path3D;
  64615. extrudedGeneric.cap = cap;
  64616. return extrudedGeneric;
  64617. };
  64618. return MeshBuilder;
  64619. }());
  64620. BABYLON.MeshBuilder = MeshBuilder;
  64621. })(BABYLON || (BABYLON = {}));
  64622. //# sourceMappingURL=babylon.meshBuilder.js.map
  64623. var BABYLON;
  64624. (function (BABYLON) {
  64625. /**
  64626. * Draco compression (https://google.github.io/draco/)
  64627. *
  64628. * This class wraps the Draco module.
  64629. *
  64630. * **Encoder**
  64631. *
  64632. * The encoder is not currently implemented.
  64633. *
  64634. * **Decoder**
  64635. *
  64636. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  64637. *
  64638. * To update the configuration, use the following code:
  64639. * ```javascript
  64640. * BABYLON.DracoCompression.Configuration = {
  64641. * decoder: {
  64642. * wasmUrl: "<url to the WebAssembly library>",
  64643. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  64644. * fallbackUrl: "<url to the fallback JavaScript library>",
  64645. * }
  64646. * };
  64647. * ```
  64648. *
  64649. * 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.
  64650. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  64651. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  64652. *
  64653. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  64654. * ```javascript
  64655. * var dracoCompression = new BABYLON.DracoCompression();
  64656. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  64657. * [BABYLON.VertexBuffer.PositionKind]: 0
  64658. * });
  64659. * ```
  64660. *
  64661. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  64662. */
  64663. var DracoCompression = /** @class */ (function () {
  64664. /**
  64665. * Constructor
  64666. */
  64667. function DracoCompression() {
  64668. }
  64669. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  64670. /**
  64671. * Returns true if the decoder is available.
  64672. */
  64673. get: function () {
  64674. if (typeof DracoDecoderModule !== "undefined") {
  64675. return true;
  64676. }
  64677. var decoder = DracoCompression.Configuration.decoder;
  64678. if (decoder) {
  64679. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  64680. return true;
  64681. }
  64682. if (decoder.fallbackUrl) {
  64683. return true;
  64684. }
  64685. }
  64686. return false;
  64687. },
  64688. enumerable: true,
  64689. configurable: true
  64690. });
  64691. /**
  64692. * Stop all async operations and release resources.
  64693. */
  64694. DracoCompression.prototype.dispose = function () {
  64695. };
  64696. /**
  64697. * Decode Draco compressed mesh data to vertex data.
  64698. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  64699. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  64700. * @returns A promise that resolves with the decoded vertex data
  64701. */
  64702. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  64703. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  64704. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  64705. var module = wrappedModule.module;
  64706. var vertexData = new BABYLON.VertexData();
  64707. var buffer = new module.DecoderBuffer();
  64708. buffer.Init(dataView, dataView.byteLength);
  64709. var decoder = new module.Decoder();
  64710. var geometry;
  64711. var status;
  64712. try {
  64713. var type = decoder.GetEncodedGeometryType(buffer);
  64714. switch (type) {
  64715. case module.TRIANGULAR_MESH:
  64716. geometry = new module.Mesh();
  64717. status = decoder.DecodeBufferToMesh(buffer, geometry);
  64718. break;
  64719. case module.POINT_CLOUD:
  64720. geometry = new module.PointCloud();
  64721. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  64722. break;
  64723. default:
  64724. throw new Error("Invalid geometry type " + type);
  64725. }
  64726. if (!status.ok() || !geometry.ptr) {
  64727. throw new Error(status.error_msg());
  64728. }
  64729. var numPoints = geometry.num_points();
  64730. if (type === module.TRIANGULAR_MESH) {
  64731. var numFaces = geometry.num_faces();
  64732. var faceIndices = new module.DracoInt32Array();
  64733. try {
  64734. var indices = new Uint32Array(numFaces * 3);
  64735. for (var i = 0; i < numFaces; i++) {
  64736. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  64737. var offset = i * 3;
  64738. indices[offset + 0] = faceIndices.GetValue(0);
  64739. indices[offset + 1] = faceIndices.GetValue(1);
  64740. indices[offset + 2] = faceIndices.GetValue(2);
  64741. }
  64742. vertexData.indices = indices;
  64743. }
  64744. finally {
  64745. module.destroy(faceIndices);
  64746. }
  64747. }
  64748. for (var kind in attributes) {
  64749. var uniqueId = attributes[kind];
  64750. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  64751. var dracoData = new module.DracoFloat32Array();
  64752. try {
  64753. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  64754. var babylonData = new Float32Array(numPoints * attribute.num_components());
  64755. for (var i = 0; i < babylonData.length; i++) {
  64756. babylonData[i] = dracoData.GetValue(i);
  64757. }
  64758. vertexData.set(babylonData, kind);
  64759. }
  64760. finally {
  64761. module.destroy(dracoData);
  64762. }
  64763. }
  64764. }
  64765. finally {
  64766. if (geometry) {
  64767. module.destroy(geometry);
  64768. }
  64769. module.destroy(decoder);
  64770. module.destroy(buffer);
  64771. }
  64772. return vertexData;
  64773. });
  64774. };
  64775. DracoCompression._GetDecoderModule = function () {
  64776. if (!DracoCompression._DecoderModulePromise) {
  64777. var promise = null;
  64778. var config_1 = {};
  64779. if (typeof DracoDecoderModule !== "undefined") {
  64780. promise = Promise.resolve();
  64781. }
  64782. else {
  64783. var decoder = DracoCompression.Configuration.decoder;
  64784. if (decoder) {
  64785. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  64786. promise = Promise.all([
  64787. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  64788. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  64789. config_1.wasmBinary = data;
  64790. })
  64791. ]);
  64792. }
  64793. else if (decoder.fallbackUrl) {
  64794. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  64795. }
  64796. }
  64797. }
  64798. if (!promise) {
  64799. throw new Error("Draco decoder module is not available");
  64800. }
  64801. DracoCompression._DecoderModulePromise = promise.then(function () {
  64802. return new Promise(function (resolve) {
  64803. config_1.onModuleLoaded = function (decoderModule) {
  64804. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  64805. resolve({ module: decoderModule });
  64806. };
  64807. DracoDecoderModule(config_1);
  64808. });
  64809. });
  64810. }
  64811. return DracoCompression._DecoderModulePromise;
  64812. };
  64813. DracoCompression._LoadScriptAsync = function (url) {
  64814. return new Promise(function (resolve, reject) {
  64815. BABYLON.Tools.LoadScript(url, function () {
  64816. resolve();
  64817. }, function (message) {
  64818. reject(new Error(message));
  64819. });
  64820. });
  64821. };
  64822. DracoCompression._LoadFileAsync = function (url) {
  64823. return new Promise(function (resolve, reject) {
  64824. BABYLON.Tools.LoadFile(url, function (data) {
  64825. resolve(data);
  64826. }, undefined, undefined, true, function (request, exception) {
  64827. reject(exception);
  64828. });
  64829. });
  64830. };
  64831. /**
  64832. * The configuration. Defaults to the following urls:
  64833. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  64834. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  64835. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  64836. */
  64837. DracoCompression.Configuration = {
  64838. decoder: {
  64839. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  64840. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  64841. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  64842. }
  64843. };
  64844. return DracoCompression;
  64845. }());
  64846. BABYLON.DracoCompression = DracoCompression;
  64847. })(BABYLON || (BABYLON = {}));
  64848. //# sourceMappingURL=babylon.dracoCompression.js.map
  64849. var BABYLON;
  64850. (function (BABYLON) {
  64851. var AudioEngine = /** @class */ (function () {
  64852. function AudioEngine() {
  64853. this._audioContext = null;
  64854. this._audioContextInitialized = false;
  64855. this.canUseWebAudio = false;
  64856. this.WarnedWebAudioUnsupported = false;
  64857. this.unlocked = false;
  64858. this.isMP3supported = false;
  64859. this.isOGGsupported = false;
  64860. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  64861. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  64862. this.canUseWebAudio = true;
  64863. }
  64864. var audioElem = document.createElement('audio');
  64865. try {
  64866. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  64867. this.isMP3supported = true;
  64868. }
  64869. }
  64870. catch (e) {
  64871. // protect error during capability check.
  64872. }
  64873. try {
  64874. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  64875. this.isOGGsupported = true;
  64876. }
  64877. }
  64878. catch (e) {
  64879. // protect error during capability check.
  64880. }
  64881. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  64882. this._unlockiOSaudio();
  64883. }
  64884. else {
  64885. this.unlocked = true;
  64886. }
  64887. }
  64888. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  64889. get: function () {
  64890. if (!this._audioContextInitialized) {
  64891. this._initializeAudioContext();
  64892. }
  64893. return this._audioContext;
  64894. },
  64895. enumerable: true,
  64896. configurable: true
  64897. });
  64898. AudioEngine.prototype._unlockiOSaudio = function () {
  64899. var _this = this;
  64900. var unlockaudio = function () {
  64901. if (!_this.audioContext) {
  64902. return;
  64903. }
  64904. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  64905. var source = _this.audioContext.createBufferSource();
  64906. source.buffer = buffer;
  64907. source.connect(_this.audioContext.destination);
  64908. source.start(0);
  64909. setTimeout(function () {
  64910. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  64911. _this.unlocked = true;
  64912. window.removeEventListener('touchend', unlockaudio, false);
  64913. if (_this.onAudioUnlocked) {
  64914. _this.onAudioUnlocked();
  64915. }
  64916. }
  64917. }, 0);
  64918. };
  64919. window.addEventListener('touchend', unlockaudio, false);
  64920. };
  64921. AudioEngine.prototype._initializeAudioContext = function () {
  64922. try {
  64923. if (this.canUseWebAudio) {
  64924. this._audioContext = new AudioContext();
  64925. // create a global volume gain node
  64926. this.masterGain = this._audioContext.createGain();
  64927. this.masterGain.gain.value = 1;
  64928. this.masterGain.connect(this._audioContext.destination);
  64929. this._audioContextInitialized = true;
  64930. }
  64931. }
  64932. catch (e) {
  64933. this.canUseWebAudio = false;
  64934. BABYLON.Tools.Error("Web Audio: " + e.message);
  64935. }
  64936. };
  64937. AudioEngine.prototype.dispose = function () {
  64938. if (this.canUseWebAudio && this._audioContextInitialized) {
  64939. if (this._connectedAnalyser && this._audioContext) {
  64940. this._connectedAnalyser.stopDebugCanvas();
  64941. this._connectedAnalyser.dispose();
  64942. this.masterGain.disconnect();
  64943. this.masterGain.connect(this._audioContext.destination);
  64944. this._connectedAnalyser = null;
  64945. }
  64946. this.masterGain.gain.value = 1;
  64947. }
  64948. this.WarnedWebAudioUnsupported = false;
  64949. };
  64950. AudioEngine.prototype.getGlobalVolume = function () {
  64951. if (this.canUseWebAudio && this._audioContextInitialized) {
  64952. return this.masterGain.gain.value;
  64953. }
  64954. else {
  64955. return -1;
  64956. }
  64957. };
  64958. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  64959. if (this.canUseWebAudio && this._audioContextInitialized) {
  64960. this.masterGain.gain.value = newVolume;
  64961. }
  64962. };
  64963. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  64964. if (this._connectedAnalyser) {
  64965. this._connectedAnalyser.stopDebugCanvas();
  64966. }
  64967. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  64968. this._connectedAnalyser = analyser;
  64969. this.masterGain.disconnect();
  64970. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  64971. }
  64972. };
  64973. return AudioEngine;
  64974. }());
  64975. BABYLON.AudioEngine = AudioEngine;
  64976. })(BABYLON || (BABYLON = {}));
  64977. //# sourceMappingURL=babylon.audioEngine.js.map
  64978. var BABYLON;
  64979. (function (BABYLON) {
  64980. var Sound = /** @class */ (function () {
  64981. /**
  64982. * Create a sound and attach it to a scene
  64983. * @param name Name of your sound
  64984. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  64985. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  64986. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  64987. */
  64988. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  64989. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  64990. var _this = this;
  64991. this.autoplay = false;
  64992. this.loop = false;
  64993. this.useCustomAttenuation = false;
  64994. this.spatialSound = false;
  64995. this.refDistance = 1;
  64996. this.rolloffFactor = 1;
  64997. this.maxDistance = 100;
  64998. this.distanceModel = "linear";
  64999. this._panningModel = "equalpower";
  65000. /**
  65001. * Observable event when the current playing sound finishes.
  65002. */
  65003. this.onEndedObservable = new BABYLON.Observable();
  65004. this._playbackRate = 1;
  65005. this._streaming = false;
  65006. this._startTime = 0;
  65007. this._startOffset = 0;
  65008. this._position = BABYLON.Vector3.Zero();
  65009. /** @hidden */
  65010. this._positionInEmitterSpace = false;
  65011. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  65012. this._volume = 1;
  65013. this._isReadyToPlay = false;
  65014. this.isPlaying = false;
  65015. this.isPaused = false;
  65016. this._isDirectional = false;
  65017. // Used if you'd like to create a directional sound.
  65018. // If not set, the sound will be omnidirectional
  65019. this._coneInnerAngle = 360;
  65020. this._coneOuterAngle = 360;
  65021. this._coneOuterGain = 0;
  65022. this._isOutputConnected = false;
  65023. this._urlType = "Unknown";
  65024. this.name = name;
  65025. this._scene = scene;
  65026. this._readyToPlayCallback = readyToPlayCallback;
  65027. // Default custom attenuation function is a linear attenuation
  65028. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  65029. if (currentDistance < maxDistance) {
  65030. return currentVolume * (1 - currentDistance / maxDistance);
  65031. }
  65032. else {
  65033. return 0;
  65034. }
  65035. };
  65036. if (options) {
  65037. this.autoplay = options.autoplay || false;
  65038. this.loop = options.loop || false;
  65039. // if volume === 0, we need another way to check this option
  65040. if (options.volume !== undefined) {
  65041. this._volume = options.volume;
  65042. }
  65043. this.spatialSound = options.spatialSound || false;
  65044. this.maxDistance = options.maxDistance || 100;
  65045. this.useCustomAttenuation = options.useCustomAttenuation || false;
  65046. this.rolloffFactor = options.rolloffFactor || 1;
  65047. this.refDistance = options.refDistance || 1;
  65048. this.distanceModel = options.distanceModel || "linear";
  65049. this._playbackRate = options.playbackRate || 1;
  65050. this._streaming = options.streaming || false;
  65051. }
  65052. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  65053. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  65054. this._soundGain.gain.value = this._volume;
  65055. this._inputAudioNode = this._soundGain;
  65056. this._outputAudioNode = this._soundGain;
  65057. if (this.spatialSound) {
  65058. this._createSpatialParameters();
  65059. }
  65060. this._scene.mainSoundTrack.AddSound(this);
  65061. var validParameter = true;
  65062. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  65063. if (urlOrArrayBuffer) {
  65064. try {
  65065. if (typeof (urlOrArrayBuffer) === "string") {
  65066. this._urlType = "String";
  65067. }
  65068. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  65069. this._urlType = "ArrayBuffer";
  65070. }
  65071. else if (urlOrArrayBuffer instanceof MediaStream) {
  65072. this._urlType = "MediaStream";
  65073. }
  65074. else if (Array.isArray(urlOrArrayBuffer)) {
  65075. this._urlType = "Array";
  65076. }
  65077. var urls = [];
  65078. var codecSupportedFound = false;
  65079. switch (this._urlType) {
  65080. case "MediaStream":
  65081. this._streaming = true;
  65082. this._isReadyToPlay = true;
  65083. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);
  65084. if (this.autoplay) {
  65085. this.play();
  65086. }
  65087. if (this._readyToPlayCallback) {
  65088. this._readyToPlayCallback();
  65089. }
  65090. break;
  65091. case "ArrayBuffer":
  65092. if (urlOrArrayBuffer.byteLength > 0) {
  65093. codecSupportedFound = true;
  65094. this._soundLoaded(urlOrArrayBuffer);
  65095. }
  65096. break;
  65097. case "String":
  65098. urls.push(urlOrArrayBuffer);
  65099. case "Array":
  65100. if (urls.length === 0)
  65101. urls = urlOrArrayBuffer;
  65102. // If we found a supported format, we load it immediately and stop the loop
  65103. for (var i = 0; i < urls.length; i++) {
  65104. var url = urls[i];
  65105. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  65106. codecSupportedFound = true;
  65107. }
  65108. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  65109. codecSupportedFound = true;
  65110. }
  65111. if (url.indexOf(".wav", url.length - 4) !== -1) {
  65112. codecSupportedFound = true;
  65113. }
  65114. if (url.indexOf("blob:") !== -1) {
  65115. codecSupportedFound = true;
  65116. }
  65117. if (codecSupportedFound) {
  65118. // Loading sound using XHR2
  65119. if (!this._streaming) {
  65120. this._scene._loadFile(url, function (data) {
  65121. _this._soundLoaded(data);
  65122. }, undefined, true, true, function (exception) {
  65123. if (exception) {
  65124. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  65125. }
  65126. BABYLON.Tools.Error("Sound creation aborted.");
  65127. _this._scene.mainSoundTrack.RemoveSound(_this);
  65128. });
  65129. }
  65130. // Streaming sound using HTML5 Audio tag
  65131. else {
  65132. this._htmlAudioElement = new Audio(url);
  65133. this._htmlAudioElement.controls = false;
  65134. this._htmlAudioElement.loop = this.loop;
  65135. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  65136. this._htmlAudioElement.preload = "auto";
  65137. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  65138. _this._isReadyToPlay = true;
  65139. if (_this.autoplay) {
  65140. _this.play();
  65141. }
  65142. if (_this._readyToPlayCallback) {
  65143. _this._readyToPlayCallback();
  65144. }
  65145. });
  65146. document.body.appendChild(this._htmlAudioElement);
  65147. }
  65148. break;
  65149. }
  65150. }
  65151. break;
  65152. default:
  65153. validParameter = false;
  65154. break;
  65155. }
  65156. if (!validParameter) {
  65157. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  65158. }
  65159. else {
  65160. if (!codecSupportedFound) {
  65161. this._isReadyToPlay = true;
  65162. // Simulating a ready to play event to avoid breaking code path
  65163. if (this._readyToPlayCallback) {
  65164. window.setTimeout(function () {
  65165. if (_this._readyToPlayCallback) {
  65166. _this._readyToPlayCallback();
  65167. }
  65168. }, 1000);
  65169. }
  65170. }
  65171. }
  65172. }
  65173. catch (ex) {
  65174. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  65175. this._scene.mainSoundTrack.RemoveSound(this);
  65176. }
  65177. }
  65178. }
  65179. else {
  65180. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  65181. this._scene.mainSoundTrack.AddSound(this);
  65182. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  65183. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  65184. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  65185. }
  65186. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  65187. if (this._readyToPlayCallback) {
  65188. window.setTimeout(function () {
  65189. if (_this._readyToPlayCallback) {
  65190. _this._readyToPlayCallback();
  65191. }
  65192. }, 1000);
  65193. }
  65194. }
  65195. }
  65196. Sound.prototype.dispose = function () {
  65197. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  65198. if (this.isPlaying) {
  65199. this.stop();
  65200. }
  65201. this._isReadyToPlay = false;
  65202. if (this.soundTrackId === -1) {
  65203. this._scene.mainSoundTrack.RemoveSound(this);
  65204. }
  65205. else {
  65206. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  65207. }
  65208. if (this._soundGain) {
  65209. this._soundGain.disconnect();
  65210. this._soundGain = null;
  65211. }
  65212. if (this._soundPanner) {
  65213. this._soundPanner.disconnect();
  65214. this._soundPanner = null;
  65215. }
  65216. if (this._soundSource) {
  65217. this._soundSource.disconnect();
  65218. this._soundSource = null;
  65219. }
  65220. this._audioBuffer = null;
  65221. if (this._htmlAudioElement) {
  65222. this._htmlAudioElement.pause();
  65223. this._htmlAudioElement.src = "";
  65224. document.body.removeChild(this._htmlAudioElement);
  65225. }
  65226. if (this._streamingSource) {
  65227. this._streamingSource.disconnect();
  65228. }
  65229. if (this._connectedMesh && this._registerFunc) {
  65230. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  65231. this._connectedMesh = null;
  65232. }
  65233. }
  65234. };
  65235. Sound.prototype.isReady = function () {
  65236. return this._isReadyToPlay;
  65237. };
  65238. Sound.prototype._soundLoaded = function (audioData) {
  65239. var _this = this;
  65240. if (!BABYLON.Engine.audioEngine.audioContext) {
  65241. return;
  65242. }
  65243. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  65244. _this._audioBuffer = buffer;
  65245. _this._isReadyToPlay = true;
  65246. if (_this.autoplay) {
  65247. _this.play();
  65248. }
  65249. if (_this._readyToPlayCallback) {
  65250. _this._readyToPlayCallback();
  65251. }
  65252. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  65253. };
  65254. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  65255. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  65256. this._audioBuffer = audioBuffer;
  65257. this._isReadyToPlay = true;
  65258. }
  65259. };
  65260. Sound.prototype.updateOptions = function (options) {
  65261. if (options) {
  65262. this.loop = options.loop || this.loop;
  65263. this.maxDistance = options.maxDistance || this.maxDistance;
  65264. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  65265. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  65266. this.refDistance = options.refDistance || this.refDistance;
  65267. this.distanceModel = options.distanceModel || this.distanceModel;
  65268. this._playbackRate = options.playbackRate || this._playbackRate;
  65269. this._updateSpatialParameters();
  65270. if (this.isPlaying) {
  65271. if (this._streaming && this._htmlAudioElement) {
  65272. this._htmlAudioElement.playbackRate = this._playbackRate;
  65273. }
  65274. else {
  65275. if (this._soundSource) {
  65276. this._soundSource.playbackRate.value = this._playbackRate;
  65277. }
  65278. }
  65279. }
  65280. }
  65281. };
  65282. Sound.prototype._createSpatialParameters = function () {
  65283. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  65284. if (this._scene.headphone) {
  65285. this._panningModel = "HRTF";
  65286. }
  65287. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  65288. this._updateSpatialParameters();
  65289. this._soundPanner.connect(this._outputAudioNode);
  65290. this._inputAudioNode = this._soundPanner;
  65291. }
  65292. };
  65293. Sound.prototype._updateSpatialParameters = function () {
  65294. if (this.spatialSound && this._soundPanner) {
  65295. if (this.useCustomAttenuation) {
  65296. // Tricks to disable in a way embedded Web Audio attenuation
  65297. this._soundPanner.distanceModel = "linear";
  65298. this._soundPanner.maxDistance = Number.MAX_VALUE;
  65299. this._soundPanner.refDistance = 1;
  65300. this._soundPanner.rolloffFactor = 1;
  65301. this._soundPanner.panningModel = this._panningModel;
  65302. }
  65303. else {
  65304. this._soundPanner.distanceModel = this.distanceModel;
  65305. this._soundPanner.maxDistance = this.maxDistance;
  65306. this._soundPanner.refDistance = this.refDistance;
  65307. this._soundPanner.rolloffFactor = this.rolloffFactor;
  65308. this._soundPanner.panningModel = this._panningModel;
  65309. }
  65310. }
  65311. };
  65312. Sound.prototype.switchPanningModelToHRTF = function () {
  65313. this._panningModel = "HRTF";
  65314. this._switchPanningModel();
  65315. };
  65316. Sound.prototype.switchPanningModelToEqualPower = function () {
  65317. this._panningModel = "equalpower";
  65318. this._switchPanningModel();
  65319. };
  65320. Sound.prototype._switchPanningModel = function () {
  65321. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  65322. this._soundPanner.panningModel = this._panningModel;
  65323. }
  65324. };
  65325. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  65326. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  65327. if (this._isOutputConnected) {
  65328. this._outputAudioNode.disconnect();
  65329. }
  65330. this._outputAudioNode.connect(soundTrackAudioNode);
  65331. this._isOutputConnected = true;
  65332. }
  65333. };
  65334. /**
  65335. * Transform this sound into a directional source
  65336. * @param coneInnerAngle Size of the inner cone in degree
  65337. * @param coneOuterAngle Size of the outer cone in degree
  65338. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  65339. */
  65340. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  65341. if (coneOuterAngle < coneInnerAngle) {
  65342. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  65343. return;
  65344. }
  65345. this._coneInnerAngle = coneInnerAngle;
  65346. this._coneOuterAngle = coneOuterAngle;
  65347. this._coneOuterGain = coneOuterGain;
  65348. this._isDirectional = true;
  65349. if (this.isPlaying && this.loop) {
  65350. this.stop();
  65351. this.play();
  65352. }
  65353. };
  65354. Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", {
  65355. /**
  65356. * Gets or sets the inner angle for the directional cone.
  65357. */
  65358. get: function () {
  65359. return this._coneInnerAngle;
  65360. },
  65361. /**
  65362. * Gets or sets the inner angle for the directional cone.
  65363. */
  65364. set: function (value) {
  65365. if (value != this._coneInnerAngle) {
  65366. if (this._coneOuterAngle < value) {
  65367. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  65368. return;
  65369. }
  65370. this._coneInnerAngle = value;
  65371. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  65372. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  65373. }
  65374. }
  65375. },
  65376. enumerable: true,
  65377. configurable: true
  65378. });
  65379. Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", {
  65380. /**
  65381. * Gets or sets the outer angle for the directional cone.
  65382. */
  65383. get: function () {
  65384. return this._coneOuterAngle;
  65385. },
  65386. /**
  65387. * Gets or sets the outer angle for the directional cone.
  65388. */
  65389. set: function (value) {
  65390. if (value != this._coneOuterAngle) {
  65391. if (value < this._coneInnerAngle) {
  65392. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  65393. return;
  65394. }
  65395. this._coneOuterAngle = value;
  65396. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  65397. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  65398. }
  65399. }
  65400. },
  65401. enumerable: true,
  65402. configurable: true
  65403. });
  65404. Sound.prototype.setPosition = function (newPosition) {
  65405. this._position = newPosition;
  65406. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  65407. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  65408. }
  65409. };
  65410. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  65411. this._localDirection = newLocalDirection;
  65412. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  65413. this._updateDirection();
  65414. }
  65415. };
  65416. Sound.prototype._updateDirection = function () {
  65417. if (!this._connectedMesh || !this._soundPanner) {
  65418. return;
  65419. }
  65420. var mat = this._connectedMesh.getWorldMatrix();
  65421. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  65422. direction.normalize();
  65423. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  65424. };
  65425. Sound.prototype.updateDistanceFromListener = function () {
  65426. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  65427. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  65428. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  65429. }
  65430. };
  65431. Sound.prototype.setAttenuationFunction = function (callback) {
  65432. this._customAttenuationFunction = callback;
  65433. };
  65434. /**
  65435. * Play the sound
  65436. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  65437. * @param offset (optional) Start the sound setting it at a specific time
  65438. */
  65439. Sound.prototype.play = function (time, offset) {
  65440. var _this = this;
  65441. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  65442. try {
  65443. if (this._startOffset < 0) {
  65444. time = -this._startOffset;
  65445. this._startOffset = 0;
  65446. }
  65447. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  65448. if (!this._soundSource || !this._streamingSource) {
  65449. if (this.spatialSound && this._soundPanner) {
  65450. if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  65451. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  65452. }
  65453. if (this._isDirectional) {
  65454. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  65455. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  65456. this._soundPanner.coneOuterGain = this._coneOuterGain;
  65457. if (this._connectedMesh) {
  65458. this._updateDirection();
  65459. }
  65460. else {
  65461. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  65462. }
  65463. }
  65464. }
  65465. }
  65466. if (this._streaming) {
  65467. if (!this._streamingSource) {
  65468. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  65469. this._htmlAudioElement.onended = function () { _this._onended(); };
  65470. this._htmlAudioElement.playbackRate = this._playbackRate;
  65471. }
  65472. this._streamingSource.disconnect();
  65473. this._streamingSource.connect(this._inputAudioNode);
  65474. if (this._htmlAudioElement) {
  65475. this._htmlAudioElement.play();
  65476. }
  65477. }
  65478. else {
  65479. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  65480. this._soundSource.buffer = this._audioBuffer;
  65481. this._soundSource.connect(this._inputAudioNode);
  65482. this._soundSource.loop = this.loop;
  65483. this._soundSource.playbackRate.value = this._playbackRate;
  65484. this._soundSource.onended = function () { _this._onended(); };
  65485. if (this._soundSource.buffer) {
  65486. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  65487. }
  65488. }
  65489. this._startTime = startTime;
  65490. this.isPlaying = true;
  65491. this.isPaused = false;
  65492. }
  65493. catch (ex) {
  65494. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  65495. }
  65496. }
  65497. };
  65498. Sound.prototype._onended = function () {
  65499. this.isPlaying = false;
  65500. if (this.onended) {
  65501. this.onended();
  65502. }
  65503. this.onEndedObservable.notifyObservers(this);
  65504. };
  65505. /**
  65506. * Stop the sound
  65507. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  65508. */
  65509. Sound.prototype.stop = function (time) {
  65510. if (this.isPlaying) {
  65511. if (this._streaming) {
  65512. if (this._htmlAudioElement) {
  65513. this._htmlAudioElement.pause();
  65514. // Test needed for Firefox or it will generate an Invalid State Error
  65515. if (this._htmlAudioElement.currentTime > 0) {
  65516. this._htmlAudioElement.currentTime = 0;
  65517. }
  65518. }
  65519. else {
  65520. this._streamingSource.disconnect();
  65521. }
  65522. }
  65523. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  65524. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  65525. this._soundSource.stop(stopTime);
  65526. this._soundSource.onended = function () { };
  65527. if (!this.isPaused) {
  65528. this._startOffset = 0;
  65529. }
  65530. }
  65531. this.isPlaying = false;
  65532. }
  65533. };
  65534. Sound.prototype.pause = function () {
  65535. if (this.isPlaying) {
  65536. this.isPaused = true;
  65537. if (this._streaming) {
  65538. if (this._htmlAudioElement) {
  65539. this._htmlAudioElement.pause();
  65540. }
  65541. else {
  65542. this._streamingSource.disconnect();
  65543. }
  65544. }
  65545. else if (BABYLON.Engine.audioEngine.audioContext) {
  65546. this.stop(0);
  65547. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  65548. }
  65549. }
  65550. };
  65551. Sound.prototype.setVolume = function (newVolume, time) {
  65552. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  65553. if (time && BABYLON.Engine.audioEngine.audioContext) {
  65554. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  65555. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  65556. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  65557. }
  65558. else {
  65559. this._soundGain.gain.value = newVolume;
  65560. }
  65561. }
  65562. this._volume = newVolume;
  65563. };
  65564. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  65565. this._playbackRate = newPlaybackRate;
  65566. if (this.isPlaying) {
  65567. if (this._streaming && this._htmlAudioElement) {
  65568. this._htmlAudioElement.playbackRate = this._playbackRate;
  65569. }
  65570. else if (this._soundSource) {
  65571. this._soundSource.playbackRate.value = this._playbackRate;
  65572. }
  65573. }
  65574. };
  65575. Sound.prototype.getVolume = function () {
  65576. return this._volume;
  65577. };
  65578. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  65579. var _this = this;
  65580. if (this._connectedMesh && this._registerFunc) {
  65581. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  65582. this._registerFunc = null;
  65583. }
  65584. this._connectedMesh = meshToConnectTo;
  65585. if (!this.spatialSound) {
  65586. this.spatialSound = true;
  65587. this._createSpatialParameters();
  65588. if (this.isPlaying && this.loop) {
  65589. this.stop();
  65590. this.play();
  65591. }
  65592. }
  65593. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  65594. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  65595. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  65596. };
  65597. Sound.prototype.detachFromMesh = function () {
  65598. if (this._connectedMesh && this._registerFunc) {
  65599. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  65600. this._registerFunc = null;
  65601. this._connectedMesh = null;
  65602. }
  65603. };
  65604. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  65605. if (!node.getBoundingInfo) {
  65606. return;
  65607. }
  65608. var mesh = node;
  65609. if (this._positionInEmitterSpace) {
  65610. mesh.worldMatrixFromCache.invertToRef(BABYLON.Tmp.Matrix[0]);
  65611. this.setPosition(BABYLON.Tmp.Matrix[0].getTranslation());
  65612. }
  65613. else {
  65614. var boundingInfo = mesh.getBoundingInfo();
  65615. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  65616. }
  65617. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  65618. this._updateDirection();
  65619. }
  65620. };
  65621. Sound.prototype.clone = function () {
  65622. var _this = this;
  65623. if (!this._streaming) {
  65624. var setBufferAndRun = function () {
  65625. if (_this._isReadyToPlay) {
  65626. clonedSound._audioBuffer = _this.getAudioBuffer();
  65627. clonedSound._isReadyToPlay = true;
  65628. if (clonedSound.autoplay) {
  65629. clonedSound.play();
  65630. }
  65631. }
  65632. else {
  65633. window.setTimeout(setBufferAndRun, 300);
  65634. }
  65635. };
  65636. var currentOptions = {
  65637. autoplay: this.autoplay, loop: this.loop,
  65638. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  65639. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  65640. refDistance: this.refDistance, distanceModel: this.distanceModel
  65641. };
  65642. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  65643. if (this.useCustomAttenuation) {
  65644. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  65645. }
  65646. clonedSound.setPosition(this._position);
  65647. clonedSound.setPlaybackRate(this._playbackRate);
  65648. setBufferAndRun();
  65649. return clonedSound;
  65650. }
  65651. // Can't clone a streaming sound
  65652. else {
  65653. return null;
  65654. }
  65655. };
  65656. Sound.prototype.getAudioBuffer = function () {
  65657. return this._audioBuffer;
  65658. };
  65659. Sound.prototype.serialize = function () {
  65660. var serializationObject = {
  65661. name: this.name,
  65662. url: this.name,
  65663. autoplay: this.autoplay,
  65664. loop: this.loop,
  65665. volume: this._volume,
  65666. spatialSound: this.spatialSound,
  65667. maxDistance: this.maxDistance,
  65668. rolloffFactor: this.rolloffFactor,
  65669. refDistance: this.refDistance,
  65670. distanceModel: this.distanceModel,
  65671. playbackRate: this._playbackRate,
  65672. panningModel: this._panningModel,
  65673. soundTrackId: this.soundTrackId
  65674. };
  65675. if (this.spatialSound) {
  65676. if (this._connectedMesh)
  65677. serializationObject.connectedMeshId = this._connectedMesh.id;
  65678. serializationObject.position = this._position.asArray();
  65679. serializationObject.refDistance = this.refDistance;
  65680. serializationObject.distanceModel = this.distanceModel;
  65681. serializationObject.isDirectional = this._isDirectional;
  65682. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  65683. serializationObject.coneInnerAngle = this._coneInnerAngle;
  65684. serializationObject.coneOuterAngle = this._coneOuterAngle;
  65685. serializationObject.coneOuterGain = this._coneOuterGain;
  65686. }
  65687. return serializationObject;
  65688. };
  65689. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  65690. var soundName = parsedSound.name;
  65691. var soundUrl;
  65692. if (parsedSound.url) {
  65693. soundUrl = rootUrl + parsedSound.url;
  65694. }
  65695. else {
  65696. soundUrl = rootUrl + soundName;
  65697. }
  65698. var options = {
  65699. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  65700. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  65701. rolloffFactor: parsedSound.rolloffFactor,
  65702. refDistance: parsedSound.refDistance,
  65703. distanceModel: parsedSound.distanceModel,
  65704. playbackRate: parsedSound.playbackRate
  65705. };
  65706. var newSound;
  65707. if (!sourceSound) {
  65708. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  65709. scene._addPendingData(newSound);
  65710. }
  65711. else {
  65712. var setBufferAndRun = function () {
  65713. if (sourceSound._isReadyToPlay) {
  65714. newSound._audioBuffer = sourceSound.getAudioBuffer();
  65715. newSound._isReadyToPlay = true;
  65716. if (newSound.autoplay) {
  65717. newSound.play();
  65718. }
  65719. }
  65720. else {
  65721. window.setTimeout(setBufferAndRun, 300);
  65722. }
  65723. };
  65724. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  65725. setBufferAndRun();
  65726. }
  65727. if (parsedSound.position) {
  65728. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  65729. newSound.setPosition(soundPosition);
  65730. }
  65731. if (parsedSound.isDirectional) {
  65732. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  65733. if (parsedSound.localDirectionToMesh) {
  65734. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  65735. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  65736. }
  65737. }
  65738. if (parsedSound.connectedMeshId) {
  65739. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  65740. if (connectedMesh) {
  65741. newSound.attachToMesh(connectedMesh);
  65742. }
  65743. }
  65744. return newSound;
  65745. };
  65746. return Sound;
  65747. }());
  65748. BABYLON.Sound = Sound;
  65749. })(BABYLON || (BABYLON = {}));
  65750. //# sourceMappingURL=babylon.sound.js.map
  65751. var BABYLON;
  65752. (function (BABYLON) {
  65753. var SoundTrack = /** @class */ (function () {
  65754. function SoundTrack(scene, options) {
  65755. this.id = -1;
  65756. this._isMainTrack = false;
  65757. this._isInitialized = false;
  65758. this._scene = scene;
  65759. this.soundCollection = new Array();
  65760. this._options = options;
  65761. if (!this._isMainTrack) {
  65762. this._scene.soundTracks.push(this);
  65763. this.id = this._scene.soundTracks.length - 1;
  65764. }
  65765. }
  65766. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  65767. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  65768. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  65769. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  65770. if (this._options) {
  65771. if (this._options.volume) {
  65772. this._outputAudioNode.gain.value = this._options.volume;
  65773. }
  65774. if (this._options.mainTrack) {
  65775. this._isMainTrack = this._options.mainTrack;
  65776. }
  65777. }
  65778. this._isInitialized = true;
  65779. }
  65780. };
  65781. SoundTrack.prototype.dispose = function () {
  65782. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  65783. if (this._connectedAnalyser) {
  65784. this._connectedAnalyser.stopDebugCanvas();
  65785. }
  65786. while (this.soundCollection.length) {
  65787. this.soundCollection[0].dispose();
  65788. }
  65789. if (this._outputAudioNode) {
  65790. this._outputAudioNode.disconnect();
  65791. }
  65792. this._outputAudioNode = null;
  65793. }
  65794. };
  65795. SoundTrack.prototype.AddSound = function (sound) {
  65796. if (!this._isInitialized) {
  65797. this._initializeSoundTrackAudioGraph();
  65798. }
  65799. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  65800. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  65801. }
  65802. if (sound.soundTrackId) {
  65803. if (sound.soundTrackId === -1) {
  65804. this._scene.mainSoundTrack.RemoveSound(sound);
  65805. }
  65806. else {
  65807. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  65808. }
  65809. }
  65810. this.soundCollection.push(sound);
  65811. sound.soundTrackId = this.id;
  65812. };
  65813. SoundTrack.prototype.RemoveSound = function (sound) {
  65814. var index = this.soundCollection.indexOf(sound);
  65815. if (index !== -1) {
  65816. this.soundCollection.splice(index, 1);
  65817. }
  65818. };
  65819. SoundTrack.prototype.setVolume = function (newVolume) {
  65820. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  65821. this._outputAudioNode.gain.value = newVolume;
  65822. }
  65823. };
  65824. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  65825. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  65826. for (var i = 0; i < this.soundCollection.length; i++) {
  65827. this.soundCollection[i].switchPanningModelToHRTF();
  65828. }
  65829. }
  65830. };
  65831. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  65832. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  65833. for (var i = 0; i < this.soundCollection.length; i++) {
  65834. this.soundCollection[i].switchPanningModelToEqualPower();
  65835. }
  65836. }
  65837. };
  65838. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  65839. if (this._connectedAnalyser) {
  65840. this._connectedAnalyser.stopDebugCanvas();
  65841. }
  65842. this._connectedAnalyser = analyser;
  65843. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  65844. this._outputAudioNode.disconnect();
  65845. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  65846. }
  65847. };
  65848. return SoundTrack;
  65849. }());
  65850. BABYLON.SoundTrack = SoundTrack;
  65851. })(BABYLON || (BABYLON = {}));
  65852. //# sourceMappingURL=babylon.soundtrack.js.map
  65853. var BABYLON;
  65854. (function (BABYLON) {
  65855. /**
  65856. * Class used to work with sound analyzer using fast fourier transform (FFT)
  65857. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  65858. */
  65859. var Analyser = /** @class */ (function () {
  65860. /**
  65861. * Creates a new analyser
  65862. * @param scene defines hosting scene
  65863. */
  65864. function Analyser(scene) {
  65865. /**
  65866. * Gets or sets the smoothing
  65867. * @ignorenaming
  65868. */
  65869. this.SMOOTHING = 0.75;
  65870. /**
  65871. * Gets or sets the FFT table size
  65872. * @ignorenaming
  65873. */
  65874. this.FFT_SIZE = 512;
  65875. /**
  65876. * Gets or sets the bar graph amplitude
  65877. * @ignorenaming
  65878. */
  65879. this.BARGRAPHAMPLITUDE = 256;
  65880. /**
  65881. * Gets or sets the position of the debug canvas
  65882. * @ignorenaming
  65883. */
  65884. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  65885. /**
  65886. * Gets or sets the debug canvas size
  65887. * @ignorenaming
  65888. */
  65889. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  65890. this._scene = scene;
  65891. this._audioEngine = BABYLON.Engine.audioEngine;
  65892. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  65893. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  65894. this._webAudioAnalyser.minDecibels = -140;
  65895. this._webAudioAnalyser.maxDecibels = 0;
  65896. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  65897. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  65898. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  65899. }
  65900. }
  65901. /**
  65902. * Get the number of data values you will have to play with for the visualization
  65903. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  65904. * @returns a number
  65905. */
  65906. Analyser.prototype.getFrequencyBinCount = function () {
  65907. if (this._audioEngine.canUseWebAudio) {
  65908. return this._webAudioAnalyser.frequencyBinCount;
  65909. }
  65910. else {
  65911. return 0;
  65912. }
  65913. };
  65914. /**
  65915. * Gets the current frequency data as a byte array
  65916. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  65917. * @returns a Uint8Array
  65918. */
  65919. Analyser.prototype.getByteFrequencyData = function () {
  65920. if (this._audioEngine.canUseWebAudio) {
  65921. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  65922. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  65923. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  65924. }
  65925. return this._byteFreqs;
  65926. };
  65927. /**
  65928. * Gets the current waveform as a byte array
  65929. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  65930. * @returns a Uint8Array
  65931. */
  65932. Analyser.prototype.getByteTimeDomainData = function () {
  65933. if (this._audioEngine.canUseWebAudio) {
  65934. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  65935. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  65936. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  65937. }
  65938. return this._byteTime;
  65939. };
  65940. /**
  65941. * Gets the current frequency data as a float array
  65942. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  65943. * @returns a Float32Array
  65944. */
  65945. Analyser.prototype.getFloatFrequencyData = function () {
  65946. if (this._audioEngine.canUseWebAudio) {
  65947. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  65948. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  65949. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  65950. }
  65951. return this._floatFreqs;
  65952. };
  65953. /**
  65954. * Renders the debug canvas
  65955. */
  65956. Analyser.prototype.drawDebugCanvas = function () {
  65957. var _this = this;
  65958. if (this._audioEngine.canUseWebAudio) {
  65959. if (!this._debugCanvas) {
  65960. this._debugCanvas = document.createElement("canvas");
  65961. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  65962. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  65963. this._debugCanvas.style.position = "absolute";
  65964. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  65965. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  65966. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  65967. document.body.appendChild(this._debugCanvas);
  65968. this._registerFunc = function () {
  65969. _this.drawDebugCanvas();
  65970. };
  65971. this._scene.registerBeforeRender(this._registerFunc);
  65972. }
  65973. if (this._registerFunc && this._debugCanvasContext) {
  65974. var workingArray = this.getByteFrequencyData();
  65975. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  65976. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  65977. // Draw the frequency domain chart.
  65978. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  65979. var value = workingArray[i];
  65980. var percent = value / this.BARGRAPHAMPLITUDE;
  65981. var height = this.DEBUGCANVASSIZE.height * percent;
  65982. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  65983. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  65984. var hue = i / this.getFrequencyBinCount() * 360;
  65985. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  65986. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  65987. }
  65988. }
  65989. }
  65990. };
  65991. /**
  65992. * Stops rendering the debug canvas and removes it
  65993. */
  65994. Analyser.prototype.stopDebugCanvas = function () {
  65995. if (this._debugCanvas) {
  65996. if (this._registerFunc) {
  65997. this._scene.unregisterBeforeRender(this._registerFunc);
  65998. this._registerFunc = null;
  65999. }
  66000. document.body.removeChild(this._debugCanvas);
  66001. this._debugCanvas = null;
  66002. this._debugCanvasContext = null;
  66003. }
  66004. };
  66005. /**
  66006. * Connects two audio nodes
  66007. * @param inputAudioNode defines first node to connect
  66008. * @param outputAudioNode defines second node to connect
  66009. */
  66010. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  66011. if (this._audioEngine.canUseWebAudio) {
  66012. inputAudioNode.connect(this._webAudioAnalyser);
  66013. this._webAudioAnalyser.connect(outputAudioNode);
  66014. }
  66015. };
  66016. /**
  66017. * Releases all associated resources
  66018. */
  66019. Analyser.prototype.dispose = function () {
  66020. if (this._audioEngine.canUseWebAudio) {
  66021. this._webAudioAnalyser.disconnect();
  66022. }
  66023. };
  66024. return Analyser;
  66025. }());
  66026. BABYLON.Analyser = Analyser;
  66027. })(BABYLON || (BABYLON = {}));
  66028. //# sourceMappingURL=babylon.analyser.js.map
  66029. var BABYLON;
  66030. (function (BABYLON) {
  66031. /**
  66032. * Wraps one or more Sound objects and selects one with random weight for playback.
  66033. */
  66034. var WeightedSound = /** @class */ (function () {
  66035. /**
  66036. * Creates a new WeightedSound from the list of sounds given.
  66037. * @param loop When true a Sound will be selected and played when the current playing Sound completes.
  66038. * @param sounds Array of Sounds that will be selected from.
  66039. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1
  66040. */
  66041. function WeightedSound(loop, sounds, weights) {
  66042. var _this = this;
  66043. /** When true a Sound will be selected and played when the current playing Sound completes. */
  66044. this.loop = false;
  66045. this._coneInnerAngle = 360;
  66046. this._coneOuterAngle = 360;
  66047. this._volume = 1;
  66048. /** A Sound is currently playing. */
  66049. this.isPlaying = false;
  66050. /** A Sound is currently paused. */
  66051. this.isPaused = false;
  66052. this._sounds = [];
  66053. this._weights = [];
  66054. if (sounds.length !== weights.length) {
  66055. throw new Error('Sounds length does not equal weights length');
  66056. }
  66057. this.loop = loop;
  66058. this._weights = weights;
  66059. // Normalize the weights
  66060. var weightSum = 0;
  66061. for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
  66062. var weight = weights_1[_i];
  66063. weightSum += weight;
  66064. }
  66065. var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
  66066. for (var i = 0; i < this._weights.length; i++) {
  66067. this._weights[i] *= invWeightSum;
  66068. }
  66069. this._sounds = sounds;
  66070. for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
  66071. var sound = _b[_a];
  66072. sound.onEndedObservable.add(function () { _this._onended(); });
  66073. }
  66074. }
  66075. Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", {
  66076. /**
  66077. * The size of cone in degrees for a directional sound in which there will be no attenuation.
  66078. */
  66079. get: function () {
  66080. return this._coneInnerAngle;
  66081. },
  66082. /**
  66083. * The size of cone in degress for a directional sound in which there will be no attenuation.
  66084. */
  66085. set: function (value) {
  66086. if (value !== this._coneInnerAngle) {
  66087. if (this._coneOuterAngle < value) {
  66088. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  66089. return;
  66090. }
  66091. this._coneInnerAngle = value;
  66092. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  66093. var sound = _a[_i];
  66094. sound.directionalConeInnerAngle = value;
  66095. }
  66096. }
  66097. },
  66098. enumerable: true,
  66099. configurable: true
  66100. });
  66101. Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", {
  66102. /**
  66103. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  66104. * Listener angles between innerAngle and outerAngle will falloff linearly.
  66105. */
  66106. get: function () {
  66107. return this._coneOuterAngle;
  66108. },
  66109. /**
  66110. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  66111. * Listener angles between innerAngle and outerAngle will falloff linearly.
  66112. */
  66113. set: function (value) {
  66114. if (value !== this._coneOuterAngle) {
  66115. if (value < this._coneInnerAngle) {
  66116. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  66117. return;
  66118. }
  66119. this._coneOuterAngle = value;
  66120. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  66121. var sound = _a[_i];
  66122. sound.directionalConeOuterAngle = value;
  66123. }
  66124. }
  66125. },
  66126. enumerable: true,
  66127. configurable: true
  66128. });
  66129. Object.defineProperty(WeightedSound.prototype, "volume", {
  66130. /**
  66131. * Playback volume.
  66132. */
  66133. get: function () {
  66134. return this._volume;
  66135. },
  66136. /**
  66137. * Playback volume.
  66138. */
  66139. set: function (value) {
  66140. if (value !== this._volume) {
  66141. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  66142. var sound = _a[_i];
  66143. sound.setVolume(value);
  66144. }
  66145. }
  66146. },
  66147. enumerable: true,
  66148. configurable: true
  66149. });
  66150. WeightedSound.prototype._onended = function () {
  66151. if (this._currentIndex !== undefined) {
  66152. this._sounds[this._currentIndex].autoplay = false;
  66153. }
  66154. if (this.loop && this.isPlaying) {
  66155. this.play();
  66156. }
  66157. else {
  66158. this.isPlaying = false;
  66159. }
  66160. };
  66161. /**
  66162. * Suspend playback
  66163. */
  66164. WeightedSound.prototype.pause = function () {
  66165. this.isPaused = true;
  66166. if (this._currentIndex !== undefined) {
  66167. this._sounds[this._currentIndex].pause();
  66168. }
  66169. };
  66170. /**
  66171. * Stop playback
  66172. */
  66173. WeightedSound.prototype.stop = function () {
  66174. this.isPlaying = false;
  66175. if (this._currentIndex !== undefined) {
  66176. this._sounds[this._currentIndex].stop();
  66177. }
  66178. };
  66179. /**
  66180. * Start playback.
  66181. * @param startOffset Position the clip head at a specific time in seconds.
  66182. */
  66183. WeightedSound.prototype.play = function (startOffset) {
  66184. if (!this.isPaused) {
  66185. this.stop();
  66186. var randomValue = Math.random();
  66187. var total = 0;
  66188. for (var i = 0; i < this._weights.length; i++) {
  66189. total += this._weights[i];
  66190. if (randomValue <= total) {
  66191. this._currentIndex = i;
  66192. break;
  66193. }
  66194. }
  66195. }
  66196. var sound = this._sounds[this._currentIndex];
  66197. if (sound.isReady()) {
  66198. sound.play(0, this.isPaused ? undefined : startOffset);
  66199. }
  66200. else {
  66201. sound.autoplay = true;
  66202. }
  66203. this.isPlaying = true;
  66204. this.isPaused = false;
  66205. };
  66206. return WeightedSound;
  66207. }());
  66208. BABYLON.WeightedSound = WeightedSound;
  66209. })(BABYLON || (BABYLON = {}));
  66210. //# sourceMappingURL=babylon.weightedsound.js.map
  66211. var BABYLON;
  66212. (function (BABYLON) {
  66213. var CubeTexture = /** @class */ (function (_super) {
  66214. __extends(CubeTexture, _super);
  66215. /**
  66216. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  66217. * as prefiltered data.
  66218. * @param rootUrl defines the url of the texture or the root name of the six images
  66219. * @param scene defines the scene the texture is attached to
  66220. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  66221. * @param noMipmap defines if mipmaps should be created or not
  66222. * @param files defines the six files to load for the different faces
  66223. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  66224. * @param onError defines a callback triggered in case of error during load
  66225. * @param format defines the internal format to use for the texture once loaded
  66226. * @param prefiltered defines whether or not the texture is created from prefiltered data
  66227. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  66228. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  66229. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  66230. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  66231. * @return the cube texture
  66232. */
  66233. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  66234. if (extensions === void 0) { extensions = null; }
  66235. if (noMipmap === void 0) { noMipmap = false; }
  66236. if (files === void 0) { files = null; }
  66237. if (onLoad === void 0) { onLoad = null; }
  66238. if (onError === void 0) { onError = null; }
  66239. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  66240. if (prefiltered === void 0) { prefiltered = false; }
  66241. if (forcedExtension === void 0) { forcedExtension = null; }
  66242. if (createPolynomials === void 0) { createPolynomials = false; }
  66243. if (lodScale === void 0) { lodScale = 0.8; }
  66244. if (lodOffset === void 0) { lodOffset = 0; }
  66245. var _this = _super.call(this, scene) || this;
  66246. /**
  66247. * Gets or sets the center of the bounding box associated with the cube texture
  66248. * It must define where the camera used to render the texture was set
  66249. */
  66250. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  66251. _this._rotationY = 0;
  66252. /** @hidden */
  66253. _this._prefiltered = false;
  66254. _this.name = rootUrl;
  66255. _this.url = rootUrl;
  66256. _this._noMipmap = noMipmap;
  66257. _this.hasAlpha = false;
  66258. _this._format = format;
  66259. _this.isCube = true;
  66260. _this._textureMatrix = BABYLON.Matrix.Identity();
  66261. _this._createPolynomials = createPolynomials;
  66262. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  66263. if (!rootUrl && !files) {
  66264. return _this;
  66265. }
  66266. var lastDot = rootUrl.lastIndexOf(".");
  66267. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  66268. var isDDS = (extension === ".dds");
  66269. var isEnv = (extension === ".env");
  66270. if (isEnv) {
  66271. _this.gammaSpace = false;
  66272. _this._prefiltered = false;
  66273. }
  66274. else {
  66275. _this._prefiltered = prefiltered;
  66276. if (prefiltered) {
  66277. _this.gammaSpace = false;
  66278. }
  66279. }
  66280. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  66281. if (!files) {
  66282. if (!isEnv && !isDDS && !extensions) {
  66283. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  66284. }
  66285. files = [];
  66286. if (extensions) {
  66287. for (var index = 0; index < extensions.length; index++) {
  66288. files.push(rootUrl + extensions[index]);
  66289. }
  66290. }
  66291. }
  66292. _this._files = files;
  66293. if (!_this._texture) {
  66294. if (!scene.useDelayedTextureLoading) {
  66295. if (prefiltered) {
  66296. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  66297. }
  66298. else {
  66299. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  66300. }
  66301. }
  66302. else {
  66303. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  66304. }
  66305. }
  66306. else if (onLoad) {
  66307. if (_this._texture.isReady) {
  66308. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  66309. }
  66310. else {
  66311. _this._texture.onLoadedObservable.add(onLoad);
  66312. }
  66313. }
  66314. return _this;
  66315. }
  66316. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  66317. get: function () {
  66318. return this._boundingBoxSize;
  66319. },
  66320. /**
  66321. * Gets or sets the size of the bounding box associated with the cube texture
  66322. * When defined, the cubemap will switch to local mode
  66323. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  66324. * @example https://www.babylonjs-playground.com/#RNASML
  66325. */
  66326. set: function (value) {
  66327. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  66328. return;
  66329. }
  66330. this._boundingBoxSize = value;
  66331. var scene = this.getScene();
  66332. if (scene) {
  66333. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  66334. }
  66335. },
  66336. enumerable: true,
  66337. configurable: true
  66338. });
  66339. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  66340. /**
  66341. * Gets texture matrix rotation angle around Y axis radians.
  66342. */
  66343. get: function () {
  66344. return this._rotationY;
  66345. },
  66346. /**
  66347. * Sets texture matrix rotation angle around Y axis in radians.
  66348. */
  66349. set: function (value) {
  66350. this._rotationY = value;
  66351. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  66352. },
  66353. enumerable: true,
  66354. configurable: true
  66355. });
  66356. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  66357. var rootUrlKey = "";
  66358. files.forEach(function (url) { return rootUrlKey += url; });
  66359. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  66360. };
  66361. /**
  66362. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  66363. * @param url defines the url of the prefiltered texture
  66364. * @param scene defines the scene the texture is attached to
  66365. * @param forcedExtension defines the extension of the file if different from the url
  66366. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  66367. * @return the prefiltered texture
  66368. */
  66369. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  66370. if (forcedExtension === void 0) { forcedExtension = null; }
  66371. if (createPolynomials === void 0) { createPolynomials = true; }
  66372. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  66373. };
  66374. // Methods
  66375. CubeTexture.prototype.delayLoad = function () {
  66376. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  66377. return;
  66378. }
  66379. var scene = this.getScene();
  66380. if (!scene) {
  66381. return;
  66382. }
  66383. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  66384. this._texture = this._getFromCache(this.url, this._noMipmap);
  66385. if (!this._texture) {
  66386. if (this._prefiltered) {
  66387. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  66388. }
  66389. else {
  66390. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  66391. }
  66392. }
  66393. };
  66394. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  66395. return this._textureMatrix;
  66396. };
  66397. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  66398. this._textureMatrix = value;
  66399. };
  66400. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  66401. var texture = BABYLON.SerializationHelper.Parse(function () {
  66402. var prefiltered = false;
  66403. if (parsedTexture.prefiltered) {
  66404. prefiltered = parsedTexture.prefiltered;
  66405. }
  66406. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  66407. }, parsedTexture, scene);
  66408. // Local Cubemaps
  66409. if (parsedTexture.boundingBoxPosition) {
  66410. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  66411. }
  66412. if (parsedTexture.boundingBoxSize) {
  66413. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  66414. }
  66415. // Animations
  66416. if (parsedTexture.animations) {
  66417. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  66418. var parsedAnimation = parsedTexture.animations[animationIndex];
  66419. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  66420. }
  66421. }
  66422. return texture;
  66423. };
  66424. CubeTexture.prototype.clone = function () {
  66425. var _this = this;
  66426. return BABYLON.SerializationHelper.Clone(function () {
  66427. var scene = _this.getScene();
  66428. if (!scene) {
  66429. return _this;
  66430. }
  66431. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  66432. }, this);
  66433. };
  66434. __decorate([
  66435. BABYLON.serialize("rotationY")
  66436. ], CubeTexture.prototype, "rotationY", null);
  66437. return CubeTexture;
  66438. }(BABYLON.BaseTexture));
  66439. BABYLON.CubeTexture = CubeTexture;
  66440. })(BABYLON || (BABYLON = {}));
  66441. //# sourceMappingURL=babylon.cubeTexture.js.map
  66442. var BABYLON;
  66443. (function (BABYLON) {
  66444. /**
  66445. * Raw cube texture where the raw buffers are passed in
  66446. */
  66447. var RawCubeTexture = /** @class */ (function (_super) {
  66448. __extends(RawCubeTexture, _super);
  66449. /**
  66450. * Creates a cube texture where the raw buffers are passed in.
  66451. * @param scene defines the scene the texture is attached to
  66452. * @param data defines the array of data to use to create each face
  66453. * @param size defines the size of the textures
  66454. * @param format defines the format of the data
  66455. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  66456. * @param generateMipMaps defines if the engine should generate the mip levels
  66457. * @param invertY defines if data must be stored with Y axis inverted
  66458. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  66459. * @param compression defines the compression used (null by default)
  66460. */
  66461. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  66462. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  66463. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66464. if (generateMipMaps === void 0) { generateMipMaps = false; }
  66465. if (invertY === void 0) { invertY = false; }
  66466. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66467. if (compression === void 0) { compression = null; }
  66468. var _this = _super.call(this, "", scene) || this;
  66469. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  66470. return _this;
  66471. }
  66472. /**
  66473. * Updates the raw cube texture.
  66474. * @param data defines the data to store
  66475. * @param format defines the data format
  66476. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  66477. * @param invertY defines if data must be stored with Y axis inverted
  66478. * @param compression defines the compression used (null by default)
  66479. * @param level defines which level of the texture to update
  66480. */
  66481. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  66482. if (compression === void 0) { compression = null; }
  66483. if (level === void 0) { level = 0; }
  66484. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  66485. };
  66486. /**
  66487. * Updates a raw cube texture with RGBD encoded data.
  66488. * @param data defines the array of data [mipmap][face] to use to create each face
  66489. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  66490. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  66491. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  66492. * @returns a promsie that resolves when the operation is complete
  66493. */
  66494. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  66495. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  66496. if (lodScale === void 0) { lodScale = 0.8; }
  66497. if (lodOffset === void 0) { lodOffset = 0; }
  66498. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  66499. };
  66500. /**
  66501. * Clones the raw cube texture.
  66502. * @return a new cube texture
  66503. */
  66504. RawCubeTexture.prototype.clone = function () {
  66505. var _this = this;
  66506. return BABYLON.SerializationHelper.Clone(function () {
  66507. var scene = _this.getScene();
  66508. var internalTexture = _this._texture;
  66509. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  66510. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  66511. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  66512. }
  66513. return texture;
  66514. }, this);
  66515. };
  66516. /** @hidden */
  66517. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  66518. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  66519. internalTexture._bufferViewArrayArray = data;
  66520. internalTexture._lodGenerationScale = lodScale;
  66521. internalTexture._lodGenerationOffset = lodOffset;
  66522. internalTexture._sphericalPolynomial = sphericalPolynomial;
  66523. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  66524. internalTexture.isReady = true;
  66525. });
  66526. };
  66527. return RawCubeTexture;
  66528. }(BABYLON.CubeTexture));
  66529. BABYLON.RawCubeTexture = RawCubeTexture;
  66530. })(BABYLON || (BABYLON = {}));
  66531. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  66532. var BABYLON;
  66533. (function (BABYLON) {
  66534. var RenderTargetTexture = /** @class */ (function (_super) {
  66535. __extends(RenderTargetTexture, _super);
  66536. /**
  66537. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  66538. * or used a shadow, depth texture...
  66539. * @param name The friendly name of the texture
  66540. * @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)
  66541. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  66542. * @param generateMipMaps True if mip maps need to be generated after render.
  66543. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  66544. * @param type The type of the buffer in the RTT (int, half float, float...)
  66545. * @param isCube True if a cube texture needs to be created
  66546. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  66547. * @param generateDepthBuffer True to generate a depth buffer
  66548. * @param generateStencilBuffer True to generate a stencil buffer
  66549. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  66550. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  66551. */
  66552. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  66553. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  66554. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66555. if (isCube === void 0) { isCube = false; }
  66556. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66557. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  66558. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  66559. if (isMulti === void 0) { isMulti = false; }
  66560. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  66561. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  66562. _this.isCube = isCube;
  66563. _this.renderParticles = true;
  66564. _this.renderSprites = false;
  66565. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  66566. _this.ignoreCameraViewport = false;
  66567. // Events
  66568. /**
  66569. * An event triggered when the texture is unbind.
  66570. */
  66571. _this.onBeforeBindObservable = new BABYLON.Observable();
  66572. /**
  66573. * An event triggered when the texture is unbind.
  66574. */
  66575. _this.onAfterUnbindObservable = new BABYLON.Observable();
  66576. /**
  66577. * An event triggered before rendering the texture
  66578. */
  66579. _this.onBeforeRenderObservable = new BABYLON.Observable();
  66580. /**
  66581. * An event triggered after rendering the texture
  66582. */
  66583. _this.onAfterRenderObservable = new BABYLON.Observable();
  66584. /**
  66585. * An event triggered after the texture clear
  66586. */
  66587. _this.onClearObservable = new BABYLON.Observable();
  66588. _this._currentRefreshId = -1;
  66589. _this._refreshRate = 1;
  66590. _this._samples = 1;
  66591. /**
  66592. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  66593. * It must define where the camera used to render the texture is set
  66594. */
  66595. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  66596. scene = _this.getScene();
  66597. if (!scene) {
  66598. return _this;
  66599. }
  66600. _this.renderList = new Array();
  66601. _this._engine = scene.getEngine();
  66602. _this.name = name;
  66603. _this.isRenderTarget = true;
  66604. _this._initialSizeParameter = size;
  66605. _this._processSizeParameter(size);
  66606. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  66607. });
  66608. _this._generateMipMaps = generateMipMaps ? true : false;
  66609. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  66610. // Rendering groups
  66611. _this._renderingManager = new BABYLON.RenderingManager(scene);
  66612. _this._renderingManager._useSceneAutoClearSetup = true;
  66613. if (isMulti) {
  66614. return _this;
  66615. }
  66616. _this._renderTargetOptions = {
  66617. generateMipMaps: generateMipMaps,
  66618. type: type,
  66619. format: format,
  66620. samplingMode: samplingMode,
  66621. generateDepthBuffer: generateDepthBuffer,
  66622. generateStencilBuffer: generateStencilBuffer
  66623. };
  66624. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  66625. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66626. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66627. }
  66628. if (isCube) {
  66629. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  66630. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  66631. _this._textureMatrix = BABYLON.Matrix.Identity();
  66632. }
  66633. else {
  66634. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  66635. }
  66636. return _this;
  66637. }
  66638. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  66639. get: function () {
  66640. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  66641. },
  66642. enumerable: true,
  66643. configurable: true
  66644. });
  66645. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  66646. get: function () {
  66647. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  66648. },
  66649. enumerable: true,
  66650. configurable: true
  66651. });
  66652. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  66653. get: function () {
  66654. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  66655. },
  66656. enumerable: true,
  66657. configurable: true
  66658. });
  66659. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  66660. /**
  66661. * Use this list to define the list of mesh you want to render.
  66662. */
  66663. get: function () {
  66664. return this._renderList;
  66665. },
  66666. set: function (value) {
  66667. this._renderList = value;
  66668. if (this._renderList) {
  66669. this._hookArray(this._renderList);
  66670. }
  66671. },
  66672. enumerable: true,
  66673. configurable: true
  66674. });
  66675. RenderTargetTexture.prototype._hookArray = function (array) {
  66676. var _this = this;
  66677. var oldPush = array.push;
  66678. array.push = function () {
  66679. var items = [];
  66680. for (var _i = 0; _i < arguments.length; _i++) {
  66681. items[_i] = arguments[_i];
  66682. }
  66683. var result = oldPush.apply(array, items);
  66684. _this.getScene().meshes.forEach(function (mesh) {
  66685. mesh._markSubMeshesAsLightDirty();
  66686. });
  66687. return result;
  66688. };
  66689. var oldSplice = array.splice;
  66690. array.splice = function (index, deleteCount) {
  66691. var deleted = oldSplice.apply(array, [index, deleteCount]);
  66692. _this.getScene().meshes.forEach(function (mesh) {
  66693. mesh._markSubMeshesAsLightDirty();
  66694. });
  66695. return deleted;
  66696. };
  66697. };
  66698. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  66699. set: function (callback) {
  66700. if (this._onAfterUnbindObserver) {
  66701. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  66702. }
  66703. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  66704. },
  66705. enumerable: true,
  66706. configurable: true
  66707. });
  66708. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  66709. set: function (callback) {
  66710. if (this._onBeforeRenderObserver) {
  66711. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  66712. }
  66713. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  66714. },
  66715. enumerable: true,
  66716. configurable: true
  66717. });
  66718. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  66719. set: function (callback) {
  66720. if (this._onAfterRenderObserver) {
  66721. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  66722. }
  66723. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  66724. },
  66725. enumerable: true,
  66726. configurable: true
  66727. });
  66728. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  66729. set: function (callback) {
  66730. if (this._onClearObserver) {
  66731. this.onClearObservable.remove(this._onClearObserver);
  66732. }
  66733. this._onClearObserver = this.onClearObservable.add(callback);
  66734. },
  66735. enumerable: true,
  66736. configurable: true
  66737. });
  66738. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  66739. get: function () {
  66740. return this._renderTargetOptions;
  66741. },
  66742. enumerable: true,
  66743. configurable: true
  66744. });
  66745. RenderTargetTexture.prototype._onRatioRescale = function () {
  66746. if (this._sizeRatio) {
  66747. this.resize(this._initialSizeParameter);
  66748. }
  66749. };
  66750. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  66751. get: function () {
  66752. return this._boundingBoxSize;
  66753. },
  66754. /**
  66755. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  66756. * When defined, the cubemap will switch to local mode
  66757. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  66758. * @example https://www.babylonjs-playground.com/#RNASML
  66759. */
  66760. set: function (value) {
  66761. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  66762. return;
  66763. }
  66764. this._boundingBoxSize = value;
  66765. var scene = this.getScene();
  66766. if (scene) {
  66767. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  66768. }
  66769. },
  66770. enumerable: true,
  66771. configurable: true
  66772. });
  66773. /**
  66774. * Creates a depth stencil texture.
  66775. * This is only available in WebGL 2 or with the depth texture extension available.
  66776. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  66777. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  66778. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  66779. */
  66780. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  66781. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  66782. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  66783. if (generateStencil === void 0) { generateStencil = false; }
  66784. if (!this.getScene()) {
  66785. return;
  66786. }
  66787. var engine = this.getScene().getEngine();
  66788. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  66789. bilinearFiltering: bilinearFiltering,
  66790. comparisonFunction: comparisonFunction,
  66791. generateStencil: generateStencil,
  66792. isCube: this.isCube
  66793. });
  66794. engine.setFrameBufferDepthStencilTexture(this);
  66795. };
  66796. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  66797. if (size.ratio) {
  66798. this._sizeRatio = size.ratio;
  66799. this._size = {
  66800. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  66801. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  66802. };
  66803. }
  66804. else {
  66805. this._size = size;
  66806. }
  66807. };
  66808. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  66809. get: function () {
  66810. return this._samples;
  66811. },
  66812. set: function (value) {
  66813. if (this._samples === value) {
  66814. return;
  66815. }
  66816. var scene = this.getScene();
  66817. if (!scene) {
  66818. return;
  66819. }
  66820. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  66821. },
  66822. enumerable: true,
  66823. configurable: true
  66824. });
  66825. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  66826. this._currentRefreshId = -1;
  66827. };
  66828. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  66829. get: function () {
  66830. return this._refreshRate;
  66831. },
  66832. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  66833. set: function (value) {
  66834. this._refreshRate = value;
  66835. this.resetRefreshCounter();
  66836. },
  66837. enumerable: true,
  66838. configurable: true
  66839. });
  66840. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  66841. if (!this._postProcessManager) {
  66842. var scene = this.getScene();
  66843. if (!scene) {
  66844. return;
  66845. }
  66846. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  66847. this._postProcesses = new Array();
  66848. }
  66849. this._postProcesses.push(postProcess);
  66850. this._postProcesses[0].autoClear = false;
  66851. };
  66852. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  66853. if (!this._postProcesses) {
  66854. return;
  66855. }
  66856. if (dispose) {
  66857. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  66858. var postProcess = _a[_i];
  66859. postProcess.dispose();
  66860. }
  66861. }
  66862. this._postProcesses = [];
  66863. };
  66864. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  66865. if (!this._postProcesses) {
  66866. return;
  66867. }
  66868. var index = this._postProcesses.indexOf(postProcess);
  66869. if (index === -1) {
  66870. return;
  66871. }
  66872. this._postProcesses.splice(index, 1);
  66873. if (this._postProcesses.length > 0) {
  66874. this._postProcesses[0].autoClear = false;
  66875. }
  66876. };
  66877. /** @hidden */
  66878. RenderTargetTexture.prototype._shouldRender = function () {
  66879. if (this._currentRefreshId === -1) { // At least render once
  66880. this._currentRefreshId = 1;
  66881. return true;
  66882. }
  66883. if (this.refreshRate === this._currentRefreshId) {
  66884. this._currentRefreshId = 1;
  66885. return true;
  66886. }
  66887. this._currentRefreshId++;
  66888. return false;
  66889. };
  66890. RenderTargetTexture.prototype.getRenderSize = function () {
  66891. if (this._size.width) {
  66892. return this._size.width;
  66893. }
  66894. return this._size;
  66895. };
  66896. RenderTargetTexture.prototype.getRenderWidth = function () {
  66897. if (this._size.width) {
  66898. return this._size.width;
  66899. }
  66900. return this._size;
  66901. };
  66902. RenderTargetTexture.prototype.getRenderHeight = function () {
  66903. if (this._size.width) {
  66904. return this._size.height;
  66905. }
  66906. return this._size;
  66907. };
  66908. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  66909. get: function () {
  66910. return true;
  66911. },
  66912. enumerable: true,
  66913. configurable: true
  66914. });
  66915. RenderTargetTexture.prototype.scale = function (ratio) {
  66916. var newSize = this.getRenderSize() * ratio;
  66917. this.resize(newSize);
  66918. };
  66919. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  66920. if (this.isCube) {
  66921. return this._textureMatrix;
  66922. }
  66923. return _super.prototype.getReflectionTextureMatrix.call(this);
  66924. };
  66925. RenderTargetTexture.prototype.resize = function (size) {
  66926. this.releaseInternalTexture();
  66927. var scene = this.getScene();
  66928. if (!scene) {
  66929. return;
  66930. }
  66931. this._processSizeParameter(size);
  66932. if (this.isCube) {
  66933. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  66934. }
  66935. else {
  66936. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  66937. }
  66938. };
  66939. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  66940. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  66941. if (dumpForDebug === void 0) { dumpForDebug = false; }
  66942. var scene = this.getScene();
  66943. if (!scene) {
  66944. return;
  66945. }
  66946. var engine = scene.getEngine();
  66947. if (this.useCameraPostProcesses !== undefined) {
  66948. useCameraPostProcess = this.useCameraPostProcesses;
  66949. }
  66950. if (this._waitingRenderList) {
  66951. this.renderList = [];
  66952. for (var index = 0; index < this._waitingRenderList.length; index++) {
  66953. var id = this._waitingRenderList[index];
  66954. var mesh_1 = scene.getMeshByID(id);
  66955. if (mesh_1) {
  66956. this.renderList.push(mesh_1);
  66957. }
  66958. }
  66959. delete this._waitingRenderList;
  66960. }
  66961. // Is predicate defined?
  66962. if (this.renderListPredicate) {
  66963. if (this.renderList) {
  66964. this.renderList.splice(0); // Clear previous renderList
  66965. }
  66966. else {
  66967. this.renderList = [];
  66968. }
  66969. var scene = this.getScene();
  66970. if (!scene) {
  66971. return;
  66972. }
  66973. var sceneMeshes = scene.meshes;
  66974. for (var index = 0; index < sceneMeshes.length; index++) {
  66975. var mesh = sceneMeshes[index];
  66976. if (this.renderListPredicate(mesh)) {
  66977. this.renderList.push(mesh);
  66978. }
  66979. }
  66980. }
  66981. this.onBeforeBindObservable.notifyObservers(this);
  66982. // Set custom projection.
  66983. // Needs to be before binding to prevent changing the aspect ratio.
  66984. var camera;
  66985. if (this.activeCamera) {
  66986. camera = this.activeCamera;
  66987. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  66988. if (this.activeCamera !== scene.activeCamera) {
  66989. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  66990. }
  66991. }
  66992. else {
  66993. camera = scene.activeCamera;
  66994. if (camera) {
  66995. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  66996. }
  66997. }
  66998. // Prepare renderingManager
  66999. this._renderingManager.reset();
  67000. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  67001. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  67002. var sceneRenderId = scene.getRenderId();
  67003. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  67004. var mesh = currentRenderList[meshIndex];
  67005. if (mesh) {
  67006. if (!mesh.isReady(this.refreshRate === 0)) {
  67007. this.resetRefreshCounter();
  67008. continue;
  67009. }
  67010. mesh._preActivateForIntermediateRendering(sceneRenderId);
  67011. var isMasked = void 0;
  67012. if (!this.renderList && camera) {
  67013. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  67014. }
  67015. else {
  67016. isMasked = false;
  67017. }
  67018. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  67019. mesh._activate(sceneRenderId);
  67020. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  67021. var subMesh = mesh.subMeshes[subIndex];
  67022. scene._activeIndices.addCount(subMesh.indexCount, false);
  67023. this._renderingManager.dispatch(subMesh, mesh);
  67024. }
  67025. }
  67026. }
  67027. }
  67028. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  67029. var particleSystem = scene.particleSystems[particleIndex];
  67030. var emitter = particleSystem.emitter;
  67031. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  67032. continue;
  67033. }
  67034. if (currentRenderList.indexOf(emitter) >= 0) {
  67035. this._renderingManager.dispatchParticles(particleSystem);
  67036. }
  67037. }
  67038. if (this.isCube) {
  67039. for (var face = 0; face < 6; face++) {
  67040. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  67041. scene.incrementRenderId();
  67042. scene.resetCachedMaterial();
  67043. }
  67044. }
  67045. else {
  67046. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  67047. }
  67048. this.onAfterUnbindObservable.notifyObservers(this);
  67049. if (scene.activeCamera) {
  67050. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  67051. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  67052. }
  67053. engine.setViewport(scene.activeCamera.viewport);
  67054. }
  67055. scene.resetCachedMaterial();
  67056. };
  67057. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  67058. var minimum = 128;
  67059. var x = renderDimension * scale;
  67060. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  67061. // Ensure we don't exceed the render dimension (while staying POT)
  67062. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  67063. };
  67064. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  67065. var _this = this;
  67066. if (!this._texture) {
  67067. return;
  67068. }
  67069. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  67070. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  67071. });
  67072. };
  67073. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  67074. var scene = this.getScene();
  67075. if (!scene) {
  67076. return;
  67077. }
  67078. var engine = scene.getEngine();
  67079. if (!this._texture) {
  67080. return;
  67081. }
  67082. // Bind
  67083. if (this._postProcessManager) {
  67084. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  67085. }
  67086. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  67087. if (this._texture) {
  67088. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  67089. }
  67090. }
  67091. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  67092. // Clear
  67093. if (this.onClearObservable.hasObservers()) {
  67094. this.onClearObservable.notifyObservers(engine);
  67095. }
  67096. else {
  67097. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  67098. }
  67099. if (!this._doNotChangeAspectRatio) {
  67100. scene.updateTransformMatrix(true);
  67101. }
  67102. // Render
  67103. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  67104. if (this._postProcessManager) {
  67105. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  67106. }
  67107. else if (useCameraPostProcess) {
  67108. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  67109. }
  67110. if (!this._doNotChangeAspectRatio) {
  67111. scene.updateTransformMatrix(true);
  67112. }
  67113. // Dump ?
  67114. if (dumpForDebug) {
  67115. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  67116. }
  67117. // Unbind
  67118. if (!this.isCube || faceIndex === 5) {
  67119. if (this.isCube) {
  67120. if (faceIndex === 5) {
  67121. engine.generateMipMapsForCubemap(this._texture);
  67122. }
  67123. }
  67124. this.unbindFrameBuffer(engine, faceIndex);
  67125. }
  67126. else {
  67127. this.onAfterRenderObservable.notifyObservers(faceIndex);
  67128. }
  67129. };
  67130. /**
  67131. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  67132. * This allowed control for front to back rendering or reversly depending of the special needs.
  67133. *
  67134. * @param renderingGroupId The rendering group id corresponding to its index
  67135. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  67136. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  67137. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  67138. */
  67139. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  67140. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  67141. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  67142. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  67143. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  67144. };
  67145. /**
  67146. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  67147. *
  67148. * @param renderingGroupId The rendering group id corresponding to its index
  67149. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  67150. */
  67151. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  67152. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  67153. this._renderingManager._useSceneAutoClearSetup = false;
  67154. };
  67155. RenderTargetTexture.prototype.clone = function () {
  67156. var textureSize = this.getSize();
  67157. 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);
  67158. // Base texture
  67159. newTexture.hasAlpha = this.hasAlpha;
  67160. newTexture.level = this.level;
  67161. // RenderTarget Texture
  67162. newTexture.coordinatesMode = this.coordinatesMode;
  67163. if (this.renderList) {
  67164. newTexture.renderList = this.renderList.slice(0);
  67165. }
  67166. return newTexture;
  67167. };
  67168. RenderTargetTexture.prototype.serialize = function () {
  67169. if (!this.name) {
  67170. return null;
  67171. }
  67172. var serializationObject = _super.prototype.serialize.call(this);
  67173. serializationObject.renderTargetSize = this.getRenderSize();
  67174. serializationObject.renderList = [];
  67175. if (this.renderList) {
  67176. for (var index = 0; index < this.renderList.length; index++) {
  67177. serializationObject.renderList.push(this.renderList[index].id);
  67178. }
  67179. }
  67180. return serializationObject;
  67181. };
  67182. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  67183. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  67184. var objBuffer = this.getInternalTexture();
  67185. var scene = this.getScene();
  67186. if (objBuffer && scene) {
  67187. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  67188. }
  67189. };
  67190. RenderTargetTexture.prototype.dispose = function () {
  67191. if (this._postProcessManager) {
  67192. this._postProcessManager.dispose();
  67193. this._postProcessManager = null;
  67194. }
  67195. this.clearPostProcesses(true);
  67196. if (this._resizeObserver) {
  67197. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  67198. this._resizeObserver = null;
  67199. }
  67200. this.renderList = null;
  67201. // Remove from custom render targets
  67202. var scene = this.getScene();
  67203. if (!scene) {
  67204. return;
  67205. }
  67206. var index = scene.customRenderTargets.indexOf(this);
  67207. if (index >= 0) {
  67208. scene.customRenderTargets.splice(index, 1);
  67209. }
  67210. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  67211. var camera = _a[_i];
  67212. index = camera.customRenderTargets.indexOf(this);
  67213. if (index >= 0) {
  67214. camera.customRenderTargets.splice(index, 1);
  67215. }
  67216. }
  67217. _super.prototype.dispose.call(this);
  67218. };
  67219. /** @hidden */
  67220. RenderTargetTexture.prototype._rebuild = function () {
  67221. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  67222. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  67223. }
  67224. if (this._postProcessManager) {
  67225. this._postProcessManager._rebuild();
  67226. }
  67227. };
  67228. /**
  67229. * Clear the info related to rendering groups preventing retention point in material dispose.
  67230. */
  67231. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  67232. if (this._renderingManager) {
  67233. this._renderingManager.freeRenderingGroups();
  67234. }
  67235. };
  67236. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  67237. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  67238. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  67239. return RenderTargetTexture;
  67240. }(BABYLON.Texture));
  67241. BABYLON.RenderTargetTexture = RenderTargetTexture;
  67242. })(BABYLON || (BABYLON = {}));
  67243. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  67244. var BABYLON;
  67245. (function (BABYLON) {
  67246. ;
  67247. var MultiRenderTarget = /** @class */ (function (_super) {
  67248. __extends(MultiRenderTarget, _super);
  67249. function MultiRenderTarget(name, size, count, scene, options) {
  67250. var _this = this;
  67251. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  67252. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  67253. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  67254. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  67255. _this._engine = scene.getEngine();
  67256. if (!_this.isSupported) {
  67257. _this.dispose();
  67258. return;
  67259. }
  67260. var types = [];
  67261. var samplingModes = [];
  67262. for (var i = 0; i < count; i++) {
  67263. if (options && options.types && options.types[i] !== undefined) {
  67264. types.push(options.types[i]);
  67265. }
  67266. else {
  67267. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  67268. }
  67269. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  67270. samplingModes.push(options.samplingModes[i]);
  67271. }
  67272. else {
  67273. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  67274. }
  67275. }
  67276. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  67277. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  67278. _this._size = size;
  67279. _this._multiRenderTargetOptions = {
  67280. samplingModes: samplingModes,
  67281. generateMipMaps: generateMipMaps,
  67282. generateDepthBuffer: generateDepthBuffer,
  67283. generateStencilBuffer: generateStencilBuffer,
  67284. generateDepthTexture: generateDepthTexture,
  67285. types: types,
  67286. textureCount: count
  67287. };
  67288. _this._createInternalTextures();
  67289. _this._createTextures();
  67290. return _this;
  67291. }
  67292. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  67293. get: function () {
  67294. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  67295. },
  67296. enumerable: true,
  67297. configurable: true
  67298. });
  67299. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  67300. get: function () {
  67301. return this._textures;
  67302. },
  67303. enumerable: true,
  67304. configurable: true
  67305. });
  67306. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  67307. get: function () {
  67308. return this._textures[this._textures.length - 1];
  67309. },
  67310. enumerable: true,
  67311. configurable: true
  67312. });
  67313. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  67314. set: function (wrap) {
  67315. if (this._textures) {
  67316. for (var i = 0; i < this._textures.length; i++) {
  67317. this._textures[i].wrapU = wrap;
  67318. }
  67319. }
  67320. },
  67321. enumerable: true,
  67322. configurable: true
  67323. });
  67324. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  67325. set: function (wrap) {
  67326. if (this._textures) {
  67327. for (var i = 0; i < this._textures.length; i++) {
  67328. this._textures[i].wrapV = wrap;
  67329. }
  67330. }
  67331. },
  67332. enumerable: true,
  67333. configurable: true
  67334. });
  67335. /** @hidden */
  67336. MultiRenderTarget.prototype._rebuild = function () {
  67337. this.releaseInternalTextures();
  67338. this._createInternalTextures();
  67339. for (var i = 0; i < this._internalTextures.length; i++) {
  67340. var texture = this._textures[i];
  67341. texture._texture = this._internalTextures[i];
  67342. }
  67343. // Keeps references to frame buffer and stencil/depth buffer
  67344. this._texture = this._internalTextures[0];
  67345. };
  67346. MultiRenderTarget.prototype._createInternalTextures = function () {
  67347. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  67348. };
  67349. MultiRenderTarget.prototype._createTextures = function () {
  67350. this._textures = [];
  67351. for (var i = 0; i < this._internalTextures.length; i++) {
  67352. var texture = new BABYLON.Texture(null, this.getScene());
  67353. texture._texture = this._internalTextures[i];
  67354. this._textures.push(texture);
  67355. }
  67356. // Keeps references to frame buffer and stencil/depth buffer
  67357. this._texture = this._internalTextures[0];
  67358. };
  67359. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  67360. get: function () {
  67361. return this._samples;
  67362. },
  67363. set: function (value) {
  67364. if (this._samples === value) {
  67365. return;
  67366. }
  67367. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  67368. },
  67369. enumerable: true,
  67370. configurable: true
  67371. });
  67372. MultiRenderTarget.prototype.resize = function (size) {
  67373. this.releaseInternalTextures();
  67374. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  67375. this._createInternalTextures();
  67376. };
  67377. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  67378. var _this = this;
  67379. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  67380. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  67381. });
  67382. };
  67383. MultiRenderTarget.prototype.dispose = function () {
  67384. this.releaseInternalTextures();
  67385. _super.prototype.dispose.call(this);
  67386. };
  67387. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  67388. if (!this._internalTextures) {
  67389. return;
  67390. }
  67391. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  67392. if (this._internalTextures[i] !== undefined) {
  67393. this._internalTextures[i].dispose();
  67394. this._internalTextures.splice(i, 1);
  67395. }
  67396. }
  67397. };
  67398. return MultiRenderTarget;
  67399. }(BABYLON.RenderTargetTexture));
  67400. BABYLON.MultiRenderTarget = MultiRenderTarget;
  67401. })(BABYLON || (BABYLON = {}));
  67402. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  67403. var BABYLON;
  67404. (function (BABYLON) {
  67405. var MirrorTexture = /** @class */ (function (_super) {
  67406. __extends(MirrorTexture, _super);
  67407. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  67408. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67409. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  67410. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  67411. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  67412. _this.scene = scene;
  67413. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  67414. _this._transformMatrix = BABYLON.Matrix.Zero();
  67415. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  67416. _this._adaptiveBlurKernel = 0;
  67417. _this._blurKernelX = 0;
  67418. _this._blurKernelY = 0;
  67419. _this._blurRatio = 1.0;
  67420. _this.ignoreCameraViewport = true;
  67421. _this._updateGammaSpace();
  67422. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  67423. _this._updateGammaSpace;
  67424. });
  67425. _this.onBeforeRenderObservable.add(function () {
  67426. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  67427. _this._savedViewMatrix = scene.getViewMatrix();
  67428. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  67429. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  67430. scene.clipPlane = _this.mirrorPlane;
  67431. scene.getEngine().cullBackFaces = false;
  67432. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  67433. });
  67434. _this.onAfterRenderObservable.add(function () {
  67435. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  67436. scene.getEngine().cullBackFaces = true;
  67437. scene._mirroredCameraPosition = null;
  67438. delete scene.clipPlane;
  67439. });
  67440. return _this;
  67441. }
  67442. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  67443. get: function () {
  67444. return this._blurRatio;
  67445. },
  67446. set: function (value) {
  67447. if (this._blurRatio === value) {
  67448. return;
  67449. }
  67450. this._blurRatio = value;
  67451. this._preparePostProcesses();
  67452. },
  67453. enumerable: true,
  67454. configurable: true
  67455. });
  67456. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  67457. set: function (value) {
  67458. this._adaptiveBlurKernel = value;
  67459. this._autoComputeBlurKernel();
  67460. },
  67461. enumerable: true,
  67462. configurable: true
  67463. });
  67464. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  67465. set: function (value) {
  67466. this.blurKernelX = value;
  67467. this.blurKernelY = value;
  67468. },
  67469. enumerable: true,
  67470. configurable: true
  67471. });
  67472. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  67473. get: function () {
  67474. return this._blurKernelX;
  67475. },
  67476. set: function (value) {
  67477. if (this._blurKernelX === value) {
  67478. return;
  67479. }
  67480. this._blurKernelX = value;
  67481. this._preparePostProcesses();
  67482. },
  67483. enumerable: true,
  67484. configurable: true
  67485. });
  67486. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  67487. get: function () {
  67488. return this._blurKernelY;
  67489. },
  67490. set: function (value) {
  67491. if (this._blurKernelY === value) {
  67492. return;
  67493. }
  67494. this._blurKernelY = value;
  67495. this._preparePostProcesses();
  67496. },
  67497. enumerable: true,
  67498. configurable: true
  67499. });
  67500. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  67501. var engine = this.getScene().getEngine();
  67502. var dw = this.getRenderWidth() / engine.getRenderWidth();
  67503. var dh = this.getRenderHeight() / engine.getRenderHeight();
  67504. this.blurKernelX = this._adaptiveBlurKernel * dw;
  67505. this.blurKernelY = this._adaptiveBlurKernel * dh;
  67506. };
  67507. MirrorTexture.prototype._onRatioRescale = function () {
  67508. if (this._sizeRatio) {
  67509. this.resize(this._initialSizeParameter);
  67510. if (!this._adaptiveBlurKernel) {
  67511. this._preparePostProcesses();
  67512. }
  67513. }
  67514. if (this._adaptiveBlurKernel) {
  67515. this._autoComputeBlurKernel();
  67516. }
  67517. };
  67518. MirrorTexture.prototype._updateGammaSpace = function () {
  67519. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  67520. };
  67521. MirrorTexture.prototype._preparePostProcesses = function () {
  67522. this.clearPostProcesses(true);
  67523. if (this._blurKernelX && this._blurKernelY) {
  67524. var engine = this.getScene().getEngine();
  67525. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67526. 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);
  67527. this._blurX.autoClear = false;
  67528. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  67529. this._blurX.inputTexture = this._texture;
  67530. }
  67531. else {
  67532. this._blurX.alwaysForcePOT = true;
  67533. }
  67534. 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);
  67535. this._blurY.autoClear = false;
  67536. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  67537. this.addPostProcess(this._blurX);
  67538. this.addPostProcess(this._blurY);
  67539. }
  67540. else {
  67541. if (this._blurY) {
  67542. this.removePostProcess(this._blurY);
  67543. this._blurY.dispose();
  67544. this._blurY = null;
  67545. }
  67546. if (this._blurX) {
  67547. this.removePostProcess(this._blurX);
  67548. this._blurX.dispose();
  67549. this._blurX = null;
  67550. }
  67551. }
  67552. };
  67553. MirrorTexture.prototype.clone = function () {
  67554. var scene = this.getScene();
  67555. if (!scene) {
  67556. return this;
  67557. }
  67558. var textureSize = this.getSize();
  67559. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  67560. // Base texture
  67561. newTexture.hasAlpha = this.hasAlpha;
  67562. newTexture.level = this.level;
  67563. // Mirror Texture
  67564. newTexture.mirrorPlane = this.mirrorPlane.clone();
  67565. if (this.renderList) {
  67566. newTexture.renderList = this.renderList.slice(0);
  67567. }
  67568. return newTexture;
  67569. };
  67570. MirrorTexture.prototype.serialize = function () {
  67571. if (!this.name) {
  67572. return null;
  67573. }
  67574. var serializationObject = _super.prototype.serialize.call(this);
  67575. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  67576. return serializationObject;
  67577. };
  67578. MirrorTexture.prototype.dispose = function () {
  67579. _super.prototype.dispose.call(this);
  67580. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  67581. };
  67582. return MirrorTexture;
  67583. }(BABYLON.RenderTargetTexture));
  67584. BABYLON.MirrorTexture = MirrorTexture;
  67585. })(BABYLON || (BABYLON = {}));
  67586. //# sourceMappingURL=babylon.mirrorTexture.js.map
  67587. var BABYLON;
  67588. (function (BABYLON) {
  67589. /**
  67590. * Creates a refraction texture used by refraction channel of the standard material.
  67591. * @param name the texture name
  67592. * @param size size of the underlying texture
  67593. * @param scene root scene
  67594. */
  67595. var RefractionTexture = /** @class */ (function (_super) {
  67596. __extends(RefractionTexture, _super);
  67597. function RefractionTexture(name, size, scene, generateMipMaps) {
  67598. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  67599. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  67600. _this.depth = 2.0;
  67601. _this.onBeforeRenderObservable.add(function () {
  67602. scene.clipPlane = _this.refractionPlane;
  67603. });
  67604. _this.onAfterRenderObservable.add(function () {
  67605. delete scene.clipPlane;
  67606. });
  67607. return _this;
  67608. }
  67609. RefractionTexture.prototype.clone = function () {
  67610. var scene = this.getScene();
  67611. if (!scene) {
  67612. return this;
  67613. }
  67614. var textureSize = this.getSize();
  67615. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  67616. // Base texture
  67617. newTexture.hasAlpha = this.hasAlpha;
  67618. newTexture.level = this.level;
  67619. // Refraction Texture
  67620. newTexture.refractionPlane = this.refractionPlane.clone();
  67621. if (this.renderList) {
  67622. newTexture.renderList = this.renderList.slice(0);
  67623. }
  67624. newTexture.depth = this.depth;
  67625. return newTexture;
  67626. };
  67627. RefractionTexture.prototype.serialize = function () {
  67628. if (!this.name) {
  67629. return null;
  67630. }
  67631. var serializationObject = _super.prototype.serialize.call(this);
  67632. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  67633. serializationObject.depth = this.depth;
  67634. return serializationObject;
  67635. };
  67636. return RefractionTexture;
  67637. }(BABYLON.RenderTargetTexture));
  67638. BABYLON.RefractionTexture = RefractionTexture;
  67639. })(BABYLON || (BABYLON = {}));
  67640. //# sourceMappingURL=babylon.refractionTexture.js.map
  67641. var BABYLON;
  67642. (function (BABYLON) {
  67643. /**
  67644. * A class extending {BABYLON.Texture} allowing drawing on a texture
  67645. * @see http://doc.babylonjs.com/how_to/dynamictexture
  67646. */
  67647. var DynamicTexture = /** @class */ (function (_super) {
  67648. __extends(DynamicTexture, _super);
  67649. /**
  67650. * Creates a {BABYLON.DynamicTexture}
  67651. * @param name defines the name of the texture
  67652. * @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
  67653. * @param scene defines the scene where you want the texture
  67654. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  67655. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  67656. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  67657. */
  67658. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  67659. if (scene === void 0) { scene = null; }
  67660. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67661. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  67662. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  67663. _this.name = name;
  67664. _this._engine = _this.getScene().getEngine();
  67665. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67666. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67667. _this._generateMipMaps = generateMipMaps;
  67668. if (options.getContext) {
  67669. _this._canvas = options;
  67670. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  67671. }
  67672. else {
  67673. _this._canvas = document.createElement("canvas");
  67674. if (options.width || options.width === 0) {
  67675. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  67676. }
  67677. else {
  67678. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  67679. }
  67680. }
  67681. var textureSize = _this.getSize();
  67682. _this._canvas.width = textureSize.width;
  67683. _this._canvas.height = textureSize.height;
  67684. _this._context = _this._canvas.getContext("2d");
  67685. return _this;
  67686. }
  67687. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  67688. /**
  67689. * Gets the current state of canRescale
  67690. */
  67691. get: function () {
  67692. return true;
  67693. },
  67694. enumerable: true,
  67695. configurable: true
  67696. });
  67697. DynamicTexture.prototype._recreate = function (textureSize) {
  67698. this._canvas.width = textureSize.width;
  67699. this._canvas.height = textureSize.height;
  67700. this.releaseInternalTexture();
  67701. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  67702. };
  67703. /**
  67704. * Scales the texture
  67705. * @param ratio the scale factor to apply to both width and height
  67706. */
  67707. DynamicTexture.prototype.scale = function (ratio) {
  67708. var textureSize = this.getSize();
  67709. textureSize.width *= ratio;
  67710. textureSize.height *= ratio;
  67711. this._recreate(textureSize);
  67712. };
  67713. /**
  67714. * Resizes the texture
  67715. * @param width the new width
  67716. * @param height the new height
  67717. */
  67718. DynamicTexture.prototype.scaleTo = function (width, height) {
  67719. var textureSize = this.getSize();
  67720. textureSize.width = width;
  67721. textureSize.height = height;
  67722. this._recreate(textureSize);
  67723. };
  67724. /**
  67725. * Gets the context of the canvas used by the texture
  67726. * @returns the canvas context of the dynamic texture
  67727. */
  67728. DynamicTexture.prototype.getContext = function () {
  67729. return this._context;
  67730. };
  67731. /**
  67732. * Clears the texture
  67733. */
  67734. DynamicTexture.prototype.clear = function () {
  67735. var size = this.getSize();
  67736. this._context.fillRect(0, 0, size.width, size.height);
  67737. };
  67738. /**
  67739. * Updates the texture
  67740. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  67741. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  67742. */
  67743. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  67744. if (premulAlpha === void 0) { premulAlpha = false; }
  67745. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  67746. };
  67747. /**
  67748. * Draws text onto the texture
  67749. * @param text defines the text to be drawn
  67750. * @param x defines the placement of the text from the left
  67751. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  67752. * @param font defines the font to be used with font-style, font-size, font-name
  67753. * @param color defines the color used for the text
  67754. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  67755. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  67756. * @param update defines whether texture is immediately update (default is true)
  67757. */
  67758. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  67759. if (update === void 0) { update = true; }
  67760. var size = this.getSize();
  67761. if (clearColor) {
  67762. this._context.fillStyle = clearColor;
  67763. this._context.fillRect(0, 0, size.width, size.height);
  67764. }
  67765. this._context.font = font;
  67766. if (x === null || x === undefined) {
  67767. var textSize = this._context.measureText(text);
  67768. x = (size.width - textSize.width) / 2;
  67769. }
  67770. if (y === null || y === undefined) {
  67771. var fontSize = parseInt((font.replace(/\D/g, '')));
  67772. y = (size.height / 2) + (fontSize / 3.65);
  67773. }
  67774. this._context.fillStyle = color;
  67775. this._context.fillText(text, x, y);
  67776. if (update) {
  67777. this.update(invertY);
  67778. }
  67779. };
  67780. /**
  67781. * Clones the texture
  67782. * @returns the clone of the texture.
  67783. */
  67784. DynamicTexture.prototype.clone = function () {
  67785. var scene = this.getScene();
  67786. if (!scene) {
  67787. return this;
  67788. }
  67789. var textureSize = this.getSize();
  67790. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  67791. // Base texture
  67792. newTexture.hasAlpha = this.hasAlpha;
  67793. newTexture.level = this.level;
  67794. // Dynamic Texture
  67795. newTexture.wrapU = this.wrapU;
  67796. newTexture.wrapV = this.wrapV;
  67797. return newTexture;
  67798. };
  67799. /**
  67800. * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized
  67801. * @returns a serialized dynamic texture object
  67802. */
  67803. DynamicTexture.prototype.serialize = function () {
  67804. var scene = this.getScene();
  67805. if (scene && !scene.isReady()) {
  67806. BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
  67807. }
  67808. var serializationObject = _super.prototype.serialize.call(this);
  67809. serializationObject.base64String = this._canvas.toDataURL();
  67810. serializationObject.invertY = this._invertY;
  67811. serializationObject.samplingMode = this.samplingMode;
  67812. return serializationObject;
  67813. };
  67814. /** @hidden */
  67815. DynamicTexture.prototype._rebuild = function () {
  67816. this.update();
  67817. };
  67818. return DynamicTexture;
  67819. }(BABYLON.Texture));
  67820. BABYLON.DynamicTexture = DynamicTexture;
  67821. })(BABYLON || (BABYLON = {}));
  67822. //# sourceMappingURL=babylon.dynamicTexture.js.map
  67823. var BABYLON;
  67824. (function (BABYLON) {
  67825. var VideoTexture = /** @class */ (function (_super) {
  67826. __extends(VideoTexture, _super);
  67827. /**
  67828. * Creates a video texture.
  67829. * Sample : https://doc.babylonjs.com/how_to/video_texture
  67830. * @param {string | null} name optional name, will detect from video source, if not defined
  67831. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  67832. * @param {BABYLON.Scene} scene is obviously the current scene.
  67833. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  67834. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  67835. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  67836. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  67837. */
  67838. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  67839. if (generateMipMaps === void 0) { generateMipMaps = false; }
  67840. if (invertY === void 0) { invertY = false; }
  67841. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67842. if (settings === void 0) { settings = {
  67843. autoPlay: true,
  67844. loop: true,
  67845. autoUpdateTexture: true,
  67846. }; }
  67847. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  67848. _this._onUserActionRequestedObservable = null;
  67849. _this._stillImageCaptured = false;
  67850. _this._poster = false;
  67851. _this._createInternalTexture = function () {
  67852. if (_this._texture != null) {
  67853. if (_this._poster) {
  67854. _this._texture.dispose();
  67855. _this._poster = false;
  67856. }
  67857. else {
  67858. return;
  67859. }
  67860. }
  67861. if (!_this._engine.needPOTTextures ||
  67862. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  67863. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67864. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67865. }
  67866. else {
  67867. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67868. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67869. _this._generateMipMaps = false;
  67870. }
  67871. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  67872. if (!_this.video.autoplay) {
  67873. var oldHandler_1 = _this.video.onplaying;
  67874. var error_1 = false;
  67875. _this.video.onplaying = function () {
  67876. _this.video.onplaying = oldHandler_1;
  67877. _this._texture.isReady = true;
  67878. _this._updateInternalTexture();
  67879. if (!error_1) {
  67880. _this.video.pause();
  67881. }
  67882. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  67883. _this.onLoadObservable.notifyObservers(_this);
  67884. }
  67885. };
  67886. var playing = _this.video.play();
  67887. if (playing) {
  67888. playing.then(function () {
  67889. // Everything is good.
  67890. })
  67891. .catch(function () {
  67892. error_1 = true;
  67893. // On Chrome for instance, new policies might prevent playing without user interaction.
  67894. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  67895. _this._onUserActionRequestedObservable.notifyObservers(_this);
  67896. }
  67897. });
  67898. }
  67899. else {
  67900. _this.video.onplaying = oldHandler_1;
  67901. _this._texture.isReady = true;
  67902. _this._updateInternalTexture();
  67903. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  67904. _this.onLoadObservable.notifyObservers(_this);
  67905. }
  67906. }
  67907. }
  67908. else {
  67909. _this._texture.isReady = true;
  67910. _this._updateInternalTexture();
  67911. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  67912. _this.onLoadObservable.notifyObservers(_this);
  67913. }
  67914. }
  67915. };
  67916. _this.reset = function () {
  67917. if (_this._texture == null) {
  67918. return;
  67919. }
  67920. if (!_this._poster) {
  67921. _this._texture.dispose();
  67922. _this._texture = null;
  67923. }
  67924. };
  67925. _this._updateInternalTexture = function (e) {
  67926. if (_this._texture == null || !_this._texture.isReady) {
  67927. return;
  67928. }
  67929. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  67930. return;
  67931. }
  67932. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  67933. };
  67934. _this._engine = _this.getScene().getEngine();
  67935. _this._generateMipMaps = generateMipMaps;
  67936. _this._samplingMode = samplingMode;
  67937. _this.autoUpdateTexture = settings.autoUpdateTexture;
  67938. _this.name = name || _this._getName(src);
  67939. _this.video = _this._getVideo(src);
  67940. if (settings.poster) {
  67941. _this.video.poster = settings.poster;
  67942. }
  67943. if (settings.autoPlay !== undefined) {
  67944. _this.video.autoplay = settings.autoPlay;
  67945. }
  67946. if (settings.loop !== undefined) {
  67947. _this.video.loop = settings.loop;
  67948. }
  67949. _this.video.setAttribute("playsinline", "");
  67950. _this.video.addEventListener("canplay", _this._createInternalTexture);
  67951. _this.video.addEventListener("paused", _this._updateInternalTexture);
  67952. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  67953. _this.video.addEventListener("emptied", _this.reset);
  67954. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  67955. _this._createInternalTexture();
  67956. }
  67957. if (settings.poster) {
  67958. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  67959. _this._poster = true;
  67960. }
  67961. return _this;
  67962. }
  67963. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  67964. get: function () {
  67965. if (!this._onUserActionRequestedObservable) {
  67966. this._onUserActionRequestedObservable = new BABYLON.Observable();
  67967. }
  67968. return this._onUserActionRequestedObservable;
  67969. },
  67970. enumerable: true,
  67971. configurable: true
  67972. });
  67973. VideoTexture.prototype._getName = function (src) {
  67974. if (src instanceof HTMLVideoElement) {
  67975. return src.currentSrc;
  67976. }
  67977. if (typeof src === "object") {
  67978. return src.toString();
  67979. }
  67980. return src;
  67981. };
  67982. ;
  67983. VideoTexture.prototype._getVideo = function (src) {
  67984. if (src instanceof HTMLVideoElement) {
  67985. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  67986. return src;
  67987. }
  67988. var video = document.createElement("video");
  67989. if (typeof src === "string") {
  67990. BABYLON.Tools.SetCorsBehavior(src, video);
  67991. video.src = src;
  67992. }
  67993. else {
  67994. BABYLON.Tools.SetCorsBehavior(src[0], video);
  67995. src.forEach(function (url) {
  67996. var source = document.createElement("source");
  67997. source.src = url;
  67998. video.appendChild(source);
  67999. });
  68000. }
  68001. return video;
  68002. };
  68003. ;
  68004. /**
  68005. * @hidden Internal method to initiate `update`.
  68006. */
  68007. VideoTexture.prototype._rebuild = function () {
  68008. this.update();
  68009. };
  68010. /**
  68011. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  68012. */
  68013. VideoTexture.prototype.update = function () {
  68014. if (!this.autoUpdateTexture) {
  68015. // Expecting user to call `updateTexture` manually
  68016. return;
  68017. }
  68018. this.updateTexture(true);
  68019. };
  68020. /**
  68021. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  68022. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  68023. */
  68024. VideoTexture.prototype.updateTexture = function (isVisible) {
  68025. if (!isVisible) {
  68026. return;
  68027. }
  68028. if (this.video.paused && this._stillImageCaptured) {
  68029. return;
  68030. }
  68031. this._stillImageCaptured = true;
  68032. this._updateInternalTexture();
  68033. };
  68034. /**
  68035. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  68036. * @param url New url.
  68037. */
  68038. VideoTexture.prototype.updateURL = function (url) {
  68039. this.video.src = url;
  68040. };
  68041. VideoTexture.prototype.dispose = function () {
  68042. _super.prototype.dispose.call(this);
  68043. if (this._onUserActionRequestedObservable) {
  68044. this._onUserActionRequestedObservable.clear();
  68045. this._onUserActionRequestedObservable = null;
  68046. }
  68047. this.video.removeEventListener("canplay", this._createInternalTexture);
  68048. this.video.removeEventListener("paused", this._updateInternalTexture);
  68049. this.video.removeEventListener("seeked", this._updateInternalTexture);
  68050. this.video.removeEventListener("emptied", this.reset);
  68051. this.video.pause();
  68052. };
  68053. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  68054. var video = document.createElement("video");
  68055. video.setAttribute('autoplay', '');
  68056. video.setAttribute('muted', '');
  68057. video.setAttribute('playsinline', '');
  68058. var constraintsDeviceId;
  68059. if (constraints && constraints.deviceId) {
  68060. constraintsDeviceId = {
  68061. exact: constraints.deviceId,
  68062. };
  68063. }
  68064. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  68065. if (navigator.mediaDevices) {
  68066. navigator.mediaDevices.getUserMedia({ video: constraints })
  68067. .then(function (stream) {
  68068. if (video.mozSrcObject !== undefined) {
  68069. // hack for Firefox < 19
  68070. video.mozSrcObject = stream;
  68071. }
  68072. else {
  68073. video.srcObject = stream;
  68074. }
  68075. var onPlaying = function () {
  68076. if (onReady) {
  68077. onReady(new VideoTexture("video", video, scene, true, true));
  68078. }
  68079. video.removeEventListener("playing", onPlaying);
  68080. };
  68081. video.addEventListener("playing", onPlaying);
  68082. video.play();
  68083. })
  68084. .catch(function (err) {
  68085. BABYLON.Tools.Error(err.name);
  68086. });
  68087. }
  68088. else {
  68089. navigator.getUserMedia =
  68090. navigator.getUserMedia ||
  68091. navigator.webkitGetUserMedia ||
  68092. navigator.mozGetUserMedia ||
  68093. navigator.msGetUserMedia;
  68094. if (navigator.getUserMedia) {
  68095. navigator.getUserMedia({
  68096. video: {
  68097. deviceId: constraintsDeviceId,
  68098. width: {
  68099. min: (constraints && constraints.minWidth) || 256,
  68100. max: (constraints && constraints.maxWidth) || 640,
  68101. },
  68102. height: {
  68103. min: (constraints && constraints.minHeight) || 256,
  68104. max: (constraints && constraints.maxHeight) || 480,
  68105. },
  68106. },
  68107. }, function (stream) {
  68108. if (video.mozSrcObject !== undefined) {
  68109. // hack for Firefox < 19
  68110. video.mozSrcObject = stream;
  68111. }
  68112. else {
  68113. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  68114. }
  68115. video.play();
  68116. if (onReady) {
  68117. onReady(new VideoTexture("video", video, scene, true, true));
  68118. }
  68119. }, function (e) {
  68120. BABYLON.Tools.Error(e.name);
  68121. });
  68122. }
  68123. }
  68124. };
  68125. return VideoTexture;
  68126. }(BABYLON.Texture));
  68127. BABYLON.VideoTexture = VideoTexture;
  68128. })(BABYLON || (BABYLON = {}));
  68129. //# sourceMappingURL=babylon.videoTexture.js.map
  68130. var BABYLON;
  68131. (function (BABYLON) {
  68132. var RawTexture = /** @class */ (function (_super) {
  68133. __extends(RawTexture, _super);
  68134. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  68135. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68136. if (invertY === void 0) { invertY = false; }
  68137. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68138. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68139. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  68140. _this.format = format;
  68141. _this._engine = scene.getEngine();
  68142. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  68143. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68144. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68145. return _this;
  68146. }
  68147. RawTexture.prototype.update = function (data) {
  68148. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  68149. };
  68150. // Statics
  68151. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  68152. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68153. if (invertY === void 0) { invertY = false; }
  68154. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68155. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  68156. };
  68157. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  68158. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68159. if (invertY === void 0) { invertY = false; }
  68160. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68161. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  68162. };
  68163. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  68164. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68165. if (invertY === void 0) { invertY = false; }
  68166. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68167. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  68168. };
  68169. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  68170. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68171. if (invertY === void 0) { invertY = false; }
  68172. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68173. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68174. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  68175. };
  68176. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  68177. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68178. if (invertY === void 0) { invertY = false; }
  68179. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68180. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68181. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  68182. };
  68183. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  68184. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68185. if (invertY === void 0) { invertY = false; }
  68186. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68187. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  68188. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  68189. };
  68190. return RawTexture;
  68191. }(BABYLON.Texture));
  68192. BABYLON.RawTexture = RawTexture;
  68193. })(BABYLON || (BABYLON = {}));
  68194. //# sourceMappingURL=babylon.rawTexture.js.map
  68195. var BABYLON;
  68196. (function (BABYLON) {
  68197. /**
  68198. * Class used to store 3D textures containing user data
  68199. */
  68200. var RawTexture3D = /** @class */ (function (_super) {
  68201. __extends(RawTexture3D, _super);
  68202. /**
  68203. * Create a new RawTexture3D
  68204. * @param data defines the data of the texture
  68205. * @param width defines the width of the texture
  68206. * @param height defines the height of the texture
  68207. * @param depth defines the depth of the texture
  68208. * @param format defines the texture format to use
  68209. * @param scene defines the hosting scene
  68210. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  68211. * @param invertY defines if texture must be stored with Y axis inverted
  68212. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  68213. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  68214. */
  68215. function RawTexture3D(data, width, height, depth,
  68216. /** Gets or sets the texture format to use */
  68217. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  68218. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68219. if (invertY === void 0) { invertY = false; }
  68220. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68221. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68222. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  68223. _this.format = format;
  68224. _this._engine = scene.getEngine();
  68225. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  68226. _this.is3D = true;
  68227. return _this;
  68228. }
  68229. /**
  68230. * Update the texture with new data
  68231. * @param data defines the data to store in the texture
  68232. */
  68233. RawTexture3D.prototype.update = function (data) {
  68234. if (!this._texture) {
  68235. return;
  68236. }
  68237. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  68238. };
  68239. return RawTexture3D;
  68240. }(BABYLON.Texture));
  68241. BABYLON.RawTexture3D = RawTexture3D;
  68242. })(BABYLON || (BABYLON = {}));
  68243. //# sourceMappingURL=babylon.rawTexture3D.js.map
  68244. var BABYLON;
  68245. (function (BABYLON) {
  68246. /**
  68247. * PostProcessManager is used to manage one or more post processes or post process pipelines
  68248. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  68249. */
  68250. var PostProcessManager = /** @class */ (function () {
  68251. /**
  68252. * Creates a new instance PostProcess
  68253. * @param scene The scene that the post process is associated with.
  68254. */
  68255. function PostProcessManager(scene) {
  68256. this._vertexBuffers = {};
  68257. this._scene = scene;
  68258. }
  68259. PostProcessManager.prototype._prepareBuffers = function () {
  68260. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  68261. return;
  68262. }
  68263. // VBO
  68264. var vertices = [];
  68265. vertices.push(1, 1);
  68266. vertices.push(-1, 1);
  68267. vertices.push(-1, -1);
  68268. vertices.push(1, -1);
  68269. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  68270. this._buildIndexBuffer();
  68271. };
  68272. PostProcessManager.prototype._buildIndexBuffer = function () {
  68273. // Indices
  68274. var indices = [];
  68275. indices.push(0);
  68276. indices.push(1);
  68277. indices.push(2);
  68278. indices.push(0);
  68279. indices.push(2);
  68280. indices.push(3);
  68281. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  68282. };
  68283. /**
  68284. * Rebuilds the vertex buffers of the manager.
  68285. * @hidden
  68286. */
  68287. PostProcessManager.prototype._rebuild = function () {
  68288. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68289. if (!vb) {
  68290. return;
  68291. }
  68292. vb._rebuild();
  68293. this._buildIndexBuffer();
  68294. };
  68295. // Methods
  68296. /**
  68297. * Prepares a frame to be run through a post process.
  68298. * @param sourceTexture The input texture to the post procesess. (default: null)
  68299. * @param postProcesses An array of post processes to be run. (default: null)
  68300. * @returns True if the post processes were able to be run.
  68301. * @hidden
  68302. */
  68303. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  68304. if (sourceTexture === void 0) { sourceTexture = null; }
  68305. if (postProcesses === void 0) { postProcesses = null; }
  68306. var camera = this._scene.activeCamera;
  68307. if (!camera) {
  68308. return false;
  68309. }
  68310. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  68311. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  68312. return false;
  68313. }
  68314. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  68315. return true;
  68316. };
  68317. /**
  68318. * Manually render a set of post processes to a texture.
  68319. * @param postProcesses An array of post processes to be run.
  68320. * @param targetTexture The target texture to render to.
  68321. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  68322. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  68323. * @param lodLevel defines which lod of the texture to render to
  68324. */
  68325. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  68326. if (targetTexture === void 0) { targetTexture = null; }
  68327. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  68328. if (faceIndex === void 0) { faceIndex = 0; }
  68329. if (lodLevel === void 0) { lodLevel = 0; }
  68330. var engine = this._scene.getEngine();
  68331. for (var index = 0; index < postProcesses.length; index++) {
  68332. if (index < postProcesses.length - 1) {
  68333. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  68334. }
  68335. else {
  68336. if (targetTexture) {
  68337. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  68338. }
  68339. else {
  68340. engine.restoreDefaultFramebuffer();
  68341. }
  68342. }
  68343. var pp = postProcesses[index];
  68344. var effect = pp.apply();
  68345. if (effect) {
  68346. pp.onBeforeRenderObservable.notifyObservers(effect);
  68347. // VBOs
  68348. this._prepareBuffers();
  68349. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  68350. // Draw order
  68351. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  68352. pp.onAfterRenderObservable.notifyObservers(effect);
  68353. }
  68354. }
  68355. // Restore depth buffer
  68356. engine.setDepthBuffer(true);
  68357. engine.setDepthWrite(true);
  68358. };
  68359. /**
  68360. * Finalize the result of the output of the postprocesses.
  68361. * @param doNotPresent If true the result will not be displayed to the screen.
  68362. * @param targetTexture The target texture to render to.
  68363. * @param faceIndex The index of the face to bind the target texture to.
  68364. * @param postProcesses The array of post processes to render.
  68365. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  68366. * @hidden
  68367. */
  68368. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  68369. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  68370. var camera = this._scene.activeCamera;
  68371. if (!camera) {
  68372. return;
  68373. }
  68374. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  68375. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  68376. return;
  68377. }
  68378. var engine = this._scene.getEngine();
  68379. for (var index = 0, len = postProcesses.length; index < len; index++) {
  68380. var pp = postProcesses[index];
  68381. if (index < len - 1) {
  68382. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  68383. }
  68384. else {
  68385. if (targetTexture) {
  68386. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  68387. pp._outputTexture = targetTexture;
  68388. }
  68389. else {
  68390. engine.restoreDefaultFramebuffer();
  68391. pp._outputTexture = null;
  68392. }
  68393. }
  68394. if (doNotPresent) {
  68395. break;
  68396. }
  68397. var effect = pp.apply();
  68398. if (effect) {
  68399. pp.onBeforeRenderObservable.notifyObservers(effect);
  68400. // VBOs
  68401. this._prepareBuffers();
  68402. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  68403. // Draw order
  68404. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  68405. pp.onAfterRenderObservable.notifyObservers(effect);
  68406. }
  68407. }
  68408. // Restore states
  68409. engine.setDepthBuffer(true);
  68410. engine.setDepthWrite(true);
  68411. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  68412. };
  68413. /**
  68414. * Disposes of the post process manager.
  68415. */
  68416. PostProcessManager.prototype.dispose = function () {
  68417. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68418. if (buffer) {
  68419. buffer.dispose();
  68420. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  68421. }
  68422. if (this._indexBuffer) {
  68423. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  68424. this._indexBuffer = null;
  68425. }
  68426. };
  68427. return PostProcessManager;
  68428. }());
  68429. BABYLON.PostProcessManager = PostProcessManager;
  68430. })(BABYLON || (BABYLON = {}));
  68431. //# sourceMappingURL=babylon.postProcessManager.js.map
  68432. var BABYLON;
  68433. (function (BABYLON) {
  68434. /**
  68435. * PostProcess can be used to apply a shader to a texture after it has been rendered
  68436. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  68437. */
  68438. var PostProcess = /** @class */ (function () {
  68439. /**
  68440. * Creates a new instance PostProcess
  68441. * @param name The name of the PostProcess.
  68442. * @param fragmentUrl The url of the fragment shader to be used.
  68443. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  68444. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  68445. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  68446. * @param camera The camera to apply the render pass to.
  68447. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68448. * @param engine The engine which the post process will be applied. (default: current engine)
  68449. * @param reusable If the post process can be reused on the same frame. (default: false)
  68450. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  68451. * @param textureType Type of textures used when performing the post process. (default: 0)
  68452. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  68453. * @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
  68454. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  68455. */
  68456. function PostProcess(
  68457. /** Name of the PostProcess. */
  68458. name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  68459. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  68460. if (defines === void 0) { defines = null; }
  68461. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68462. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  68463. if (blockCompilation === void 0) { blockCompilation = false; }
  68464. this.name = name;
  68465. /**
  68466. * Width of the texture to apply the post process on
  68467. */
  68468. this.width = -1;
  68469. /**
  68470. * Height of the texture to apply the post process on
  68471. */
  68472. this.height = -1;
  68473. /**
  68474. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  68475. * @hidden
  68476. */
  68477. this._outputTexture = null;
  68478. /**
  68479. * If the buffer needs to be cleared before applying the post process. (default: true)
  68480. * Should be set to false if shader will overwrite all previous pixels.
  68481. */
  68482. this.autoClear = true;
  68483. /**
  68484. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  68485. */
  68486. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  68487. /**
  68488. * Animations to be used for the post processing
  68489. */
  68490. this.animations = new Array();
  68491. /**
  68492. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  68493. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  68494. */
  68495. this.enablePixelPerfectMode = false;
  68496. /**
  68497. * Force the postprocess to be applied without taking in account viewport
  68498. */
  68499. this.forceFullscreenViewport = true;
  68500. /**
  68501. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  68502. *
  68503. * | Value | Type | Description |
  68504. * | ----- | ----------------------------------- | ----------- |
  68505. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  68506. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  68507. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  68508. *
  68509. */
  68510. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  68511. /**
  68512. * Force textures to be a power of two (default: false)
  68513. */
  68514. this.alwaysForcePOT = false;
  68515. this._samples = 1;
  68516. /**
  68517. * Modify the scale of the post process to be the same as the viewport (default: false)
  68518. */
  68519. this.adaptScaleToCurrentViewport = false;
  68520. this._reusable = false;
  68521. /**
  68522. * Smart array of input and output textures for the post process.
  68523. * @hidden
  68524. */
  68525. this._textures = new BABYLON.SmartArray(2);
  68526. /**
  68527. * The index in _textures that corresponds to the output texture.
  68528. * @hidden
  68529. */
  68530. this._currentRenderTextureInd = 0;
  68531. this._scaleRatio = new BABYLON.Vector2(1, 1);
  68532. this._texelSize = BABYLON.Vector2.Zero();
  68533. // Events
  68534. /**
  68535. * An event triggered when the postprocess is activated.
  68536. */
  68537. this.onActivateObservable = new BABYLON.Observable();
  68538. /**
  68539. * An event triggered when the postprocess changes its size.
  68540. */
  68541. this.onSizeChangedObservable = new BABYLON.Observable();
  68542. /**
  68543. * An event triggered when the postprocess applies its effect.
  68544. */
  68545. this.onApplyObservable = new BABYLON.Observable();
  68546. /**
  68547. * An event triggered before rendering the postprocess
  68548. */
  68549. this.onBeforeRenderObservable = new BABYLON.Observable();
  68550. /**
  68551. * An event triggered after rendering the postprocess
  68552. */
  68553. this.onAfterRenderObservable = new BABYLON.Observable();
  68554. if (camera != null) {
  68555. this._camera = camera;
  68556. this._scene = camera.getScene();
  68557. camera.attachPostProcess(this);
  68558. this._engine = this._scene.getEngine();
  68559. this._scene.postProcesses.push(this);
  68560. }
  68561. else if (engine) {
  68562. this._engine = engine;
  68563. this._engine.postProcesses.push(this);
  68564. }
  68565. this._options = options;
  68566. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  68567. this._reusable = reusable || false;
  68568. this._textureType = textureType;
  68569. this._samplers = samplers || [];
  68570. this._samplers.push("textureSampler");
  68571. this._fragmentUrl = fragmentUrl;
  68572. this._vertexUrl = vertexUrl;
  68573. this._parameters = parameters || [];
  68574. this._parameters.push("scale");
  68575. this._indexParameters = indexParameters;
  68576. if (!blockCompilation) {
  68577. this.updateEffect(defines);
  68578. }
  68579. }
  68580. Object.defineProperty(PostProcess.prototype, "samples", {
  68581. /**
  68582. * Number of sample textures (default: 1)
  68583. */
  68584. get: function () {
  68585. return this._samples;
  68586. },
  68587. set: function (n) {
  68588. var _this = this;
  68589. this._samples = n;
  68590. this._textures.forEach(function (texture) {
  68591. if (texture.samples !== _this._samples) {
  68592. _this._engine.updateRenderTargetTextureSampleCount(texture, _this._samples);
  68593. }
  68594. });
  68595. },
  68596. enumerable: true,
  68597. configurable: true
  68598. });
  68599. Object.defineProperty(PostProcess.prototype, "onActivate", {
  68600. /**
  68601. * A function that is added to the onActivateObservable
  68602. */
  68603. set: function (callback) {
  68604. if (this._onActivateObserver) {
  68605. this.onActivateObservable.remove(this._onActivateObserver);
  68606. }
  68607. if (callback) {
  68608. this._onActivateObserver = this.onActivateObservable.add(callback);
  68609. }
  68610. },
  68611. enumerable: true,
  68612. configurable: true
  68613. });
  68614. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  68615. /**
  68616. * A function that is added to the onSizeChangedObservable
  68617. */
  68618. set: function (callback) {
  68619. if (this._onSizeChangedObserver) {
  68620. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  68621. }
  68622. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  68623. },
  68624. enumerable: true,
  68625. configurable: true
  68626. });
  68627. Object.defineProperty(PostProcess.prototype, "onApply", {
  68628. /**
  68629. * A function that is added to the onApplyObservable
  68630. */
  68631. set: function (callback) {
  68632. if (this._onApplyObserver) {
  68633. this.onApplyObservable.remove(this._onApplyObserver);
  68634. }
  68635. this._onApplyObserver = this.onApplyObservable.add(callback);
  68636. },
  68637. enumerable: true,
  68638. configurable: true
  68639. });
  68640. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  68641. /**
  68642. * A function that is added to the onBeforeRenderObservable
  68643. */
  68644. set: function (callback) {
  68645. if (this._onBeforeRenderObserver) {
  68646. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  68647. }
  68648. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  68649. },
  68650. enumerable: true,
  68651. configurable: true
  68652. });
  68653. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  68654. /**
  68655. * A function that is added to the onAfterRenderObservable
  68656. */
  68657. set: function (callback) {
  68658. if (this._onAfterRenderObserver) {
  68659. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  68660. }
  68661. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  68662. },
  68663. enumerable: true,
  68664. configurable: true
  68665. });
  68666. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  68667. /**
  68668. * 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
  68669. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  68670. */
  68671. get: function () {
  68672. return this._textures.data[this._currentRenderTextureInd];
  68673. },
  68674. set: function (value) {
  68675. this._forcedOutputTexture = value;
  68676. },
  68677. enumerable: true,
  68678. configurable: true
  68679. });
  68680. /**
  68681. * Gets the camera which post process is applied to.
  68682. * @returns The camera the post process is applied to.
  68683. */
  68684. PostProcess.prototype.getCamera = function () {
  68685. return this._camera;
  68686. };
  68687. Object.defineProperty(PostProcess.prototype, "texelSize", {
  68688. /**
  68689. * Gets the texel size of the postprocess.
  68690. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  68691. */
  68692. get: function () {
  68693. if (this._shareOutputWithPostProcess) {
  68694. return this._shareOutputWithPostProcess.texelSize;
  68695. }
  68696. if (this._forcedOutputTexture) {
  68697. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  68698. }
  68699. return this._texelSize;
  68700. },
  68701. enumerable: true,
  68702. configurable: true
  68703. });
  68704. /**
  68705. * Gets the engine which this post process belongs to.
  68706. * @returns The engine the post process was enabled with.
  68707. */
  68708. PostProcess.prototype.getEngine = function () {
  68709. return this._engine;
  68710. };
  68711. /**
  68712. * The effect that is created when initializing the post process.
  68713. * @returns The created effect corrisponding the the postprocess.
  68714. */
  68715. PostProcess.prototype.getEffect = function () {
  68716. return this._effect;
  68717. };
  68718. /**
  68719. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  68720. * @param postProcess The post process to share the output with.
  68721. * @returns This post process.
  68722. */
  68723. PostProcess.prototype.shareOutputWith = function (postProcess) {
  68724. this._disposeTextures();
  68725. this._shareOutputWithPostProcess = postProcess;
  68726. return this;
  68727. };
  68728. /**
  68729. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  68730. * This should be called if the post process that shares output with this post process is disabled/disposed.
  68731. */
  68732. PostProcess.prototype.useOwnOutput = function () {
  68733. if (this._textures.length == 0) {
  68734. this._textures = new BABYLON.SmartArray(2);
  68735. }
  68736. this._shareOutputWithPostProcess = null;
  68737. };
  68738. /**
  68739. * Updates the effect with the current post process compile time values and recompiles the shader.
  68740. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  68741. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  68742. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  68743. * @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
  68744. * @param onCompiled Called when the shader has been compiled.
  68745. * @param onError Called if there is an error when compiling a shader.
  68746. */
  68747. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  68748. if (defines === void 0) { defines = null; }
  68749. if (uniforms === void 0) { uniforms = null; }
  68750. if (samplers === void 0) { samplers = null; }
  68751. 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);
  68752. };
  68753. /**
  68754. * The post process is reusable if it can be used multiple times within one frame.
  68755. * @returns If the post process is reusable
  68756. */
  68757. PostProcess.prototype.isReusable = function () {
  68758. return this._reusable;
  68759. };
  68760. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  68761. PostProcess.prototype.markTextureDirty = function () {
  68762. this.width = -1;
  68763. };
  68764. /**
  68765. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  68766. * 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.
  68767. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  68768. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  68769. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  68770. * @returns The target texture that was bound to be written to.
  68771. */
  68772. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  68773. var _this = this;
  68774. if (sourceTexture === void 0) { sourceTexture = null; }
  68775. camera = camera || this._camera;
  68776. var scene = camera.getScene();
  68777. var engine = scene.getEngine();
  68778. var maxSize = engine.getCaps().maxTextureSize;
  68779. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  68780. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  68781. // 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
  68782. var webVRCamera = camera.parent;
  68783. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  68784. requiredWidth /= 2;
  68785. }
  68786. var desiredWidth = (this._options.width || requiredWidth);
  68787. var desiredHeight = this._options.height || requiredHeight;
  68788. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  68789. if (this.adaptScaleToCurrentViewport) {
  68790. var currentViewport = engine.currentViewport;
  68791. if (currentViewport) {
  68792. desiredWidth *= currentViewport.width;
  68793. desiredHeight *= currentViewport.height;
  68794. }
  68795. }
  68796. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  68797. if (!this._options.width) {
  68798. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  68799. }
  68800. if (!this._options.height) {
  68801. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  68802. }
  68803. }
  68804. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  68805. if (this._textures.length > 0) {
  68806. for (var i = 0; i < this._textures.length; i++) {
  68807. this._engine._releaseTexture(this._textures.data[i]);
  68808. }
  68809. this._textures.reset();
  68810. }
  68811. this.width = desiredWidth;
  68812. this.height = desiredHeight;
  68813. var textureSize = { width: this.width, height: this.height };
  68814. var textureOptions = {
  68815. generateMipMaps: false,
  68816. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  68817. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  68818. samplingMode: this.renderTargetSamplingMode,
  68819. type: this._textureType
  68820. };
  68821. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  68822. if (this._reusable) {
  68823. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  68824. }
  68825. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  68826. this.onSizeChangedObservable.notifyObservers(this);
  68827. }
  68828. this._textures.forEach(function (texture) {
  68829. if (texture.samples !== _this.samples) {
  68830. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  68831. }
  68832. });
  68833. }
  68834. var target;
  68835. if (this._shareOutputWithPostProcess) {
  68836. target = this._shareOutputWithPostProcess.inputTexture;
  68837. }
  68838. else if (this._forcedOutputTexture) {
  68839. target = this._forcedOutputTexture;
  68840. this.width = this._forcedOutputTexture.width;
  68841. this.height = this._forcedOutputTexture.height;
  68842. }
  68843. else {
  68844. target = this.inputTexture;
  68845. }
  68846. // Bind the input of this post process to be used as the output of the previous post process.
  68847. if (this.enablePixelPerfectMode) {
  68848. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  68849. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  68850. }
  68851. else {
  68852. this._scaleRatio.copyFromFloats(1, 1);
  68853. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  68854. }
  68855. this.onActivateObservable.notifyObservers(camera);
  68856. // Clear
  68857. if (scene._allowPostProcessClear && this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  68858. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  68859. }
  68860. if (this._reusable) {
  68861. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  68862. }
  68863. return target;
  68864. };
  68865. Object.defineProperty(PostProcess.prototype, "isSupported", {
  68866. /**
  68867. * If the post process is supported.
  68868. */
  68869. get: function () {
  68870. return this._effect.isSupported;
  68871. },
  68872. enumerable: true,
  68873. configurable: true
  68874. });
  68875. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  68876. /**
  68877. * The aspect ratio of the output texture.
  68878. */
  68879. get: function () {
  68880. if (this._shareOutputWithPostProcess) {
  68881. return this._shareOutputWithPostProcess.aspectRatio;
  68882. }
  68883. if (this._forcedOutputTexture) {
  68884. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  68885. }
  68886. return this.width / this.height;
  68887. },
  68888. enumerable: true,
  68889. configurable: true
  68890. });
  68891. /**
  68892. * Get a value indicating if the post-process is ready to be used
  68893. * @returns true if the post-process is ready (shader is compiled)
  68894. */
  68895. PostProcess.prototype.isReady = function () {
  68896. return this._effect && this._effect.isReady();
  68897. };
  68898. /**
  68899. * Binds all textures and uniforms to the shader, this will be run on every pass.
  68900. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  68901. */
  68902. PostProcess.prototype.apply = function () {
  68903. // Check
  68904. if (!this._effect || !this._effect.isReady())
  68905. return null;
  68906. // States
  68907. this._engine.enableEffect(this._effect);
  68908. this._engine.setState(false);
  68909. this._engine.setDepthBuffer(false);
  68910. this._engine.setDepthWrite(false);
  68911. // Alpha
  68912. this._engine.setAlphaMode(this.alphaMode);
  68913. if (this.alphaConstants) {
  68914. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  68915. }
  68916. // Bind the output texture of the preivous post process as the input to this post process.
  68917. var source;
  68918. if (this._shareOutputWithPostProcess) {
  68919. source = this._shareOutputWithPostProcess.inputTexture;
  68920. }
  68921. else if (this._forcedOutputTexture) {
  68922. source = this._forcedOutputTexture;
  68923. }
  68924. else {
  68925. source = this.inputTexture;
  68926. }
  68927. this._effect._bindTexture("textureSampler", source);
  68928. // Parameters
  68929. this._effect.setVector2("scale", this._scaleRatio);
  68930. this.onApplyObservable.notifyObservers(this._effect);
  68931. return this._effect;
  68932. };
  68933. PostProcess.prototype._disposeTextures = function () {
  68934. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  68935. return;
  68936. }
  68937. if (this._textures.length > 0) {
  68938. for (var i = 0; i < this._textures.length; i++) {
  68939. this._engine._releaseTexture(this._textures.data[i]);
  68940. }
  68941. }
  68942. this._textures.dispose();
  68943. };
  68944. /**
  68945. * Disposes the post process.
  68946. * @param camera The camera to dispose the post process on.
  68947. */
  68948. PostProcess.prototype.dispose = function (camera) {
  68949. camera = camera || this._camera;
  68950. this._disposeTextures();
  68951. if (this._scene) {
  68952. var index_1 = this._scene.postProcesses.indexOf(this);
  68953. if (index_1 !== -1) {
  68954. this._scene.postProcesses.splice(index_1, 1);
  68955. }
  68956. }
  68957. else {
  68958. var index_2 = this._engine.postProcesses.indexOf(this);
  68959. if (index_2 !== -1) {
  68960. this._engine.postProcesses.splice(index_2, 1);
  68961. }
  68962. }
  68963. if (!camera) {
  68964. return;
  68965. }
  68966. camera.detachPostProcess(this);
  68967. var index = camera._postProcesses.indexOf(this);
  68968. if (index === 0 && camera._postProcesses.length > 0) {
  68969. var firstPostProcess = this._camera._getFirstPostProcess();
  68970. if (firstPostProcess) {
  68971. firstPostProcess.markTextureDirty();
  68972. }
  68973. }
  68974. this.onActivateObservable.clear();
  68975. this.onAfterRenderObservable.clear();
  68976. this.onApplyObservable.clear();
  68977. this.onBeforeRenderObservable.clear();
  68978. this.onSizeChangedObservable.clear();
  68979. };
  68980. return PostProcess;
  68981. }());
  68982. BABYLON.PostProcess = PostProcess;
  68983. })(BABYLON || (BABYLON = {}));
  68984. //# sourceMappingURL=babylon.postProcess.js.map
  68985. var BABYLON;
  68986. (function (BABYLON) {
  68987. var PassPostProcess = /** @class */ (function (_super) {
  68988. __extends(PassPostProcess, _super);
  68989. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  68990. if (camera === void 0) { camera = null; }
  68991. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68992. if (blockCompilation === void 0) { blockCompilation = false; }
  68993. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  68994. }
  68995. return PassPostProcess;
  68996. }(BABYLON.PostProcess));
  68997. BABYLON.PassPostProcess = PassPostProcess;
  68998. })(BABYLON || (BABYLON = {}));
  68999. //# sourceMappingURL=babylon.passPostProcess.js.map
  69000. var __assign = (this && this.__assign) || function () {
  69001. __assign = Object.assign || function(t) {
  69002. for (var s, i = 1, n = arguments.length; i < n; i++) {
  69003. s = arguments[i];
  69004. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  69005. t[p] = s[p];
  69006. }
  69007. return t;
  69008. };
  69009. return __assign.apply(this, arguments);
  69010. };
  69011. var BABYLON;
  69012. (function (BABYLON) {
  69013. /**
  69014. * Default implementation IShadowGenerator.
  69015. * This is the main object responsible of generating shadows in the framework.
  69016. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  69017. */
  69018. var ShadowGenerator = /** @class */ (function () {
  69019. /**
  69020. * Creates a ShadowGenerator object.
  69021. * A ShadowGenerator is the required tool to use the shadows.
  69022. * Each light casting shadows needs to use its own ShadowGenerator.
  69023. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  69024. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  69025. * @param light The light object generating the shadows.
  69026. * @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.
  69027. */
  69028. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  69029. this._bias = 0.00005;
  69030. this._normalBias = 0;
  69031. this._blurBoxOffset = 1;
  69032. this._blurScale = 2;
  69033. this._blurKernel = 1;
  69034. this._useKernelBlur = false;
  69035. this._filter = ShadowGenerator.FILTER_NONE;
  69036. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  69037. this._contactHardeningLightSizeUVRatio = 0.1;
  69038. this._darkness = 0;
  69039. this._transparencyShadow = false;
  69040. /**
  69041. * Controls the extent to which the shadows fade out at the edge of the frustum
  69042. * Used only by directionals and spots
  69043. */
  69044. this.frustumEdgeFalloff = 0;
  69045. /**
  69046. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  69047. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  69048. * It might on the other hand introduce peter panning.
  69049. */
  69050. this.forceBackFacesOnly = false;
  69051. this._lightDirection = BABYLON.Vector3.Zero();
  69052. this._viewMatrix = BABYLON.Matrix.Zero();
  69053. this._projectionMatrix = BABYLON.Matrix.Zero();
  69054. this._transformMatrix = BABYLON.Matrix.Zero();
  69055. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  69056. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  69057. this._currentFaceIndex = 0;
  69058. this._currentFaceIndexCache = 0;
  69059. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  69060. this._mapSize = mapSize;
  69061. this._light = light;
  69062. this._scene = light.getScene();
  69063. light._shadowGenerator = this;
  69064. // Texture type fallback from float to int if not supported.
  69065. var caps = this._scene.getEngine().getCaps();
  69066. if (!useFullFloatFirst) {
  69067. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  69068. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  69069. }
  69070. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  69071. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  69072. }
  69073. else {
  69074. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  69075. }
  69076. }
  69077. else {
  69078. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  69079. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  69080. }
  69081. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  69082. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  69083. }
  69084. else {
  69085. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  69086. }
  69087. }
  69088. this._initializeGenerator();
  69089. this._applyFilterValues();
  69090. }
  69091. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  69092. /**
  69093. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  69094. */
  69095. get: function () {
  69096. return this._bias;
  69097. },
  69098. /**
  69099. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  69100. */
  69101. set: function (bias) {
  69102. this._bias = bias;
  69103. },
  69104. enumerable: true,
  69105. configurable: true
  69106. });
  69107. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  69108. /**
  69109. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  69110. */
  69111. get: function () {
  69112. return this._normalBias;
  69113. },
  69114. /**
  69115. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  69116. */
  69117. set: function (normalBias) {
  69118. this._normalBias = normalBias;
  69119. },
  69120. enumerable: true,
  69121. configurable: true
  69122. });
  69123. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  69124. /**
  69125. * Gets the blur box offset: offset applied during the blur pass.
  69126. * Only usefull if useKernelBlur = false
  69127. */
  69128. get: function () {
  69129. return this._blurBoxOffset;
  69130. },
  69131. /**
  69132. * Sets the blur box offset: offset applied during the blur pass.
  69133. * Only usefull if useKernelBlur = false
  69134. */
  69135. set: function (value) {
  69136. if (this._blurBoxOffset === value) {
  69137. return;
  69138. }
  69139. this._blurBoxOffset = value;
  69140. this._disposeBlurPostProcesses();
  69141. },
  69142. enumerable: true,
  69143. configurable: true
  69144. });
  69145. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  69146. /**
  69147. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  69148. * 2 means half of the size.
  69149. */
  69150. get: function () {
  69151. return this._blurScale;
  69152. },
  69153. /**
  69154. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  69155. * 2 means half of the size.
  69156. */
  69157. set: function (value) {
  69158. if (this._blurScale === value) {
  69159. return;
  69160. }
  69161. this._blurScale = value;
  69162. this._disposeBlurPostProcesses();
  69163. },
  69164. enumerable: true,
  69165. configurable: true
  69166. });
  69167. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  69168. /**
  69169. * Gets the blur kernel: kernel size of the blur pass.
  69170. * Only usefull if useKernelBlur = true
  69171. */
  69172. get: function () {
  69173. return this._blurKernel;
  69174. },
  69175. /**
  69176. * Sets the blur kernel: kernel size of the blur pass.
  69177. * Only usefull if useKernelBlur = true
  69178. */
  69179. set: function (value) {
  69180. if (this._blurKernel === value) {
  69181. return;
  69182. }
  69183. this._blurKernel = value;
  69184. this._disposeBlurPostProcesses();
  69185. },
  69186. enumerable: true,
  69187. configurable: true
  69188. });
  69189. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  69190. /**
  69191. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  69192. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  69193. */
  69194. get: function () {
  69195. return this._useKernelBlur;
  69196. },
  69197. /**
  69198. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  69199. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  69200. */
  69201. set: function (value) {
  69202. if (this._useKernelBlur === value) {
  69203. return;
  69204. }
  69205. this._useKernelBlur = value;
  69206. this._disposeBlurPostProcesses();
  69207. },
  69208. enumerable: true,
  69209. configurable: true
  69210. });
  69211. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  69212. /**
  69213. * Gets the depth scale used in ESM mode.
  69214. */
  69215. get: function () {
  69216. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  69217. },
  69218. /**
  69219. * Sets the depth scale used in ESM mode.
  69220. * This can override the scale stored on the light.
  69221. */
  69222. set: function (value) {
  69223. this._depthScale = value;
  69224. },
  69225. enumerable: true,
  69226. configurable: true
  69227. });
  69228. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  69229. /**
  69230. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  69231. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  69232. */
  69233. get: function () {
  69234. return this._filter;
  69235. },
  69236. /**
  69237. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  69238. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  69239. */
  69240. set: function (value) {
  69241. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  69242. if (this._light.needCube()) {
  69243. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  69244. this.useExponentialShadowMap = true;
  69245. return;
  69246. }
  69247. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  69248. this.useCloseExponentialShadowMap = true;
  69249. return;
  69250. }
  69251. // PCF on cubemap would also be expensive
  69252. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  69253. this.usePoissonSampling = true;
  69254. return;
  69255. }
  69256. }
  69257. // Weblg1 fallback for PCF.
  69258. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  69259. if (this._scene.getEngine().webGLVersion === 1) {
  69260. this.usePoissonSampling = true;
  69261. return;
  69262. }
  69263. }
  69264. if (this._filter === value) {
  69265. return;
  69266. }
  69267. this._filter = value;
  69268. this._disposeBlurPostProcesses();
  69269. this._applyFilterValues();
  69270. this._light._markMeshesAsLightDirty();
  69271. },
  69272. enumerable: true,
  69273. configurable: true
  69274. });
  69275. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  69276. /**
  69277. * Gets if the current filter is set to Poisson Sampling.
  69278. */
  69279. get: function () {
  69280. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  69281. },
  69282. /**
  69283. * Sets the current filter to Poisson Sampling.
  69284. */
  69285. set: function (value) {
  69286. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  69287. return;
  69288. }
  69289. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  69290. },
  69291. enumerable: true,
  69292. configurable: true
  69293. });
  69294. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  69295. /**
  69296. * Gets if the current filter is set to VSM.
  69297. * DEPRECATED. Should use useExponentialShadowMap instead.
  69298. */
  69299. get: function () {
  69300. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  69301. return this.useExponentialShadowMap;
  69302. },
  69303. /**
  69304. * Sets the current filter is to VSM.
  69305. * DEPRECATED. Should use useExponentialShadowMap instead.
  69306. */
  69307. set: function (value) {
  69308. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  69309. this.useExponentialShadowMap = value;
  69310. },
  69311. enumerable: true,
  69312. configurable: true
  69313. });
  69314. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  69315. /**
  69316. * Gets if the current filter is set to blurred VSM.
  69317. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  69318. */
  69319. get: function () {
  69320. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  69321. return this.useBlurExponentialShadowMap;
  69322. },
  69323. /**
  69324. * Sets the current filter is to blurred VSM.
  69325. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  69326. */
  69327. set: function (value) {
  69328. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  69329. this.useBlurExponentialShadowMap = value;
  69330. },
  69331. enumerable: true,
  69332. configurable: true
  69333. });
  69334. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  69335. /**
  69336. * Gets if the current filter is set to ESM.
  69337. */
  69338. get: function () {
  69339. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  69340. },
  69341. /**
  69342. * Sets the current filter is to ESM.
  69343. */
  69344. set: function (value) {
  69345. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  69346. return;
  69347. }
  69348. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  69349. },
  69350. enumerable: true,
  69351. configurable: true
  69352. });
  69353. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  69354. /**
  69355. * Gets if the current filter is set to filtered ESM.
  69356. */
  69357. get: function () {
  69358. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  69359. },
  69360. /**
  69361. * Gets if the current filter is set to filtered ESM.
  69362. */
  69363. set: function (value) {
  69364. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  69365. return;
  69366. }
  69367. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  69368. },
  69369. enumerable: true,
  69370. configurable: true
  69371. });
  69372. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  69373. /**
  69374. * Gets if the current filter is set to "close ESM" (using the inverse of the
  69375. * exponential to prevent steep falloff artifacts).
  69376. */
  69377. get: function () {
  69378. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  69379. },
  69380. /**
  69381. * Sets the current filter to "close ESM" (using the inverse of the
  69382. * exponential to prevent steep falloff artifacts).
  69383. */
  69384. set: function (value) {
  69385. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  69386. return;
  69387. }
  69388. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  69389. },
  69390. enumerable: true,
  69391. configurable: true
  69392. });
  69393. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  69394. /**
  69395. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  69396. * exponential to prevent steep falloff artifacts).
  69397. */
  69398. get: function () {
  69399. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  69400. },
  69401. /**
  69402. * Sets the current filter to filtered "close ESM" (using the inverse of the
  69403. * exponential to prevent steep falloff artifacts).
  69404. */
  69405. set: function (value) {
  69406. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  69407. return;
  69408. }
  69409. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  69410. },
  69411. enumerable: true,
  69412. configurable: true
  69413. });
  69414. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  69415. /**
  69416. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  69417. */
  69418. get: function () {
  69419. return this.filter === ShadowGenerator.FILTER_PCF;
  69420. },
  69421. /**
  69422. * Sets the current filter to "PCF" (percentage closer filtering).
  69423. */
  69424. set: function (value) {
  69425. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  69426. return;
  69427. }
  69428. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  69429. },
  69430. enumerable: true,
  69431. configurable: true
  69432. });
  69433. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  69434. /**
  69435. * Gets the PCF or PCSS Quality.
  69436. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  69437. */
  69438. get: function () {
  69439. return this._filteringQuality;
  69440. },
  69441. /**
  69442. * Sets the PCF or PCSS Quality.
  69443. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  69444. */
  69445. set: function (filteringQuality) {
  69446. this._filteringQuality = filteringQuality;
  69447. },
  69448. enumerable: true,
  69449. configurable: true
  69450. });
  69451. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  69452. /**
  69453. * Gets if the current filter is set to "PCSS" (contact hardening).
  69454. */
  69455. get: function () {
  69456. return this.filter === ShadowGenerator.FILTER_PCSS;
  69457. },
  69458. /**
  69459. * Sets the current filter to "PCSS" (contact hardening).
  69460. */
  69461. set: function (value) {
  69462. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  69463. return;
  69464. }
  69465. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  69466. },
  69467. enumerable: true,
  69468. configurable: true
  69469. });
  69470. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  69471. /**
  69472. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  69473. * Using a ratio helps keeping shape stability independently of the map size.
  69474. *
  69475. * It does not account for the light projection as it was having too much
  69476. * instability during the light setup or during light position changes.
  69477. *
  69478. * Only valid if useContactHardeningShadow is true.
  69479. */
  69480. get: function () {
  69481. return this._contactHardeningLightSizeUVRatio;
  69482. },
  69483. /**
  69484. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  69485. * Using a ratio helps keeping shape stability independently of the map size.
  69486. *
  69487. * It does not account for the light projection as it was having too much
  69488. * instability during the light setup or during light position changes.
  69489. *
  69490. * Only valid if useContactHardeningShadow is true.
  69491. */
  69492. set: function (contactHardeningLightSizeUVRatio) {
  69493. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  69494. },
  69495. enumerable: true,
  69496. configurable: true
  69497. });
  69498. /**
  69499. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  69500. * 0 means strongest and 1 would means no shadow.
  69501. * @returns the darkness.
  69502. */
  69503. ShadowGenerator.prototype.getDarkness = function () {
  69504. return this._darkness;
  69505. };
  69506. /**
  69507. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  69508. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  69509. * @returns the shadow generator allowing fluent coding.
  69510. */
  69511. ShadowGenerator.prototype.setDarkness = function (darkness) {
  69512. if (darkness >= 1.0)
  69513. this._darkness = 1.0;
  69514. else if (darkness <= 0.0)
  69515. this._darkness = 0.0;
  69516. else
  69517. this._darkness = darkness;
  69518. return this;
  69519. };
  69520. /**
  69521. * Sets the ability to have transparent shadow (boolean).
  69522. * @param transparent True if transparent else False
  69523. * @returns the shadow generator allowing fluent coding
  69524. */
  69525. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  69526. this._transparencyShadow = transparent;
  69527. return this;
  69528. };
  69529. /**
  69530. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  69531. * @returns The render target texture if present otherwise, null
  69532. */
  69533. ShadowGenerator.prototype.getShadowMap = function () {
  69534. return this._shadowMap;
  69535. };
  69536. /**
  69537. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  69538. * @returns The render target texture if the shadow map is present otherwise, null
  69539. */
  69540. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  69541. if (this._shadowMap2) {
  69542. return this._shadowMap2;
  69543. }
  69544. return this._shadowMap;
  69545. };
  69546. /**
  69547. * Helper function to add a mesh and its descendants to the list of shadow casters.
  69548. * @param mesh Mesh to add
  69549. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  69550. * @returns the Shadow Generator itself
  69551. */
  69552. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  69553. if (includeDescendants === void 0) { includeDescendants = true; }
  69554. var _a;
  69555. if (!this._shadowMap) {
  69556. return this;
  69557. }
  69558. if (!this._shadowMap.renderList) {
  69559. this._shadowMap.renderList = [];
  69560. }
  69561. this._shadowMap.renderList.push(mesh);
  69562. if (includeDescendants) {
  69563. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  69564. }
  69565. return this;
  69566. };
  69567. /**
  69568. * Helper function to remove a mesh and its descendants from the list of shadow casters
  69569. * @param mesh Mesh to remove
  69570. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  69571. * @returns the Shadow Generator itself
  69572. */
  69573. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  69574. if (includeDescendants === void 0) { includeDescendants = true; }
  69575. if (!this._shadowMap || !this._shadowMap.renderList) {
  69576. return this;
  69577. }
  69578. var index = this._shadowMap.renderList.indexOf(mesh);
  69579. if (index !== -1) {
  69580. this._shadowMap.renderList.splice(index, 1);
  69581. }
  69582. if (includeDescendants) {
  69583. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  69584. var child = _a[_i];
  69585. this.removeShadowCaster(child);
  69586. }
  69587. }
  69588. return this;
  69589. };
  69590. /**
  69591. * Returns the associated light object.
  69592. * @returns the light generating the shadow
  69593. */
  69594. ShadowGenerator.prototype.getLight = function () {
  69595. return this._light;
  69596. };
  69597. ShadowGenerator.prototype._initializeGenerator = function () {
  69598. this._light._markMeshesAsLightDirty();
  69599. this._initializeShadowMap();
  69600. };
  69601. ShadowGenerator.prototype._initializeShadowMap = function () {
  69602. var _this = this;
  69603. // Render target
  69604. var engine = this._scene.getEngine();
  69605. if (engine.webGLVersion > 1) {
  69606. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  69607. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  69608. }
  69609. else {
  69610. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  69611. }
  69612. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69613. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69614. this._shadowMap.anisotropicFilteringLevel = 1;
  69615. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  69616. this._shadowMap.renderParticles = false;
  69617. this._shadowMap.ignoreCameraViewport = true;
  69618. // Record Face Index before render.
  69619. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  69620. _this._currentFaceIndex = faceIndex;
  69621. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  69622. engine.setColorWrite(false);
  69623. }
  69624. });
  69625. // Custom render function.
  69626. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  69627. // Blur if required afer render.
  69628. this._shadowMap.onAfterUnbindObservable.add(function () {
  69629. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  69630. engine.setColorWrite(true);
  69631. }
  69632. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  69633. return;
  69634. }
  69635. var shadowMap = _this.getShadowMapForRendering();
  69636. if (shadowMap) {
  69637. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  69638. }
  69639. });
  69640. // Clear according to the chosen filter.
  69641. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  69642. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  69643. this._shadowMap.onClearObservable.add(function (engine) {
  69644. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  69645. engine.clear(clearOne, false, true, false);
  69646. }
  69647. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  69648. engine.clear(clearZero, true, true, false);
  69649. }
  69650. else {
  69651. engine.clear(clearOne, true, true, false);
  69652. }
  69653. });
  69654. };
  69655. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  69656. var _this = this;
  69657. var engine = this._scene.getEngine();
  69658. var targetSize = this._mapSize / this.blurScale;
  69659. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  69660. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  69661. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69662. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69663. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  69664. }
  69665. if (this.useKernelBlur) {
  69666. 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);
  69667. this._kernelBlurXPostprocess.width = targetSize;
  69668. this._kernelBlurXPostprocess.height = targetSize;
  69669. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  69670. effect.setTexture("textureSampler", _this._shadowMap);
  69671. });
  69672. 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);
  69673. this._kernelBlurXPostprocess.autoClear = false;
  69674. this._kernelBlurYPostprocess.autoClear = false;
  69675. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  69676. this._kernelBlurXPostprocess.packedFloat = true;
  69677. this._kernelBlurYPostprocess.packedFloat = true;
  69678. }
  69679. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  69680. }
  69681. else {
  69682. 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);
  69683. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  69684. effect.setFloat2("screenSize", targetSize, targetSize);
  69685. effect.setTexture("textureSampler", _this._shadowMap);
  69686. });
  69687. this._boxBlurPostprocess.autoClear = false;
  69688. this._blurPostProcesses = [this._boxBlurPostprocess];
  69689. }
  69690. };
  69691. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  69692. var index;
  69693. var engine = this._scene.getEngine();
  69694. if (depthOnlySubMeshes.length) {
  69695. engine.setColorWrite(false);
  69696. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  69697. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  69698. }
  69699. engine.setColorWrite(true);
  69700. }
  69701. for (index = 0; index < opaqueSubMeshes.length; index++) {
  69702. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  69703. }
  69704. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  69705. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  69706. }
  69707. if (this._transparencyShadow) {
  69708. for (index = 0; index < transparentSubMeshes.length; index++) {
  69709. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  69710. }
  69711. }
  69712. };
  69713. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  69714. var _this = this;
  69715. var mesh = subMesh.getRenderingMesh();
  69716. var scene = this._scene;
  69717. var engine = scene.getEngine();
  69718. var material = subMesh.getMaterial();
  69719. if (!material) {
  69720. return;
  69721. }
  69722. // Culling
  69723. engine.setState(material.backFaceCulling);
  69724. // Managing instances
  69725. var batch = mesh._getInstancesRenderList(subMesh._id);
  69726. if (batch.mustReturn) {
  69727. return;
  69728. }
  69729. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  69730. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  69731. engine.enableEffect(this._effect);
  69732. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  69733. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  69734. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  69735. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  69736. this._effect.setVector3("lightData", this._cachedDirection);
  69737. }
  69738. else {
  69739. this._effect.setVector3("lightData", this._cachedPosition);
  69740. }
  69741. if (scene.activeCamera) {
  69742. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  69743. }
  69744. // Alpha test
  69745. if (material && material.needAlphaTesting()) {
  69746. var alphaTexture = material.getAlphaTestTexture();
  69747. if (alphaTexture) {
  69748. this._effect.setTexture("diffuseSampler", alphaTexture);
  69749. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  69750. }
  69751. }
  69752. // Bones
  69753. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  69754. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  69755. }
  69756. // Morph targets
  69757. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  69758. if (this.forceBackFacesOnly) {
  69759. engine.setState(true, 0, false, true);
  69760. }
  69761. // Draw
  69762. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  69763. if (this.forceBackFacesOnly) {
  69764. engine.setState(true, 0, false, false);
  69765. }
  69766. }
  69767. else {
  69768. // Need to reset refresh rate of the shadowMap
  69769. if (this._shadowMap) {
  69770. this._shadowMap.resetRefreshCounter();
  69771. }
  69772. }
  69773. };
  69774. ShadowGenerator.prototype._applyFilterValues = function () {
  69775. if (!this._shadowMap) {
  69776. return;
  69777. }
  69778. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  69779. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  69780. }
  69781. else {
  69782. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  69783. }
  69784. };
  69785. /**
  69786. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  69787. * @param onCompiled Callback triggered at the and of the effects compilation
  69788. * @param options Sets of optional options forcing the compilation with different modes
  69789. */
  69790. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  69791. var _this = this;
  69792. var localOptions = __assign({ useInstances: false }, options);
  69793. var shadowMap = this.getShadowMap();
  69794. if (!shadowMap) {
  69795. if (onCompiled) {
  69796. onCompiled(this);
  69797. }
  69798. return;
  69799. }
  69800. var renderList = shadowMap.renderList;
  69801. if (!renderList) {
  69802. if (onCompiled) {
  69803. onCompiled(this);
  69804. }
  69805. return;
  69806. }
  69807. var subMeshes = new Array();
  69808. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  69809. var mesh = renderList_1[_i];
  69810. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  69811. }
  69812. if (subMeshes.length === 0) {
  69813. if (onCompiled) {
  69814. onCompiled(this);
  69815. }
  69816. return;
  69817. }
  69818. var currentIndex = 0;
  69819. var checkReady = function () {
  69820. if (!_this._scene || !_this._scene.getEngine()) {
  69821. return;
  69822. }
  69823. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  69824. currentIndex++;
  69825. if (currentIndex >= subMeshes.length) {
  69826. if (onCompiled) {
  69827. onCompiled(_this);
  69828. }
  69829. return;
  69830. }
  69831. }
  69832. setTimeout(checkReady, 16);
  69833. };
  69834. checkReady();
  69835. };
  69836. /**
  69837. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  69838. * @param options Sets of optional options forcing the compilation with different modes
  69839. * @returns A promise that resolves when the compilation completes
  69840. */
  69841. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  69842. var _this = this;
  69843. return new Promise(function (resolve) {
  69844. _this.forceCompilation(function () {
  69845. resolve();
  69846. }, options);
  69847. });
  69848. };
  69849. /**
  69850. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  69851. * @param subMesh The submesh we want to render in the shadow map
  69852. * @param useInstances Defines wether will draw in the map using instances
  69853. * @returns true if ready otherwise, false
  69854. */
  69855. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  69856. var defines = [];
  69857. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  69858. defines.push("#define FLOAT");
  69859. }
  69860. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  69861. defines.push("#define ESM");
  69862. }
  69863. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  69864. defines.push("#define DEPTHTEXTURE");
  69865. }
  69866. var attribs = [BABYLON.VertexBuffer.PositionKind];
  69867. var mesh = subMesh.getMesh();
  69868. var material = subMesh.getMaterial();
  69869. // Normal bias.
  69870. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  69871. attribs.push(BABYLON.VertexBuffer.NormalKind);
  69872. defines.push("#define NORMAL");
  69873. if (mesh.nonUniformScaling) {
  69874. defines.push("#define NONUNIFORMSCALING");
  69875. }
  69876. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  69877. defines.push("#define DIRECTIONINLIGHTDATA");
  69878. }
  69879. }
  69880. // Alpha test
  69881. if (material && material.needAlphaTesting()) {
  69882. var alphaTexture = material.getAlphaTestTexture();
  69883. if (alphaTexture) {
  69884. defines.push("#define ALPHATEST");
  69885. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  69886. attribs.push(BABYLON.VertexBuffer.UVKind);
  69887. defines.push("#define UV1");
  69888. }
  69889. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  69890. if (alphaTexture.coordinatesIndex === 1) {
  69891. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  69892. defines.push("#define UV2");
  69893. }
  69894. }
  69895. }
  69896. }
  69897. // Bones
  69898. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  69899. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  69900. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  69901. if (mesh.numBoneInfluencers > 4) {
  69902. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  69903. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  69904. }
  69905. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  69906. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  69907. }
  69908. else {
  69909. defines.push("#define NUM_BONE_INFLUENCERS 0");
  69910. }
  69911. // Morph targets
  69912. var manager = mesh.morphTargetManager;
  69913. var morphInfluencers = 0;
  69914. if (manager) {
  69915. if (manager.numInfluencers > 0) {
  69916. defines.push("#define MORPHTARGETS");
  69917. morphInfluencers = manager.numInfluencers;
  69918. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  69919. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  69920. }
  69921. }
  69922. // Instances
  69923. if (useInstances) {
  69924. defines.push("#define INSTANCES");
  69925. attribs.push("world0");
  69926. attribs.push("world1");
  69927. attribs.push("world2");
  69928. attribs.push("world3");
  69929. }
  69930. // Get correct effect
  69931. var join = defines.join("\n");
  69932. if (this._cachedDefines !== join) {
  69933. this._cachedDefines = join;
  69934. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  69935. }
  69936. if (!this._effect.isReady()) {
  69937. return false;
  69938. }
  69939. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  69940. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  69941. this._initializeBlurRTTAndPostProcesses();
  69942. }
  69943. }
  69944. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  69945. return false;
  69946. }
  69947. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  69948. return false;
  69949. }
  69950. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  69951. return false;
  69952. }
  69953. return true;
  69954. };
  69955. /**
  69956. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  69957. * @param defines Defines of the material we want to update
  69958. * @param lightIndex Index of the light in the enabled light list of the material
  69959. */
  69960. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  69961. var scene = this._scene;
  69962. var light = this._light;
  69963. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  69964. return;
  69965. }
  69966. defines["SHADOW" + lightIndex] = true;
  69967. if (this.useContactHardeningShadow) {
  69968. defines["SHADOWPCSS" + lightIndex] = true;
  69969. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  69970. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  69971. }
  69972. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  69973. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  69974. }
  69975. // else default to high.
  69976. }
  69977. if (this.usePercentageCloserFiltering) {
  69978. defines["SHADOWPCF" + lightIndex] = true;
  69979. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  69980. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  69981. }
  69982. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  69983. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  69984. }
  69985. // else default to high.
  69986. }
  69987. else if (this.usePoissonSampling) {
  69988. defines["SHADOWPOISSON" + lightIndex] = true;
  69989. }
  69990. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  69991. defines["SHADOWESM" + lightIndex] = true;
  69992. }
  69993. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  69994. defines["SHADOWCLOSEESM" + lightIndex] = true;
  69995. }
  69996. if (light.needCube()) {
  69997. defines["SHADOWCUBE" + lightIndex] = true;
  69998. }
  69999. };
  70000. /**
  70001. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  70002. * defined in the generator but impacting the effect).
  70003. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  70004. * @param effect The effect we are binfing the information for
  70005. */
  70006. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  70007. var light = this._light;
  70008. var scene = this._scene;
  70009. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  70010. return;
  70011. }
  70012. var camera = scene.activeCamera;
  70013. if (!camera) {
  70014. return;
  70015. }
  70016. var shadowMap = this.getShadowMap();
  70017. if (!shadowMap) {
  70018. return;
  70019. }
  70020. if (!light.needCube()) {
  70021. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  70022. }
  70023. // Only PCF uses depth stencil texture.
  70024. if (this._filter === ShadowGenerator.FILTER_PCF) {
  70025. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  70026. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  70027. }
  70028. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  70029. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  70030. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  70031. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  70032. }
  70033. else {
  70034. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  70035. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  70036. }
  70037. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  70038. };
  70039. /**
  70040. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  70041. * (eq to shadow prjection matrix * light transform matrix)
  70042. * @returns The transform matrix used to create the shadow map
  70043. */
  70044. ShadowGenerator.prototype.getTransformMatrix = function () {
  70045. var scene = this._scene;
  70046. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  70047. return this._transformMatrix;
  70048. }
  70049. this._currentRenderID = scene.getRenderId();
  70050. this._currentFaceIndexCache = this._currentFaceIndex;
  70051. var lightPosition = this._light.position;
  70052. if (this._light.computeTransformedInformation()) {
  70053. lightPosition = this._light.transformedPosition;
  70054. }
  70055. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  70056. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  70057. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  70058. }
  70059. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  70060. this._cachedPosition.copyFrom(lightPosition);
  70061. this._cachedDirection.copyFrom(this._lightDirection);
  70062. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  70063. var shadowMap = this.getShadowMap();
  70064. if (shadowMap) {
  70065. var renderList = shadowMap.renderList;
  70066. if (renderList) {
  70067. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  70068. }
  70069. }
  70070. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  70071. }
  70072. return this._transformMatrix;
  70073. };
  70074. /**
  70075. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  70076. * Cube and 2D textures for instance.
  70077. */
  70078. ShadowGenerator.prototype.recreateShadowMap = function () {
  70079. var shadowMap = this._shadowMap;
  70080. if (!shadowMap) {
  70081. return;
  70082. }
  70083. // Track render list.
  70084. var renderList = shadowMap.renderList;
  70085. // Clean up existing data.
  70086. this._disposeRTTandPostProcesses();
  70087. // Reinitializes.
  70088. this._initializeGenerator();
  70089. // Reaffect the filter to ensure a correct fallback if necessary.
  70090. this.filter = this.filter;
  70091. // Reaffect the filter.
  70092. this._applyFilterValues();
  70093. // Reaffect Render List.
  70094. this._shadowMap.renderList = renderList;
  70095. };
  70096. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  70097. if (this._shadowMap2) {
  70098. this._shadowMap2.dispose();
  70099. this._shadowMap2 = null;
  70100. }
  70101. if (this._boxBlurPostprocess) {
  70102. this._boxBlurPostprocess.dispose();
  70103. this._boxBlurPostprocess = null;
  70104. }
  70105. if (this._kernelBlurXPostprocess) {
  70106. this._kernelBlurXPostprocess.dispose();
  70107. this._kernelBlurXPostprocess = null;
  70108. }
  70109. if (this._kernelBlurYPostprocess) {
  70110. this._kernelBlurYPostprocess.dispose();
  70111. this._kernelBlurYPostprocess = null;
  70112. }
  70113. this._blurPostProcesses = [];
  70114. };
  70115. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  70116. if (this._shadowMap) {
  70117. this._shadowMap.dispose();
  70118. this._shadowMap = null;
  70119. }
  70120. this._disposeBlurPostProcesses();
  70121. };
  70122. /**
  70123. * Disposes the ShadowGenerator.
  70124. * Returns nothing.
  70125. */
  70126. ShadowGenerator.prototype.dispose = function () {
  70127. this._disposeRTTandPostProcesses();
  70128. if (this._light) {
  70129. this._light._shadowGenerator = null;
  70130. this._light._markMeshesAsLightDirty();
  70131. }
  70132. };
  70133. /**
  70134. * Serializes the shadow generator setup to a json object.
  70135. * @returns The serialized JSON object
  70136. */
  70137. ShadowGenerator.prototype.serialize = function () {
  70138. var serializationObject = {};
  70139. var shadowMap = this.getShadowMap();
  70140. if (!shadowMap) {
  70141. return serializationObject;
  70142. }
  70143. serializationObject.lightId = this._light.id;
  70144. serializationObject.mapSize = shadowMap.getRenderSize();
  70145. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  70146. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  70147. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  70148. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  70149. serializationObject.usePoissonSampling = this.usePoissonSampling;
  70150. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  70151. serializationObject.depthScale = this.depthScale;
  70152. serializationObject.darkness = this.getDarkness();
  70153. serializationObject.blurBoxOffset = this.blurBoxOffset;
  70154. serializationObject.blurKernel = this.blurKernel;
  70155. serializationObject.blurScale = this.blurScale;
  70156. serializationObject.useKernelBlur = this.useKernelBlur;
  70157. serializationObject.transparencyShadow = this._transparencyShadow;
  70158. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  70159. serializationObject.bias = this.bias;
  70160. serializationObject.normalBias = this.normalBias;
  70161. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  70162. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  70163. serializationObject.filteringQuality = this.filteringQuality;
  70164. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  70165. serializationObject.renderList = [];
  70166. if (shadowMap.renderList) {
  70167. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  70168. var mesh = shadowMap.renderList[meshIndex];
  70169. serializationObject.renderList.push(mesh.id);
  70170. }
  70171. }
  70172. return serializationObject;
  70173. };
  70174. /**
  70175. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  70176. * @param parsedShadowGenerator The JSON object to parse
  70177. * @param scene The scene to create the shadow map for
  70178. * @returns The parsed shadow generator
  70179. */
  70180. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  70181. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  70182. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  70183. var shadowMap = shadowGenerator.getShadowMap();
  70184. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  70185. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  70186. meshes.forEach(function (mesh) {
  70187. if (!shadowMap) {
  70188. return;
  70189. }
  70190. if (!shadowMap.renderList) {
  70191. shadowMap.renderList = [];
  70192. }
  70193. shadowMap.renderList.push(mesh);
  70194. });
  70195. }
  70196. if (parsedShadowGenerator.usePoissonSampling) {
  70197. shadowGenerator.usePoissonSampling = true;
  70198. }
  70199. else if (parsedShadowGenerator.useExponentialShadowMap) {
  70200. shadowGenerator.useExponentialShadowMap = true;
  70201. }
  70202. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  70203. shadowGenerator.useBlurExponentialShadowMap = true;
  70204. }
  70205. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  70206. shadowGenerator.useCloseExponentialShadowMap = true;
  70207. }
  70208. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  70209. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  70210. }
  70211. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  70212. shadowGenerator.usePercentageCloserFiltering = true;
  70213. }
  70214. else if (parsedShadowGenerator.useContactHardeningShadow) {
  70215. shadowGenerator.useContactHardeningShadow = true;
  70216. }
  70217. if (parsedShadowGenerator.filteringQuality) {
  70218. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  70219. }
  70220. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  70221. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  70222. }
  70223. // Backward compat
  70224. else if (parsedShadowGenerator.useVarianceShadowMap) {
  70225. shadowGenerator.useExponentialShadowMap = true;
  70226. }
  70227. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  70228. shadowGenerator.useBlurExponentialShadowMap = true;
  70229. }
  70230. if (parsedShadowGenerator.depthScale) {
  70231. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  70232. }
  70233. if (parsedShadowGenerator.blurScale) {
  70234. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  70235. }
  70236. if (parsedShadowGenerator.blurBoxOffset) {
  70237. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  70238. }
  70239. if (parsedShadowGenerator.useKernelBlur) {
  70240. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  70241. }
  70242. if (parsedShadowGenerator.blurKernel) {
  70243. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  70244. }
  70245. if (parsedShadowGenerator.bias !== undefined) {
  70246. shadowGenerator.bias = parsedShadowGenerator.bias;
  70247. }
  70248. if (parsedShadowGenerator.normalBias !== undefined) {
  70249. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  70250. }
  70251. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  70252. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  70253. }
  70254. if (parsedShadowGenerator.darkness) {
  70255. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  70256. }
  70257. if (parsedShadowGenerator.transparencyShadow) {
  70258. shadowGenerator.setTransparencyShadow(true);
  70259. }
  70260. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  70261. return shadowGenerator;
  70262. };
  70263. /**
  70264. * Shadow generator mode None: no filtering applied.
  70265. */
  70266. ShadowGenerator.FILTER_NONE = 0;
  70267. /**
  70268. * Shadow generator mode ESM: Exponential Shadow Mapping.
  70269. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  70270. */
  70271. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  70272. /**
  70273. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  70274. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  70275. */
  70276. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  70277. /**
  70278. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  70279. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  70280. */
  70281. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  70282. /**
  70283. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  70284. * edge artifacts on steep falloff.
  70285. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  70286. */
  70287. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  70288. /**
  70289. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  70290. * edge artifacts on steep falloff.
  70291. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  70292. */
  70293. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  70294. /**
  70295. * Shadow generator mode PCF: Percentage Closer Filtering
  70296. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  70297. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  70298. */
  70299. ShadowGenerator.FILTER_PCF = 6;
  70300. /**
  70301. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  70302. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  70303. * Contact Hardening
  70304. */
  70305. ShadowGenerator.FILTER_PCSS = 7;
  70306. /**
  70307. * Reserved for PCF and PCSS
  70308. * Highest Quality.
  70309. *
  70310. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  70311. *
  70312. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  70313. */
  70314. ShadowGenerator.QUALITY_HIGH = 0;
  70315. /**
  70316. * Reserved for PCF and PCSS
  70317. * Good tradeoff for quality/perf cross devices
  70318. *
  70319. * Execute PCF on a 3*3 kernel.
  70320. *
  70321. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  70322. */
  70323. ShadowGenerator.QUALITY_MEDIUM = 1;
  70324. /**
  70325. * Reserved for PCF and PCSS
  70326. * The lowest quality but the fastest.
  70327. *
  70328. * Execute PCF on a 1*1 kernel.
  70329. *
  70330. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  70331. */
  70332. ShadowGenerator.QUALITY_LOW = 2;
  70333. return ShadowGenerator;
  70334. }());
  70335. BABYLON.ShadowGenerator = ShadowGenerator;
  70336. })(BABYLON || (BABYLON = {}));
  70337. //# sourceMappingURL=babylon.shadowGenerator.js.map
  70338. var BABYLON;
  70339. (function (BABYLON) {
  70340. var DefaultLoadingScreen = /** @class */ (function () {
  70341. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  70342. if (_loadingText === void 0) { _loadingText = ""; }
  70343. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  70344. var _this = this;
  70345. this._renderingCanvas = _renderingCanvas;
  70346. this._loadingText = _loadingText;
  70347. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  70348. // Resize
  70349. this._resizeLoadingUI = function () {
  70350. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  70351. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  70352. if (!_this._loadingDiv) {
  70353. return;
  70354. }
  70355. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  70356. _this._loadingDiv.style.left = canvasRect.left + "px";
  70357. _this._loadingDiv.style.top = canvasRect.top + "px";
  70358. _this._loadingDiv.style.width = canvasRect.width + "px";
  70359. _this._loadingDiv.style.height = canvasRect.height + "px";
  70360. };
  70361. }
  70362. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  70363. if (this._loadingDiv) {
  70364. // Do not add a loading screen if there is already one
  70365. return;
  70366. }
  70367. this._loadingDiv = document.createElement("div");
  70368. this._loadingDiv.id = "babylonjsLoadingDiv";
  70369. this._loadingDiv.style.opacity = "0";
  70370. this._loadingDiv.style.transition = "opacity 1.5s ease";
  70371. this._loadingDiv.style.pointerEvents = "none";
  70372. // Loading text
  70373. this._loadingTextDiv = document.createElement("div");
  70374. this._loadingTextDiv.style.position = "absolute";
  70375. this._loadingTextDiv.style.left = "0";
  70376. this._loadingTextDiv.style.top = "50%";
  70377. this._loadingTextDiv.style.marginTop = "80px";
  70378. this._loadingTextDiv.style.width = "100%";
  70379. this._loadingTextDiv.style.height = "20px";
  70380. this._loadingTextDiv.style.fontFamily = "Arial";
  70381. this._loadingTextDiv.style.fontSize = "14px";
  70382. this._loadingTextDiv.style.color = "white";
  70383. this._loadingTextDiv.style.textAlign = "center";
  70384. this._loadingTextDiv.innerHTML = "Loading";
  70385. this._loadingDiv.appendChild(this._loadingTextDiv);
  70386. //set the predefined text
  70387. this._loadingTextDiv.innerHTML = this._loadingText;
  70388. // Generating keyframes
  70389. var style = document.createElement('style');
  70390. style.type = 'text/css';
  70391. 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 }";
  70392. style.innerHTML = keyFrames;
  70393. document.getElementsByTagName('head')[0].appendChild(style);
  70394. // Loading img
  70395. var imgBack = new Image();
  70396. 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";
  70397. imgBack.style.position = "absolute";
  70398. imgBack.style.left = "50%";
  70399. imgBack.style.top = "50%";
  70400. imgBack.style.marginLeft = "-60px";
  70401. imgBack.style.marginTop = "-60px";
  70402. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  70403. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  70404. imgBack.style.transformOrigin = "50% 50%";
  70405. imgBack.style.webkitTransformOrigin = "50% 50%";
  70406. this._loadingDiv.appendChild(imgBack);
  70407. this._resizeLoadingUI();
  70408. window.addEventListener("resize", this._resizeLoadingUI);
  70409. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  70410. document.body.appendChild(this._loadingDiv);
  70411. this._loadingDiv.style.opacity = "1";
  70412. };
  70413. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  70414. var _this = this;
  70415. if (!this._loadingDiv) {
  70416. return;
  70417. }
  70418. var onTransitionEnd = function () {
  70419. if (!_this._loadingDiv) {
  70420. return;
  70421. }
  70422. document.body.removeChild(_this._loadingDiv);
  70423. window.removeEventListener("resize", _this._resizeLoadingUI);
  70424. _this._loadingDiv = null;
  70425. };
  70426. this._loadingDiv.style.opacity = "0";
  70427. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  70428. };
  70429. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  70430. set: function (text) {
  70431. this._loadingText = text;
  70432. if (this._loadingTextDiv) {
  70433. this._loadingTextDiv.innerHTML = this._loadingText;
  70434. }
  70435. },
  70436. enumerable: true,
  70437. configurable: true
  70438. });
  70439. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  70440. get: function () {
  70441. return this._loadingDivBackgroundColor;
  70442. },
  70443. set: function (color) {
  70444. this._loadingDivBackgroundColor = color;
  70445. if (!this._loadingDiv) {
  70446. return;
  70447. }
  70448. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  70449. },
  70450. enumerable: true,
  70451. configurable: true
  70452. });
  70453. return DefaultLoadingScreen;
  70454. }());
  70455. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  70456. })(BABYLON || (BABYLON = {}));
  70457. //# sourceMappingURL=babylon.loadingScreen.js.map
  70458. var BABYLON;
  70459. (function (BABYLON) {
  70460. var SceneLoaderProgressEvent = /** @class */ (function () {
  70461. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  70462. this.lengthComputable = lengthComputable;
  70463. this.loaded = loaded;
  70464. this.total = total;
  70465. }
  70466. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  70467. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  70468. };
  70469. return SceneLoaderProgressEvent;
  70470. }());
  70471. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  70472. var SceneLoader = /** @class */ (function () {
  70473. function SceneLoader() {
  70474. }
  70475. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  70476. get: function () {
  70477. return 0;
  70478. },
  70479. enumerable: true,
  70480. configurable: true
  70481. });
  70482. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  70483. get: function () {
  70484. return 1;
  70485. },
  70486. enumerable: true,
  70487. configurable: true
  70488. });
  70489. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  70490. get: function () {
  70491. return 2;
  70492. },
  70493. enumerable: true,
  70494. configurable: true
  70495. });
  70496. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  70497. get: function () {
  70498. return 3;
  70499. },
  70500. enumerable: true,
  70501. configurable: true
  70502. });
  70503. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  70504. get: function () {
  70505. return SceneLoader._ForceFullSceneLoadingForIncremental;
  70506. },
  70507. set: function (value) {
  70508. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  70509. },
  70510. enumerable: true,
  70511. configurable: true
  70512. });
  70513. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  70514. get: function () {
  70515. return SceneLoader._ShowLoadingScreen;
  70516. },
  70517. set: function (value) {
  70518. SceneLoader._ShowLoadingScreen = value;
  70519. },
  70520. enumerable: true,
  70521. configurable: true
  70522. });
  70523. Object.defineProperty(SceneLoader, "loggingLevel", {
  70524. get: function () {
  70525. return SceneLoader._loggingLevel;
  70526. },
  70527. set: function (value) {
  70528. SceneLoader._loggingLevel = value;
  70529. },
  70530. enumerable: true,
  70531. configurable: true
  70532. });
  70533. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  70534. get: function () {
  70535. return SceneLoader._CleanBoneMatrixWeights;
  70536. },
  70537. set: function (value) {
  70538. SceneLoader._CleanBoneMatrixWeights = value;
  70539. },
  70540. enumerable: true,
  70541. configurable: true
  70542. });
  70543. SceneLoader._getDefaultPlugin = function () {
  70544. return SceneLoader._registeredPlugins[".babylon"];
  70545. };
  70546. SceneLoader._getPluginForExtension = function (extension) {
  70547. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  70548. if (registeredPlugin) {
  70549. return registeredPlugin;
  70550. }
  70551. 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");
  70552. return SceneLoader._getDefaultPlugin();
  70553. };
  70554. SceneLoader._getPluginForDirectLoad = function (data) {
  70555. for (var extension in SceneLoader._registeredPlugins) {
  70556. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  70557. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  70558. return SceneLoader._registeredPlugins[extension];
  70559. }
  70560. }
  70561. return SceneLoader._getDefaultPlugin();
  70562. };
  70563. SceneLoader._getPluginForFilename = function (sceneFilename) {
  70564. if (sceneFilename.name) {
  70565. sceneFilename = sceneFilename.name;
  70566. }
  70567. var queryStringPosition = sceneFilename.indexOf("?");
  70568. if (queryStringPosition !== -1) {
  70569. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  70570. }
  70571. var dotPosition = sceneFilename.lastIndexOf(".");
  70572. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  70573. return SceneLoader._getPluginForExtension(extension);
  70574. };
  70575. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  70576. SceneLoader._getDirectLoad = function (sceneFilename) {
  70577. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  70578. return sceneFilename.substr(5);
  70579. }
  70580. return null;
  70581. };
  70582. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  70583. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  70584. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  70585. var plugin;
  70586. if (registeredPlugin.plugin.createPlugin) {
  70587. plugin = registeredPlugin.plugin.createPlugin();
  70588. }
  70589. else {
  70590. plugin = registeredPlugin.plugin;
  70591. }
  70592. var useArrayBuffer = registeredPlugin.isBinary;
  70593. var database;
  70594. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  70595. var dataCallback = function (data, responseURL) {
  70596. if (scene.isDisposed) {
  70597. onError("Scene has been disposed");
  70598. return;
  70599. }
  70600. scene.database = database;
  70601. onSuccess(plugin, data, responseURL);
  70602. };
  70603. var request = null;
  70604. var pluginDisposed = false;
  70605. var onDisposeObservable = plugin.onDisposeObservable;
  70606. if (onDisposeObservable) {
  70607. onDisposeObservable.add(function () {
  70608. pluginDisposed = true;
  70609. if (request) {
  70610. request.abort();
  70611. request = null;
  70612. }
  70613. onDispose();
  70614. });
  70615. }
  70616. var manifestChecked = function () {
  70617. if (pluginDisposed) {
  70618. return;
  70619. }
  70620. var url = rootUrl + sceneFilename;
  70621. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  70622. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  70623. } : undefined, database, useArrayBuffer, function (request, exception) {
  70624. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  70625. });
  70626. };
  70627. if (directLoad) {
  70628. dataCallback(directLoad);
  70629. return plugin;
  70630. }
  70631. if (rootUrl.indexOf("file:") === -1) {
  70632. var engine = scene.getEngine();
  70633. var canUseOfflineSupport = engine.enableOfflineSupport;
  70634. if (canUseOfflineSupport) {
  70635. // Also check for exceptions
  70636. var exceptionFound = false;
  70637. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  70638. var regex = _a[_i];
  70639. if (regex.test(rootUrl + sceneFilename)) {
  70640. exceptionFound = true;
  70641. break;
  70642. }
  70643. }
  70644. canUseOfflineSupport = !exceptionFound;
  70645. }
  70646. if (canUseOfflineSupport) {
  70647. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  70648. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  70649. }
  70650. else {
  70651. manifestChecked();
  70652. }
  70653. }
  70654. // Loading file from disk via input file or drag'n'drop
  70655. else {
  70656. var fileOrString = sceneFilename;
  70657. if (fileOrString.name) { // File
  70658. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  70659. }
  70660. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  70661. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  70662. }
  70663. else {
  70664. onError("Unable to find file named " + sceneFilename);
  70665. }
  70666. }
  70667. return plugin;
  70668. };
  70669. // Public functions
  70670. SceneLoader.GetPluginForExtension = function (extension) {
  70671. return SceneLoader._getPluginForExtension(extension).plugin;
  70672. };
  70673. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  70674. return !!SceneLoader._registeredPlugins[extension];
  70675. };
  70676. SceneLoader.RegisterPlugin = function (plugin) {
  70677. if (typeof plugin.extensions === "string") {
  70678. var extension = plugin.extensions;
  70679. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  70680. plugin: plugin,
  70681. isBinary: false
  70682. };
  70683. }
  70684. else {
  70685. var extensions = plugin.extensions;
  70686. Object.keys(extensions).forEach(function (extension) {
  70687. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  70688. plugin: plugin,
  70689. isBinary: extensions[extension].isBinary
  70690. };
  70691. });
  70692. }
  70693. };
  70694. /**
  70695. * Import meshes into a scene
  70696. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  70697. * @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)
  70698. * @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)
  70699. * @param scene the instance of BABYLON.Scene to append to
  70700. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  70701. * @param onProgress a callback with a progress event for each file being loaded
  70702. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  70703. * @param pluginExtension the extension used to determine the plugin
  70704. * @returns The loaded plugin
  70705. */
  70706. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  70707. if (sceneFilename === void 0) { sceneFilename = ""; }
  70708. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  70709. if (onSuccess === void 0) { onSuccess = null; }
  70710. if (onProgress === void 0) { onProgress = null; }
  70711. if (onError === void 0) { onError = null; }
  70712. if (pluginExtension === void 0) { pluginExtension = null; }
  70713. if (!scene) {
  70714. BABYLON.Tools.Error("No scene available to import mesh to");
  70715. return null;
  70716. }
  70717. if (!sceneFilename) {
  70718. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  70719. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  70720. }
  70721. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  70722. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  70723. return null;
  70724. }
  70725. var loadingToken = {};
  70726. scene._addPendingData(loadingToken);
  70727. var disposeHandler = function () {
  70728. scene._removePendingData(loadingToken);
  70729. };
  70730. var errorHandler = function (message, exception) {
  70731. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  70732. if (onError) {
  70733. onError(scene, errorMessage, exception);
  70734. }
  70735. else {
  70736. BABYLON.Tools.Error(errorMessage);
  70737. // should the exception be thrown?
  70738. }
  70739. disposeHandler();
  70740. };
  70741. var progressHandler = onProgress ? function (event) {
  70742. try {
  70743. onProgress(event);
  70744. }
  70745. catch (e) {
  70746. errorHandler("Error in onProgress callback", e);
  70747. }
  70748. } : undefined;
  70749. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  70750. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  70751. if (onSuccess) {
  70752. try {
  70753. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  70754. }
  70755. catch (e) {
  70756. errorHandler("Error in onSuccess callback", e);
  70757. }
  70758. }
  70759. scene._removePendingData(loadingToken);
  70760. };
  70761. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  70762. if (plugin.rewriteRootURL) {
  70763. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  70764. }
  70765. if (sceneFilename === "") {
  70766. if (sceneFilename === "") {
  70767. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  70768. }
  70769. }
  70770. if (plugin.importMesh) {
  70771. var syncedPlugin = plugin;
  70772. var meshes = new Array();
  70773. var particleSystems = new Array();
  70774. var skeletons = new Array();
  70775. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  70776. return;
  70777. }
  70778. scene.loadingPluginName = plugin.name;
  70779. successHandler(meshes, particleSystems, skeletons, []);
  70780. }
  70781. else {
  70782. var asyncedPlugin = plugin;
  70783. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  70784. scene.loadingPluginName = plugin.name;
  70785. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  70786. }).catch(function (error) {
  70787. errorHandler(error.message, error);
  70788. });
  70789. }
  70790. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  70791. };
  70792. /**
  70793. * Import meshes into a scene
  70794. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  70795. * @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)
  70796. * @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)
  70797. * @param scene the instance of BABYLON.Scene to append to
  70798. * @param onProgress a callback with a progress event for each file being loaded
  70799. * @param pluginExtension the extension used to determine the plugin
  70800. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  70801. */
  70802. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  70803. if (sceneFilename === void 0) { sceneFilename = ""; }
  70804. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  70805. if (onProgress === void 0) { onProgress = null; }
  70806. if (pluginExtension === void 0) { pluginExtension = null; }
  70807. return new Promise(function (resolve, reject) {
  70808. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  70809. resolve({
  70810. meshes: meshes,
  70811. particleSystems: particleSystems,
  70812. skeletons: skeletons,
  70813. animationGroups: animationGroups
  70814. });
  70815. }, onProgress, function (scene, message, exception) {
  70816. reject(exception || new Error(message));
  70817. }, pluginExtension);
  70818. });
  70819. };
  70820. /**
  70821. * Load a scene
  70822. * @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)
  70823. * @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)
  70824. * @param engine is the instance of BABYLON.Engine to use to create the scene
  70825. * @param onSuccess a callback with the scene when import succeeds
  70826. * @param onProgress a callback with a progress event for each file being loaded
  70827. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  70828. * @param pluginExtension the extension used to determine the plugin
  70829. * @returns The loaded plugin
  70830. */
  70831. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  70832. if (onSuccess === void 0) { onSuccess = null; }
  70833. if (onProgress === void 0) { onProgress = null; }
  70834. if (onError === void 0) { onError = null; }
  70835. if (pluginExtension === void 0) { pluginExtension = null; }
  70836. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  70837. };
  70838. /**
  70839. * Load a scene
  70840. * @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)
  70841. * @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)
  70842. * @param engine is the instance of BABYLON.Engine to use to create the scene
  70843. * @param onProgress a callback with a progress event for each file being loaded
  70844. * @param pluginExtension the extension used to determine the plugin
  70845. * @returns The loaded scene
  70846. */
  70847. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  70848. if (onProgress === void 0) { onProgress = null; }
  70849. if (pluginExtension === void 0) { pluginExtension = null; }
  70850. return new Promise(function (resolve, reject) {
  70851. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  70852. resolve(scene);
  70853. }, onProgress, function (scene, message, exception) {
  70854. reject(exception || new Error(message));
  70855. }, pluginExtension);
  70856. });
  70857. };
  70858. /**
  70859. * Append a scene
  70860. * @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)
  70861. * @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)
  70862. * @param scene is the instance of BABYLON.Scene to append to
  70863. * @param onSuccess a callback with the scene when import succeeds
  70864. * @param onProgress a callback with a progress event for each file being loaded
  70865. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  70866. * @param pluginExtension the extension used to determine the plugin
  70867. * @returns The loaded plugin
  70868. */
  70869. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  70870. if (sceneFilename === void 0) { sceneFilename = ""; }
  70871. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  70872. if (onSuccess === void 0) { onSuccess = null; }
  70873. if (onProgress === void 0) { onProgress = null; }
  70874. if (onError === void 0) { onError = null; }
  70875. if (pluginExtension === void 0) { pluginExtension = null; }
  70876. if (!scene) {
  70877. BABYLON.Tools.Error("No scene available to append to");
  70878. return null;
  70879. }
  70880. if (!sceneFilename) {
  70881. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  70882. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  70883. }
  70884. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  70885. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  70886. return null;
  70887. }
  70888. if (SceneLoader.ShowLoadingScreen) {
  70889. scene.getEngine().displayLoadingUI();
  70890. }
  70891. var loadingToken = {};
  70892. scene._addPendingData(loadingToken);
  70893. var disposeHandler = function () {
  70894. scene._removePendingData(loadingToken);
  70895. scene.getEngine().hideLoadingUI();
  70896. };
  70897. var errorHandler = function (message, exception) {
  70898. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  70899. if (onError) {
  70900. onError(scene, errorMessage, exception);
  70901. }
  70902. else {
  70903. BABYLON.Tools.Error(errorMessage);
  70904. // should the exception be thrown?
  70905. }
  70906. disposeHandler();
  70907. };
  70908. var progressHandler = onProgress ? function (event) {
  70909. try {
  70910. onProgress(event);
  70911. }
  70912. catch (e) {
  70913. errorHandler("Error in onProgress callback", e);
  70914. }
  70915. } : undefined;
  70916. var successHandler = function () {
  70917. if (onSuccess) {
  70918. try {
  70919. onSuccess(scene);
  70920. }
  70921. catch (e) {
  70922. errorHandler("Error in onSuccess callback", e);
  70923. }
  70924. }
  70925. scene._removePendingData(loadingToken);
  70926. };
  70927. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  70928. if (sceneFilename === "") {
  70929. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  70930. }
  70931. if (plugin.load) {
  70932. var syncedPlugin = plugin;
  70933. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  70934. return;
  70935. }
  70936. scene.loadingPluginName = plugin.name;
  70937. successHandler();
  70938. }
  70939. else {
  70940. var asyncedPlugin = plugin;
  70941. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  70942. scene.loadingPluginName = plugin.name;
  70943. successHandler();
  70944. }).catch(function (error) {
  70945. errorHandler(error.message, error);
  70946. });
  70947. }
  70948. if (SceneLoader.ShowLoadingScreen) {
  70949. scene.executeWhenReady(function () {
  70950. scene.getEngine().hideLoadingUI();
  70951. });
  70952. }
  70953. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  70954. };
  70955. /**
  70956. * Append a scene
  70957. * @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)
  70958. * @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)
  70959. * @param scene is the instance of BABYLON.Scene to append to
  70960. * @param onProgress a callback with a progress event for each file being loaded
  70961. * @param pluginExtension the extension used to determine the plugin
  70962. * @returns The given scene
  70963. */
  70964. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  70965. if (sceneFilename === void 0) { sceneFilename = ""; }
  70966. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  70967. if (onProgress === void 0) { onProgress = null; }
  70968. if (pluginExtension === void 0) { pluginExtension = null; }
  70969. return new Promise(function (resolve, reject) {
  70970. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  70971. resolve(scene);
  70972. }, onProgress, function (scene, message, exception) {
  70973. reject(exception || new Error(message));
  70974. }, pluginExtension);
  70975. });
  70976. };
  70977. /**
  70978. * Load a scene into an asset container
  70979. * @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)
  70980. * @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)
  70981. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  70982. * @param onSuccess a callback with the scene when import succeeds
  70983. * @param onProgress a callback with a progress event for each file being loaded
  70984. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  70985. * @param pluginExtension the extension used to determine the plugin
  70986. * @returns The loaded plugin
  70987. */
  70988. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  70989. if (sceneFilename === void 0) { sceneFilename = ""; }
  70990. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  70991. if (onSuccess === void 0) { onSuccess = null; }
  70992. if (onProgress === void 0) { onProgress = null; }
  70993. if (onError === void 0) { onError = null; }
  70994. if (pluginExtension === void 0) { pluginExtension = null; }
  70995. if (!scene) {
  70996. BABYLON.Tools.Error("No scene available to load asset container to");
  70997. return null;
  70998. }
  70999. if (!sceneFilename) {
  71000. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  71001. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  71002. }
  71003. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  71004. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  71005. return null;
  71006. }
  71007. var loadingToken = {};
  71008. scene._addPendingData(loadingToken);
  71009. var disposeHandler = function () {
  71010. scene._removePendingData(loadingToken);
  71011. };
  71012. var errorHandler = function (message, exception) {
  71013. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  71014. if (onError) {
  71015. onError(scene, errorMessage, exception);
  71016. }
  71017. else {
  71018. BABYLON.Tools.Error(errorMessage);
  71019. // should the exception be thrown?
  71020. }
  71021. disposeHandler();
  71022. };
  71023. var progressHandler = onProgress ? function (event) {
  71024. try {
  71025. onProgress(event);
  71026. }
  71027. catch (e) {
  71028. errorHandler("Error in onProgress callback", e);
  71029. }
  71030. } : undefined;
  71031. var successHandler = function (assets) {
  71032. if (onSuccess) {
  71033. try {
  71034. onSuccess(assets);
  71035. }
  71036. catch (e) {
  71037. errorHandler("Error in onSuccess callback", e);
  71038. }
  71039. }
  71040. scene._removePendingData(loadingToken);
  71041. };
  71042. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  71043. if (plugin.loadAssetContainer) {
  71044. var syncedPlugin = plugin;
  71045. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  71046. if (!assetContainer) {
  71047. return;
  71048. }
  71049. scene.loadingPluginName = plugin.name;
  71050. successHandler(assetContainer);
  71051. }
  71052. else if (plugin.loadAssetContainerAsync) {
  71053. var asyncedPlugin = plugin;
  71054. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  71055. scene.loadingPluginName = plugin.name;
  71056. successHandler(assetContainer);
  71057. }).catch(function (error) {
  71058. errorHandler(error.message, error);
  71059. });
  71060. }
  71061. else {
  71062. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  71063. }
  71064. if (SceneLoader.ShowLoadingScreen) {
  71065. scene.executeWhenReady(function () {
  71066. scene.getEngine().hideLoadingUI();
  71067. });
  71068. }
  71069. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  71070. };
  71071. /**
  71072. * Load a scene into an asset container
  71073. * @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)
  71074. * @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)
  71075. * @param scene is the instance of BABYLON.Scene to append to
  71076. * @param onProgress a callback with a progress event for each file being loaded
  71077. * @param pluginExtension the extension used to determine the plugin
  71078. * @returns The loaded asset container
  71079. */
  71080. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  71081. if (sceneFilename === void 0) { sceneFilename = ""; }
  71082. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  71083. if (onProgress === void 0) { onProgress = null; }
  71084. if (pluginExtension === void 0) { pluginExtension = null; }
  71085. return new Promise(function (resolve, reject) {
  71086. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  71087. resolve(assetContainer);
  71088. }, onProgress, function (scene, message, exception) {
  71089. reject(exception || new Error(message));
  71090. }, pluginExtension);
  71091. });
  71092. };
  71093. // Flags
  71094. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  71095. SceneLoader._ShowLoadingScreen = true;
  71096. SceneLoader._CleanBoneMatrixWeights = false;
  71097. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  71098. // Members
  71099. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  71100. SceneLoader._registeredPlugins = {};
  71101. return SceneLoader;
  71102. }());
  71103. BABYLON.SceneLoader = SceneLoader;
  71104. ;
  71105. })(BABYLON || (BABYLON = {}));
  71106. //# sourceMappingURL=babylon.sceneLoader.js.map
  71107. var BABYLON;
  71108. (function (BABYLON) {
  71109. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  71110. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  71111. var parsedMaterial = parsedData.materials[index];
  71112. if (parsedMaterial.id === id) {
  71113. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  71114. }
  71115. }
  71116. return null;
  71117. };
  71118. var isDescendantOf = function (mesh, names, hierarchyIds) {
  71119. for (var i in names) {
  71120. if (mesh.name === names[i]) {
  71121. hierarchyIds.push(mesh.id);
  71122. return true;
  71123. }
  71124. }
  71125. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  71126. hierarchyIds.push(mesh.id);
  71127. return true;
  71128. }
  71129. return false;
  71130. };
  71131. var logOperation = function (operation, producer) {
  71132. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  71133. };
  71134. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  71135. if (addToScene === void 0) { addToScene = false; }
  71136. var container = new BABYLON.AssetContainer(scene);
  71137. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  71138. // when SceneLoader.debugLogging = true (default), or exception encountered.
  71139. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  71140. // and avoid problems with multiple concurrent .babylon loads.
  71141. var log = "importScene has failed JSON parse";
  71142. try {
  71143. var parsedData = JSON.parse(data);
  71144. log = "";
  71145. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  71146. var index;
  71147. var cache;
  71148. // Lights
  71149. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  71150. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  71151. var parsedLight = parsedData.lights[index];
  71152. var light = BABYLON.Light.Parse(parsedLight, scene);
  71153. if (light) {
  71154. container.lights.push(light);
  71155. log += (index === 0 ? "\n\tLights:" : "");
  71156. log += "\n\t\t" + light.toString(fullDetails);
  71157. }
  71158. }
  71159. }
  71160. // Animations
  71161. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  71162. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  71163. var parsedAnimation = parsedData.animations[index];
  71164. var animation = BABYLON.Animation.Parse(parsedAnimation);
  71165. scene.animations.push(animation);
  71166. container.animations.push(animation);
  71167. log += (index === 0 ? "\n\tAnimations:" : "");
  71168. log += "\n\t\t" + animation.toString(fullDetails);
  71169. }
  71170. }
  71171. // Materials
  71172. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  71173. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  71174. var parsedMaterial = parsedData.materials[index];
  71175. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  71176. container.materials.push(mat);
  71177. log += (index === 0 ? "\n\tMaterials:" : "");
  71178. log += "\n\t\t" + mat.toString(fullDetails);
  71179. }
  71180. }
  71181. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  71182. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  71183. var parsedMultiMaterial = parsedData.multiMaterials[index];
  71184. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  71185. container.multiMaterials.push(mmat);
  71186. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  71187. log += "\n\t\t" + mmat.toString(fullDetails);
  71188. }
  71189. }
  71190. // Morph targets
  71191. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  71192. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  71193. var managerData = _a[_i];
  71194. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  71195. }
  71196. }
  71197. // Skeletons
  71198. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  71199. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  71200. var parsedSkeleton = parsedData.skeletons[index];
  71201. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  71202. container.skeletons.push(skeleton);
  71203. log += (index === 0 ? "\n\tSkeletons:" : "");
  71204. log += "\n\t\t" + skeleton.toString(fullDetails);
  71205. }
  71206. }
  71207. // Geometries
  71208. var geometries = parsedData.geometries;
  71209. if (geometries !== undefined && geometries !== null) {
  71210. var addedGeometry = new Array();
  71211. // Boxes
  71212. var boxes = geometries.boxes;
  71213. if (boxes !== undefined && boxes !== null) {
  71214. for (index = 0, cache = boxes.length; index < cache; index++) {
  71215. var parsedBox = boxes[index];
  71216. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  71217. }
  71218. }
  71219. // Spheres
  71220. var spheres = geometries.spheres;
  71221. if (spheres !== undefined && spheres !== null) {
  71222. for (index = 0, cache = spheres.length; index < cache; index++) {
  71223. var parsedSphere = spheres[index];
  71224. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  71225. }
  71226. }
  71227. // Cylinders
  71228. var cylinders = geometries.cylinders;
  71229. if (cylinders !== undefined && cylinders !== null) {
  71230. for (index = 0, cache = cylinders.length; index < cache; index++) {
  71231. var parsedCylinder = cylinders[index];
  71232. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  71233. }
  71234. }
  71235. // Toruses
  71236. var toruses = geometries.toruses;
  71237. if (toruses !== undefined && toruses !== null) {
  71238. for (index = 0, cache = toruses.length; index < cache; index++) {
  71239. var parsedTorus = toruses[index];
  71240. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  71241. }
  71242. }
  71243. // Grounds
  71244. var grounds = geometries.grounds;
  71245. if (grounds !== undefined && grounds !== null) {
  71246. for (index = 0, cache = grounds.length; index < cache; index++) {
  71247. var parsedGround = grounds[index];
  71248. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  71249. }
  71250. }
  71251. // Planes
  71252. var planes = geometries.planes;
  71253. if (planes !== undefined && planes !== null) {
  71254. for (index = 0, cache = planes.length; index < cache; index++) {
  71255. var parsedPlane = planes[index];
  71256. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  71257. }
  71258. }
  71259. // TorusKnots
  71260. var torusKnots = geometries.torusKnots;
  71261. if (torusKnots !== undefined && torusKnots !== null) {
  71262. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  71263. var parsedTorusKnot = torusKnots[index];
  71264. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  71265. }
  71266. }
  71267. // VertexData
  71268. var vertexData = geometries.vertexData;
  71269. if (vertexData !== undefined && vertexData !== null) {
  71270. for (index = 0, cache = vertexData.length; index < cache; index++) {
  71271. var parsedVertexData = vertexData[index];
  71272. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  71273. }
  71274. }
  71275. addedGeometry.forEach(function (g) {
  71276. if (g) {
  71277. container.geometries.push(g);
  71278. }
  71279. });
  71280. }
  71281. // Transform nodes
  71282. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  71283. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  71284. var parsedTransformNode = parsedData.transformNodes[index];
  71285. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  71286. container.transformNodes.push(node);
  71287. }
  71288. }
  71289. // Meshes
  71290. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  71291. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  71292. var parsedMesh = parsedData.meshes[index];
  71293. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  71294. container.meshes.push(mesh);
  71295. log += (index === 0 ? "\n\tMeshes:" : "");
  71296. log += "\n\t\t" + mesh.toString(fullDetails);
  71297. }
  71298. }
  71299. // Cameras
  71300. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  71301. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  71302. var parsedCamera = parsedData.cameras[index];
  71303. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  71304. container.cameras.push(camera);
  71305. log += (index === 0 ? "\n\tCameras:" : "");
  71306. log += "\n\t\t" + camera.toString(fullDetails);
  71307. }
  71308. }
  71309. // Browsing all the graph to connect the dots
  71310. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  71311. var camera = scene.cameras[index];
  71312. if (camera._waitingParentId) {
  71313. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  71314. camera._waitingParentId = null;
  71315. }
  71316. }
  71317. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  71318. var light_1 = scene.lights[index];
  71319. if (light_1 && light_1._waitingParentId) {
  71320. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  71321. light_1._waitingParentId = null;
  71322. }
  71323. }
  71324. // Sounds
  71325. // TODO: add sound
  71326. var loadedSounds = [];
  71327. var loadedSound;
  71328. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  71329. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  71330. var parsedSound = parsedData.sounds[index];
  71331. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  71332. if (!parsedSound.url)
  71333. parsedSound.url = parsedSound.name;
  71334. if (!loadedSounds[parsedSound.url]) {
  71335. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  71336. loadedSounds[parsedSound.url] = loadedSound;
  71337. container.sounds.push(loadedSound);
  71338. }
  71339. else {
  71340. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  71341. }
  71342. }
  71343. else {
  71344. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  71345. }
  71346. }
  71347. }
  71348. loadedSounds = [];
  71349. // Connect parents & children and parse actions
  71350. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  71351. var transformNode = scene.transformNodes[index];
  71352. if (transformNode._waitingParentId) {
  71353. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  71354. transformNode._waitingParentId = null;
  71355. }
  71356. }
  71357. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  71358. var mesh = scene.meshes[index];
  71359. if (mesh._waitingParentId) {
  71360. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  71361. mesh._waitingParentId = null;
  71362. }
  71363. if (mesh._waitingActions) {
  71364. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  71365. mesh._waitingActions = null;
  71366. }
  71367. }
  71368. // freeze world matrix application
  71369. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  71370. var currentMesh = scene.meshes[index];
  71371. if (currentMesh._waitingFreezeWorldMatrix) {
  71372. currentMesh.freezeWorldMatrix();
  71373. currentMesh._waitingFreezeWorldMatrix = null;
  71374. }
  71375. else {
  71376. currentMesh.computeWorldMatrix(true);
  71377. }
  71378. }
  71379. // Shadows
  71380. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  71381. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  71382. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  71383. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  71384. // SG would be available on their associated lights
  71385. }
  71386. }
  71387. // Lights exclusions / inclusions
  71388. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  71389. var light_2 = scene.lights[index];
  71390. // Excluded check
  71391. if (light_2._excludedMeshesIds.length > 0) {
  71392. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  71393. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  71394. if (excludedMesh) {
  71395. light_2.excludedMeshes.push(excludedMesh);
  71396. }
  71397. }
  71398. light_2._excludedMeshesIds = [];
  71399. }
  71400. // Included check
  71401. if (light_2._includedOnlyMeshesIds.length > 0) {
  71402. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  71403. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  71404. if (includedOnlyMesh) {
  71405. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  71406. }
  71407. }
  71408. light_2._includedOnlyMeshesIds = [];
  71409. }
  71410. }
  71411. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  71412. // Actions (scene)
  71413. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  71414. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  71415. }
  71416. if (!addToScene) {
  71417. container.removeAllFromScene();
  71418. }
  71419. }
  71420. catch (err) {
  71421. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  71422. if (onError) {
  71423. onError(msg, err);
  71424. }
  71425. else {
  71426. BABYLON.Tools.Log(msg);
  71427. throw err;
  71428. }
  71429. }
  71430. finally {
  71431. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  71432. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  71433. }
  71434. }
  71435. return container;
  71436. };
  71437. BABYLON.SceneLoader.RegisterPlugin({
  71438. name: "babylon.js",
  71439. extensions: ".babylon",
  71440. canDirectLoad: function (data) {
  71441. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  71442. return true;
  71443. }
  71444. return false;
  71445. },
  71446. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  71447. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  71448. // when SceneLoader.debugLogging = true (default), or exception encountered.
  71449. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  71450. // and avoid problems with multiple concurrent .babylon loads.
  71451. var log = "importMesh has failed JSON parse";
  71452. try {
  71453. var parsedData = JSON.parse(data);
  71454. log = "";
  71455. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  71456. if (!meshesNames) {
  71457. meshesNames = null;
  71458. }
  71459. else if (!Array.isArray(meshesNames)) {
  71460. meshesNames = [meshesNames];
  71461. }
  71462. var hierarchyIds = new Array();
  71463. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  71464. var loadedSkeletonsIds = [];
  71465. var loadedMaterialsIds = [];
  71466. var index;
  71467. var cache;
  71468. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  71469. var parsedMesh = parsedData.meshes[index];
  71470. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  71471. if (meshesNames !== null) {
  71472. // Remove found mesh name from list.
  71473. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  71474. }
  71475. //Geometry?
  71476. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  71477. //does the file contain geometries?
  71478. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  71479. //find the correct geometry and add it to the scene
  71480. var found = false;
  71481. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  71482. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  71483. return;
  71484. }
  71485. else {
  71486. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  71487. if (parsedGeometryData.id === parsedMesh.geometryId) {
  71488. switch (geometryType) {
  71489. case "boxes":
  71490. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  71491. break;
  71492. case "spheres":
  71493. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  71494. break;
  71495. case "cylinders":
  71496. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  71497. break;
  71498. case "toruses":
  71499. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  71500. break;
  71501. case "grounds":
  71502. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  71503. break;
  71504. case "planes":
  71505. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  71506. break;
  71507. case "torusKnots":
  71508. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  71509. break;
  71510. case "vertexData":
  71511. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  71512. break;
  71513. }
  71514. found = true;
  71515. }
  71516. });
  71517. }
  71518. });
  71519. if (found === false) {
  71520. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  71521. }
  71522. }
  71523. }
  71524. // Material ?
  71525. if (parsedMesh.materialId) {
  71526. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  71527. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  71528. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  71529. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  71530. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  71531. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  71532. var subMatId = parsedMultiMaterial.materials[matIndex];
  71533. loadedMaterialsIds.push(subMatId);
  71534. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  71535. if (mat) {
  71536. log += "\n\tMaterial " + mat.toString(fullDetails);
  71537. }
  71538. }
  71539. loadedMaterialsIds.push(parsedMultiMaterial.id);
  71540. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  71541. if (mmat) {
  71542. materialFound = true;
  71543. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  71544. }
  71545. break;
  71546. }
  71547. }
  71548. }
  71549. if (materialFound === false) {
  71550. loadedMaterialsIds.push(parsedMesh.materialId);
  71551. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  71552. if (!mat) {
  71553. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  71554. }
  71555. else {
  71556. log += "\n\tMaterial " + mat.toString(fullDetails);
  71557. }
  71558. }
  71559. }
  71560. // Skeleton ?
  71561. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  71562. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  71563. if (skeletonAlreadyLoaded === false) {
  71564. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  71565. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  71566. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  71567. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  71568. skeletons.push(skeleton);
  71569. loadedSkeletonsIds.push(parsedSkeleton.id);
  71570. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  71571. }
  71572. }
  71573. }
  71574. }
  71575. // Morph targets ?
  71576. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  71577. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  71578. var managerData = _a[_i];
  71579. BABYLON.MorphTargetManager.Parse(managerData, scene);
  71580. }
  71581. }
  71582. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  71583. meshes.push(mesh);
  71584. log += "\n\tMesh " + mesh.toString(fullDetails);
  71585. }
  71586. }
  71587. // Connecting parents
  71588. var currentMesh;
  71589. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  71590. currentMesh = scene.meshes[index];
  71591. if (currentMesh._waitingParentId) {
  71592. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  71593. currentMesh._waitingParentId = null;
  71594. }
  71595. }
  71596. // freeze and compute world matrix application
  71597. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  71598. currentMesh = scene.meshes[index];
  71599. if (currentMesh._waitingFreezeWorldMatrix) {
  71600. currentMesh.freezeWorldMatrix();
  71601. currentMesh._waitingFreezeWorldMatrix = null;
  71602. }
  71603. else {
  71604. currentMesh.computeWorldMatrix(true);
  71605. }
  71606. }
  71607. }
  71608. // Particles
  71609. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  71610. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  71611. if (parser) {
  71612. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  71613. var parsedParticleSystem = parsedData.particleSystems[index];
  71614. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  71615. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  71616. }
  71617. }
  71618. }
  71619. }
  71620. return true;
  71621. }
  71622. catch (err) {
  71623. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  71624. if (onError) {
  71625. onError(msg, err);
  71626. }
  71627. else {
  71628. BABYLON.Tools.Log(msg);
  71629. throw err;
  71630. }
  71631. }
  71632. finally {
  71633. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  71634. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  71635. }
  71636. }
  71637. return false;
  71638. },
  71639. load: function (scene, data, rootUrl, onError) {
  71640. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  71641. // when SceneLoader.debugLogging = true (default), or exception encountered.
  71642. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  71643. // and avoid problems with multiple concurrent .babylon loads.
  71644. var log = "importScene has failed JSON parse";
  71645. try {
  71646. var parsedData = JSON.parse(data);
  71647. log = "";
  71648. // Scene
  71649. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  71650. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  71651. }
  71652. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  71653. scene.autoClear = parsedData.autoClear;
  71654. }
  71655. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  71656. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  71657. }
  71658. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  71659. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  71660. }
  71661. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  71662. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  71663. }
  71664. // Fog
  71665. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  71666. scene.fogMode = parsedData.fogMode;
  71667. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  71668. scene.fogStart = parsedData.fogStart;
  71669. scene.fogEnd = parsedData.fogEnd;
  71670. scene.fogDensity = parsedData.fogDensity;
  71671. log += "\tFog mode for scene: ";
  71672. switch (scene.fogMode) {
  71673. // getters not compiling, so using hardcoded
  71674. case 1:
  71675. log += "exp\n";
  71676. break;
  71677. case 2:
  71678. log += "exp2\n";
  71679. break;
  71680. case 3:
  71681. log += "linear\n";
  71682. break;
  71683. }
  71684. }
  71685. //Physics
  71686. if (parsedData.physicsEnabled) {
  71687. var physicsPlugin;
  71688. if (parsedData.physicsEngine === "cannon") {
  71689. physicsPlugin = new BABYLON.CannonJSPlugin();
  71690. }
  71691. else if (parsedData.physicsEngine === "oimo") {
  71692. physicsPlugin = new BABYLON.OimoJSPlugin();
  71693. }
  71694. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  71695. //else - default engine, which is currently oimo
  71696. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  71697. scene.enablePhysics(physicsGravity, physicsPlugin);
  71698. }
  71699. // Metadata
  71700. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  71701. scene.metadata = parsedData.metadata;
  71702. }
  71703. //collisions, if defined. otherwise, default is true
  71704. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  71705. scene.collisionsEnabled = parsedData.collisionsEnabled;
  71706. }
  71707. scene.workerCollisions = !!parsedData.workerCollisions;
  71708. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  71709. if (!container) {
  71710. return false;
  71711. }
  71712. if (parsedData.autoAnimate) {
  71713. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  71714. }
  71715. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  71716. scene.setActiveCameraByID(parsedData.activeCameraID);
  71717. }
  71718. // Environment texture
  71719. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  71720. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  71721. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  71722. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  71723. if (parsedData.environmentTextureRotationY) {
  71724. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  71725. }
  71726. scene.environmentTexture = hdrTexture;
  71727. }
  71728. else {
  71729. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  71730. if (parsedData.environmentTextureRotationY) {
  71731. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  71732. }
  71733. scene.environmentTexture = cubeTexture;
  71734. }
  71735. if (parsedData.createDefaultSkybox === true) {
  71736. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  71737. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  71738. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  71739. }
  71740. }
  71741. // Finish
  71742. return true;
  71743. }
  71744. catch (err) {
  71745. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  71746. if (onError) {
  71747. onError(msg, err);
  71748. }
  71749. else {
  71750. BABYLON.Tools.Log(msg);
  71751. throw err;
  71752. }
  71753. }
  71754. finally {
  71755. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  71756. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  71757. }
  71758. }
  71759. return false;
  71760. },
  71761. loadAssetContainer: function (scene, data, rootUrl, onError) {
  71762. var container = loadAssetContainer(scene, data, rootUrl, onError);
  71763. return container;
  71764. }
  71765. });
  71766. })(BABYLON || (BABYLON = {}));
  71767. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  71768. var BABYLON;
  71769. (function (BABYLON) {
  71770. var FilesInput = /** @class */ (function () {
  71771. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  71772. this.onProcessFileCallback = function () { return true; };
  71773. this._engine = engine;
  71774. this._currentScene = scene;
  71775. this._sceneLoadedCallback = sceneLoadedCallback;
  71776. this._progressCallback = progressCallback;
  71777. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  71778. this._textureLoadingCallback = textureLoadingCallback;
  71779. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  71780. this._onReloadCallback = onReloadCallback;
  71781. this._errorCallback = errorCallback;
  71782. }
  71783. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  71784. var _this = this;
  71785. if (elementToMonitor) {
  71786. this._elementToMonitor = elementToMonitor;
  71787. this._dragEnterHandler = function (e) { _this.drag(e); };
  71788. this._dragOverHandler = function (e) { _this.drag(e); };
  71789. this._dropHandler = function (e) { _this.drop(e); };
  71790. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  71791. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  71792. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  71793. }
  71794. };
  71795. FilesInput.prototype.dispose = function () {
  71796. if (!this._elementToMonitor) {
  71797. return;
  71798. }
  71799. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  71800. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  71801. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  71802. };
  71803. FilesInput.prototype.renderFunction = function () {
  71804. if (this._additionalRenderLoopLogicCallback) {
  71805. this._additionalRenderLoopLogicCallback();
  71806. }
  71807. if (this._currentScene) {
  71808. if (this._textureLoadingCallback) {
  71809. var remaining = this._currentScene.getWaitingItemsCount();
  71810. if (remaining > 0) {
  71811. this._textureLoadingCallback(remaining);
  71812. }
  71813. }
  71814. this._currentScene.render();
  71815. }
  71816. };
  71817. FilesInput.prototype.drag = function (e) {
  71818. e.stopPropagation();
  71819. e.preventDefault();
  71820. };
  71821. FilesInput.prototype.drop = function (eventDrop) {
  71822. eventDrop.stopPropagation();
  71823. eventDrop.preventDefault();
  71824. this.loadFiles(eventDrop);
  71825. };
  71826. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  71827. var _this = this;
  71828. var reader = folder.createReader();
  71829. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  71830. reader.readEntries(function (entries) {
  71831. remaining.count += entries.length;
  71832. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  71833. var entry = entries_1[_i];
  71834. if (entry.isFile) {
  71835. entry.file(function (file) {
  71836. file.correctName = relativePath + file.name;
  71837. files.push(file);
  71838. if (--remaining.count === 0) {
  71839. callback();
  71840. }
  71841. });
  71842. }
  71843. else if (entry.isDirectory) {
  71844. _this._traverseFolder(entry, files, remaining, callback);
  71845. }
  71846. }
  71847. if (--remaining.count) {
  71848. callback();
  71849. }
  71850. });
  71851. };
  71852. FilesInput.prototype._processFiles = function (files) {
  71853. for (var i = 0; i < files.length; i++) {
  71854. var name = files[i].correctName.toLowerCase();
  71855. var extension = name.split('.').pop();
  71856. if (!this.onProcessFileCallback(files[i], name, extension)) {
  71857. continue;
  71858. }
  71859. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  71860. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  71861. this._sceneFileToLoad = files[i];
  71862. }
  71863. else {
  71864. FilesInput.FilesToLoad[name] = files[i];
  71865. }
  71866. }
  71867. };
  71868. FilesInput.prototype.loadFiles = function (event) {
  71869. var _this = this;
  71870. // Handling data transfer via drag'n'drop
  71871. if (event && event.dataTransfer && event.dataTransfer.files) {
  71872. this._filesToLoad = event.dataTransfer.files;
  71873. }
  71874. // Handling files from input files
  71875. if (event && event.target && event.target.files) {
  71876. this._filesToLoad = event.target.files;
  71877. }
  71878. if (!this._filesToLoad || this._filesToLoad.length === 0) {
  71879. return;
  71880. }
  71881. if (this._startingProcessingFilesCallback) {
  71882. this._startingProcessingFilesCallback(this._filesToLoad);
  71883. }
  71884. if (this._filesToLoad && this._filesToLoad.length > 0) {
  71885. var files_1 = new Array();
  71886. var folders = [];
  71887. var items = event.dataTransfer ? event.dataTransfer.items : null;
  71888. for (var i = 0; i < this._filesToLoad.length; i++) {
  71889. var fileToLoad = this._filesToLoad[i];
  71890. var name_1 = fileToLoad.name.toLowerCase();
  71891. var entry = void 0;
  71892. fileToLoad.correctName = name_1;
  71893. if (items) {
  71894. var item = items[i];
  71895. if (item.getAsEntry) {
  71896. entry = item.getAsEntry();
  71897. }
  71898. else if (item.webkitGetAsEntry) {
  71899. entry = item.webkitGetAsEntry();
  71900. }
  71901. }
  71902. if (!entry) {
  71903. files_1.push(fileToLoad);
  71904. }
  71905. else {
  71906. if (entry.isDirectory) {
  71907. folders.push(entry);
  71908. }
  71909. else {
  71910. files_1.push(fileToLoad);
  71911. }
  71912. }
  71913. }
  71914. if (folders.length === 0) {
  71915. this._processFiles(files_1);
  71916. this._processReload();
  71917. }
  71918. else {
  71919. var remaining = { count: folders.length };
  71920. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  71921. var folder = folders_1[_i];
  71922. this._traverseFolder(folder, files_1, remaining, function () {
  71923. _this._processFiles(files_1);
  71924. if (remaining.count === 0) {
  71925. _this._processReload();
  71926. }
  71927. });
  71928. }
  71929. }
  71930. }
  71931. };
  71932. FilesInput.prototype._processReload = function () {
  71933. if (this._onReloadCallback) {
  71934. this._onReloadCallback(this._sceneFileToLoad);
  71935. }
  71936. else {
  71937. this.reload();
  71938. }
  71939. };
  71940. FilesInput.prototype.reload = function () {
  71941. var _this = this;
  71942. // If a scene file has been provided
  71943. if (this._sceneFileToLoad) {
  71944. if (this._currentScene) {
  71945. if (BABYLON.Tools.errorsCount > 0) {
  71946. BABYLON.Tools.ClearLogCache();
  71947. }
  71948. this._engine.stopRenderLoop();
  71949. }
  71950. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  71951. if (_this._progressCallback) {
  71952. _this._progressCallback(progress);
  71953. }
  71954. }).then(function (scene) {
  71955. if (_this._currentScene) {
  71956. _this._currentScene.dispose();
  71957. }
  71958. _this._currentScene = scene;
  71959. if (_this._sceneLoadedCallback) {
  71960. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  71961. }
  71962. // Wait for textures and shaders to be ready
  71963. _this._currentScene.executeWhenReady(function () {
  71964. _this._engine.runRenderLoop(function () {
  71965. _this.renderFunction();
  71966. });
  71967. });
  71968. }).catch(function (error) {
  71969. if (_this._errorCallback) {
  71970. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  71971. }
  71972. });
  71973. }
  71974. else {
  71975. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  71976. }
  71977. };
  71978. FilesInput.FilesToLoad = {};
  71979. return FilesInput;
  71980. }());
  71981. BABYLON.FilesInput = FilesInput;
  71982. })(BABYLON || (BABYLON = {}));
  71983. //# sourceMappingURL=babylon.filesInput.js.map
  71984. var BABYLON;
  71985. (function (BABYLON) {
  71986. var Tags = /** @class */ (function () {
  71987. function Tags() {
  71988. }
  71989. Tags.EnableFor = function (obj) {
  71990. obj._tags = obj._tags || {};
  71991. obj.hasTags = function () {
  71992. return Tags.HasTags(obj);
  71993. };
  71994. obj.addTags = function (tagsString) {
  71995. return Tags.AddTagsTo(obj, tagsString);
  71996. };
  71997. obj.removeTags = function (tagsString) {
  71998. return Tags.RemoveTagsFrom(obj, tagsString);
  71999. };
  72000. obj.matchesTagsQuery = function (tagsQuery) {
  72001. return Tags.MatchesQuery(obj, tagsQuery);
  72002. };
  72003. };
  72004. Tags.DisableFor = function (obj) {
  72005. delete obj._tags;
  72006. delete obj.hasTags;
  72007. delete obj.addTags;
  72008. delete obj.removeTags;
  72009. delete obj.matchesTagsQuery;
  72010. };
  72011. Tags.HasTags = function (obj) {
  72012. if (!obj._tags) {
  72013. return false;
  72014. }
  72015. return !BABYLON.Tools.IsEmpty(obj._tags);
  72016. };
  72017. Tags.GetTags = function (obj, asString) {
  72018. if (asString === void 0) { asString = true; }
  72019. if (!obj._tags) {
  72020. return null;
  72021. }
  72022. if (asString) {
  72023. var tagsArray = [];
  72024. for (var tag in obj._tags) {
  72025. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  72026. tagsArray.push(tag);
  72027. }
  72028. }
  72029. return tagsArray.join(" ");
  72030. }
  72031. else {
  72032. return obj._tags;
  72033. }
  72034. };
  72035. // the tags 'true' and 'false' are reserved and cannot be used as tags
  72036. // a tag cannot start with '||', '&&', and '!'
  72037. // it cannot contain whitespaces
  72038. Tags.AddTagsTo = function (obj, tagsString) {
  72039. if (!tagsString) {
  72040. return;
  72041. }
  72042. if (typeof tagsString !== "string") {
  72043. return;
  72044. }
  72045. var tags = tagsString.split(" ");
  72046. tags.forEach(function (tag, index, array) {
  72047. Tags._AddTagTo(obj, tag);
  72048. });
  72049. };
  72050. Tags._AddTagTo = function (obj, tag) {
  72051. tag = tag.trim();
  72052. if (tag === "" || tag === "true" || tag === "false") {
  72053. return;
  72054. }
  72055. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  72056. return;
  72057. }
  72058. Tags.EnableFor(obj);
  72059. obj._tags[tag] = true;
  72060. };
  72061. Tags.RemoveTagsFrom = function (obj, tagsString) {
  72062. if (!Tags.HasTags(obj)) {
  72063. return;
  72064. }
  72065. var tags = tagsString.split(" ");
  72066. for (var t in tags) {
  72067. Tags._RemoveTagFrom(obj, tags[t]);
  72068. }
  72069. };
  72070. Tags._RemoveTagFrom = function (obj, tag) {
  72071. delete obj._tags[tag];
  72072. };
  72073. Tags.MatchesQuery = function (obj, tagsQuery) {
  72074. if (tagsQuery === undefined) {
  72075. return true;
  72076. }
  72077. if (tagsQuery === "") {
  72078. return Tags.HasTags(obj);
  72079. }
  72080. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  72081. };
  72082. return Tags;
  72083. }());
  72084. BABYLON.Tags = Tags;
  72085. })(BABYLON || (BABYLON = {}));
  72086. //# sourceMappingURL=babylon.tags.js.map
  72087. var BABYLON;
  72088. (function (BABYLON) {
  72089. /**
  72090. * Class used to evalaute queries containing `and` and `or` operators
  72091. */
  72092. var AndOrNotEvaluator = /** @class */ (function () {
  72093. function AndOrNotEvaluator() {
  72094. }
  72095. /**
  72096. * Evaluate a query
  72097. * @param query defines the query to evaluate
  72098. * @param evaluateCallback defines the callback used to filter result
  72099. * @returns true if the query matches
  72100. */
  72101. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  72102. if (!query.match(/\([^\(\)]*\)/g)) {
  72103. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  72104. }
  72105. else {
  72106. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  72107. // remove parenthesis
  72108. r = r.slice(1, r.length - 1);
  72109. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  72110. });
  72111. }
  72112. if (query === "true") {
  72113. return true;
  72114. }
  72115. if (query === "false") {
  72116. return false;
  72117. }
  72118. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  72119. };
  72120. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  72121. evaluateCallback = evaluateCallback || (function (r) {
  72122. return r === "true" ? true : false;
  72123. });
  72124. var result;
  72125. var or = parenthesisContent.split("||");
  72126. for (var i in or) {
  72127. if (or.hasOwnProperty(i)) {
  72128. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  72129. var and = ori.split("&&");
  72130. if (and.length > 1) {
  72131. for (var j = 0; j < and.length; ++j) {
  72132. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  72133. if (andj !== "true" && andj !== "false") {
  72134. if (andj[0] === "!") {
  72135. result = !evaluateCallback(andj.substring(1));
  72136. }
  72137. else {
  72138. result = evaluateCallback(andj);
  72139. }
  72140. }
  72141. else {
  72142. result = andj === "true" ? true : false;
  72143. }
  72144. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  72145. ori = "false";
  72146. break;
  72147. }
  72148. }
  72149. }
  72150. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  72151. result = true;
  72152. break;
  72153. }
  72154. // result equals false (or undefined)
  72155. if (ori !== "true" && ori !== "false") {
  72156. if (ori[0] === "!") {
  72157. result = !evaluateCallback(ori.substring(1));
  72158. }
  72159. else {
  72160. result = evaluateCallback(ori);
  72161. }
  72162. }
  72163. else {
  72164. result = ori === "true" ? true : false;
  72165. }
  72166. }
  72167. }
  72168. // the whole parenthesis scope is replaced by 'true' or 'false'
  72169. return result ? "true" : "false";
  72170. };
  72171. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  72172. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  72173. // remove whitespaces
  72174. r = r.replace(/[\s]/g, function () { return ""; });
  72175. return r.length % 2 ? "!" : "";
  72176. });
  72177. booleanString = booleanString.trim();
  72178. if (booleanString === "!true") {
  72179. booleanString = "false";
  72180. }
  72181. else if (booleanString === "!false") {
  72182. booleanString = "true";
  72183. }
  72184. return booleanString;
  72185. };
  72186. return AndOrNotEvaluator;
  72187. }());
  72188. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  72189. })(BABYLON || (BABYLON = {}));
  72190. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  72191. var BABYLON;
  72192. (function (BABYLON) {
  72193. /**
  72194. * Class used to enable access to IndexedDB
  72195. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  72196. */
  72197. var Database = /** @class */ (function () {
  72198. /**
  72199. * Creates a new Database
  72200. * @param urlToScene defines the url to load the scene
  72201. * @param callbackManifestChecked defines the callback to use when manifest is checked
  72202. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  72203. */
  72204. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  72205. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  72206. var _this = this;
  72207. // Handling various flavors of prefixed version of IndexedDB
  72208. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  72209. this.callbackManifestChecked = callbackManifestChecked;
  72210. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  72211. this.db = null;
  72212. this._enableSceneOffline = false;
  72213. this._enableTexturesOffline = false;
  72214. this.manifestVersionFound = 0;
  72215. this.mustUpdateRessources = false;
  72216. this.hasReachedQuota = false;
  72217. if (!Database.IDBStorageEnabled) {
  72218. this.callbackManifestChecked(true);
  72219. }
  72220. else {
  72221. if (disableManifestCheck) {
  72222. this._enableSceneOffline = true;
  72223. this._enableTexturesOffline = true;
  72224. this.manifestVersionFound = 1;
  72225. BABYLON.Tools.SetImmediate(function () {
  72226. _this.callbackManifestChecked(true);
  72227. });
  72228. }
  72229. else {
  72230. this._checkManifestFile();
  72231. }
  72232. }
  72233. }
  72234. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  72235. /**
  72236. * Gets a boolean indicating if scene must be saved in the database
  72237. */
  72238. get: function () {
  72239. return this._enableSceneOffline;
  72240. },
  72241. enumerable: true,
  72242. configurable: true
  72243. });
  72244. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  72245. /**
  72246. * Gets a boolean indicating if textures must be saved in the database
  72247. */
  72248. get: function () {
  72249. return this._enableTexturesOffline;
  72250. },
  72251. enumerable: true,
  72252. configurable: true
  72253. });
  72254. Database.prototype._checkManifestFile = function () {
  72255. var _this = this;
  72256. var noManifestFile = function () {
  72257. _this._enableSceneOffline = false;
  72258. _this._enableTexturesOffline = false;
  72259. _this.callbackManifestChecked(false);
  72260. };
  72261. var timeStampUsed = false;
  72262. var manifestURL = this.currentSceneUrl + ".manifest";
  72263. var xhr = new XMLHttpRequest();
  72264. if (navigator.onLine) {
  72265. // Adding a timestamp to by-pass browsers' cache
  72266. timeStampUsed = true;
  72267. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  72268. }
  72269. xhr.open("GET", manifestURL, true);
  72270. xhr.addEventListener("load", function () {
  72271. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  72272. try {
  72273. var manifestFile = JSON.parse(xhr.response);
  72274. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  72275. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  72276. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  72277. _this.manifestVersionFound = manifestFile.version;
  72278. }
  72279. if (_this.callbackManifestChecked) {
  72280. _this.callbackManifestChecked(true);
  72281. }
  72282. }
  72283. catch (ex) {
  72284. noManifestFile();
  72285. }
  72286. }
  72287. else {
  72288. noManifestFile();
  72289. }
  72290. }, false);
  72291. xhr.addEventListener("error", function (event) {
  72292. if (timeStampUsed) {
  72293. timeStampUsed = false;
  72294. // Let's retry without the timeStamp
  72295. // It could fail when coupled with HTML5 Offline API
  72296. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  72297. xhr.open("GET", retryManifestURL, true);
  72298. xhr.send();
  72299. }
  72300. else {
  72301. noManifestFile();
  72302. }
  72303. }, false);
  72304. try {
  72305. xhr.send();
  72306. }
  72307. catch (ex) {
  72308. BABYLON.Tools.Error("Error on XHR send request.");
  72309. this.callbackManifestChecked(false);
  72310. }
  72311. };
  72312. /**
  72313. * Open the database and make it available
  72314. * @param successCallback defines the callback to call on success
  72315. * @param errorCallback defines the callback to call on error
  72316. */
  72317. Database.prototype.openAsync = function (successCallback, errorCallback) {
  72318. var _this = this;
  72319. var handleError = function () {
  72320. _this.isSupported = false;
  72321. if (errorCallback)
  72322. errorCallback();
  72323. };
  72324. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  72325. // Your browser doesn't support IndexedDB
  72326. this.isSupported = false;
  72327. if (errorCallback)
  72328. errorCallback();
  72329. }
  72330. else {
  72331. // If the DB hasn't been opened or created yet
  72332. if (!this.db) {
  72333. this.hasReachedQuota = false;
  72334. this.isSupported = true;
  72335. var request = this.idbFactory.open("babylonjs", 1);
  72336. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  72337. request.onerror = function (event) {
  72338. handleError();
  72339. };
  72340. // executes when a version change transaction cannot complete due to other active transactions
  72341. request.onblocked = function (event) {
  72342. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  72343. handleError();
  72344. };
  72345. // DB has been opened successfully
  72346. request.onsuccess = function (event) {
  72347. _this.db = request.result;
  72348. successCallback();
  72349. };
  72350. // Initialization of the DB. Creating Scenes & Textures stores
  72351. request.onupgradeneeded = function (event) {
  72352. _this.db = (event.target).result;
  72353. if (_this.db) {
  72354. try {
  72355. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  72356. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  72357. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  72358. }
  72359. catch (ex) {
  72360. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  72361. handleError();
  72362. }
  72363. }
  72364. };
  72365. }
  72366. // DB has already been created and opened
  72367. else {
  72368. if (successCallback)
  72369. successCallback();
  72370. }
  72371. }
  72372. };
  72373. /**
  72374. * Loads an image from the database
  72375. * @param url defines the url to load from
  72376. * @param image defines the target DOM image
  72377. */
  72378. Database.prototype.loadImageFromDB = function (url, image) {
  72379. var _this = this;
  72380. var completeURL = Database._ReturnFullUrlLocation(url);
  72381. var saveAndLoadImage = function () {
  72382. if (!_this.hasReachedQuota && _this.db !== null) {
  72383. // the texture is not yet in the DB, let's try to save it
  72384. _this._saveImageIntoDBAsync(completeURL, image);
  72385. }
  72386. // If the texture is not in the DB and we've reached the DB quota limit
  72387. // let's load it directly from the web
  72388. else {
  72389. image.src = url;
  72390. }
  72391. };
  72392. if (!this.mustUpdateRessources) {
  72393. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  72394. }
  72395. // First time we're download the images or update requested in the manifest file by a version change
  72396. else {
  72397. saveAndLoadImage();
  72398. }
  72399. };
  72400. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  72401. if (this.isSupported && this.db !== null) {
  72402. var texture;
  72403. var transaction = this.db.transaction(["textures"]);
  72404. transaction.onabort = function (event) {
  72405. image.src = url;
  72406. };
  72407. transaction.oncomplete = function (event) {
  72408. var blobTextureURL;
  72409. if (texture) {
  72410. var URL = window.URL || window.webkitURL;
  72411. blobTextureURL = URL.createObjectURL(texture.data);
  72412. image.onerror = function () {
  72413. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  72414. image.src = url;
  72415. };
  72416. image.src = blobTextureURL;
  72417. }
  72418. else {
  72419. notInDBCallback();
  72420. }
  72421. };
  72422. var getRequest = transaction.objectStore("textures").get(url);
  72423. getRequest.onsuccess = function (event) {
  72424. texture = (event.target).result;
  72425. };
  72426. getRequest.onerror = function (event) {
  72427. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  72428. image.src = url;
  72429. };
  72430. }
  72431. else {
  72432. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  72433. image.src = url;
  72434. }
  72435. };
  72436. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  72437. var _this = this;
  72438. if (this.isSupported) {
  72439. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  72440. var generateBlobUrl = function () {
  72441. var blobTextureURL;
  72442. if (blob) {
  72443. var URL = window.URL || window.webkitURL;
  72444. try {
  72445. blobTextureURL = URL.createObjectURL(blob);
  72446. }
  72447. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  72448. catch (ex) {
  72449. blobTextureURL = URL.createObjectURL(blob);
  72450. }
  72451. }
  72452. if (blobTextureURL) {
  72453. image.src = blobTextureURL;
  72454. }
  72455. };
  72456. if (Database.IsUASupportingBlobStorage) { // Create XHR
  72457. var xhr = new XMLHttpRequest(), blob;
  72458. xhr.open("GET", url, true);
  72459. xhr.responseType = "blob";
  72460. xhr.addEventListener("load", function () {
  72461. if (xhr.status === 200 && _this.db) {
  72462. // Blob as response (XHR2)
  72463. blob = xhr.response;
  72464. var transaction = _this.db.transaction(["textures"], "readwrite");
  72465. // the transaction could abort because of a QuotaExceededError error
  72466. transaction.onabort = function (event) {
  72467. try {
  72468. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  72469. var srcElement = (event.srcElement || event.target);
  72470. var error = srcElement.error;
  72471. if (error && error.name === "QuotaExceededError") {
  72472. _this.hasReachedQuota = true;
  72473. }
  72474. }
  72475. catch (ex) { }
  72476. generateBlobUrl();
  72477. };
  72478. transaction.oncomplete = function (event) {
  72479. generateBlobUrl();
  72480. };
  72481. var newTexture = { textureUrl: url, data: blob };
  72482. try {
  72483. // Put the blob into the dabase
  72484. var addRequest = transaction.objectStore("textures").put(newTexture);
  72485. addRequest.onsuccess = function (event) {
  72486. };
  72487. addRequest.onerror = function (event) {
  72488. generateBlobUrl();
  72489. };
  72490. }
  72491. catch (ex) {
  72492. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  72493. if (ex.code === 25) {
  72494. Database.IsUASupportingBlobStorage = false;
  72495. }
  72496. image.src = url;
  72497. }
  72498. }
  72499. else {
  72500. image.src = url;
  72501. }
  72502. }, false);
  72503. xhr.addEventListener("error", function (event) {
  72504. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  72505. image.src = url;
  72506. }, false);
  72507. xhr.send();
  72508. }
  72509. else {
  72510. image.src = url;
  72511. }
  72512. }
  72513. else {
  72514. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  72515. image.src = url;
  72516. }
  72517. };
  72518. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  72519. var _this = this;
  72520. var updateVersion = function () {
  72521. // the version is not yet in the DB or we need to update it
  72522. _this._saveVersionIntoDBAsync(url, versionLoaded);
  72523. };
  72524. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  72525. };
  72526. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  72527. var _this = this;
  72528. if (this.isSupported && this.db) {
  72529. var version;
  72530. try {
  72531. var transaction = this.db.transaction(["versions"]);
  72532. transaction.oncomplete = function (event) {
  72533. if (version) {
  72534. // If the version in the JSON file is different from the version in DB
  72535. if (_this.manifestVersionFound !== version.data) {
  72536. _this.mustUpdateRessources = true;
  72537. updateInDBCallback();
  72538. }
  72539. else {
  72540. callback(version.data);
  72541. }
  72542. }
  72543. // version was not found in DB
  72544. else {
  72545. _this.mustUpdateRessources = true;
  72546. updateInDBCallback();
  72547. }
  72548. };
  72549. transaction.onabort = function (event) {
  72550. callback(-1);
  72551. };
  72552. var getRequest = transaction.objectStore("versions").get(url);
  72553. getRequest.onsuccess = function (event) {
  72554. version = (event.target).result;
  72555. };
  72556. getRequest.onerror = function (event) {
  72557. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  72558. callback(-1);
  72559. };
  72560. }
  72561. catch (ex) {
  72562. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  72563. callback(-1);
  72564. }
  72565. }
  72566. else {
  72567. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  72568. callback(-1);
  72569. }
  72570. };
  72571. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  72572. var _this = this;
  72573. if (this.isSupported && !this.hasReachedQuota && this.db) {
  72574. try {
  72575. // Open a transaction to the database
  72576. var transaction = this.db.transaction(["versions"], "readwrite");
  72577. // the transaction could abort because of a QuotaExceededError error
  72578. transaction.onabort = function (event) {
  72579. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  72580. var error = event.srcElement['error'];
  72581. if (error && error.name === "QuotaExceededError") {
  72582. _this.hasReachedQuota = true;
  72583. }
  72584. }
  72585. catch (ex) { }
  72586. callback(-1);
  72587. };
  72588. transaction.oncomplete = function (event) {
  72589. callback(_this.manifestVersionFound);
  72590. };
  72591. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  72592. // Put the scene into the database
  72593. var addRequest = transaction.objectStore("versions").put(newVersion);
  72594. addRequest.onsuccess = function (event) {
  72595. };
  72596. addRequest.onerror = function (event) {
  72597. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  72598. };
  72599. }
  72600. catch (ex) {
  72601. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  72602. callback(-1);
  72603. }
  72604. }
  72605. else {
  72606. callback(-1);
  72607. }
  72608. };
  72609. /**
  72610. * Loads a file from database
  72611. * @param url defines the URL to load from
  72612. * @param sceneLoaded defines a callback to call on success
  72613. * @param progressCallBack defines a callback to call when progress changed
  72614. * @param errorCallback defines a callback to call on error
  72615. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  72616. */
  72617. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  72618. var _this = this;
  72619. var completeUrl = Database._ReturnFullUrlLocation(url);
  72620. var saveAndLoadFile = function () {
  72621. // the scene is not yet in the DB, let's try to save it
  72622. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  72623. };
  72624. this._checkVersionFromDB(completeUrl, function (version) {
  72625. if (version !== -1) {
  72626. if (!_this.mustUpdateRessources) {
  72627. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  72628. }
  72629. else {
  72630. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  72631. }
  72632. }
  72633. else {
  72634. if (errorCallback) {
  72635. errorCallback();
  72636. }
  72637. }
  72638. });
  72639. };
  72640. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  72641. if (this.isSupported && this.db) {
  72642. var targetStore;
  72643. if (url.indexOf(".babylon") !== -1) {
  72644. targetStore = "scenes";
  72645. }
  72646. else {
  72647. targetStore = "textures";
  72648. }
  72649. var file;
  72650. var transaction = this.db.transaction([targetStore]);
  72651. transaction.oncomplete = function (event) {
  72652. if (file) {
  72653. callback(file.data);
  72654. }
  72655. // file was not found in DB
  72656. else {
  72657. notInDBCallback();
  72658. }
  72659. };
  72660. transaction.onabort = function (event) {
  72661. notInDBCallback();
  72662. };
  72663. var getRequest = transaction.objectStore(targetStore).get(url);
  72664. getRequest.onsuccess = function (event) {
  72665. file = (event.target).result;
  72666. };
  72667. getRequest.onerror = function (event) {
  72668. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  72669. notInDBCallback();
  72670. };
  72671. }
  72672. else {
  72673. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  72674. callback();
  72675. }
  72676. };
  72677. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  72678. var _this = this;
  72679. if (this.isSupported) {
  72680. var targetStore;
  72681. if (url.indexOf(".babylon") !== -1) {
  72682. targetStore = "scenes";
  72683. }
  72684. else {
  72685. targetStore = "textures";
  72686. }
  72687. // Create XHR
  72688. var xhr = new XMLHttpRequest();
  72689. var fileData;
  72690. xhr.open("GET", url + "?" + Date.now(), true);
  72691. if (useArrayBuffer) {
  72692. xhr.responseType = "arraybuffer";
  72693. }
  72694. if (progressCallback) {
  72695. xhr.onprogress = progressCallback;
  72696. }
  72697. xhr.addEventListener("load", function () {
  72698. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  72699. // Blob as response (XHR2)
  72700. //fileData = xhr.responseText;
  72701. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  72702. if (!_this.hasReachedQuota && _this.db) {
  72703. // Open a transaction to the database
  72704. var transaction = _this.db.transaction([targetStore], "readwrite");
  72705. // the transaction could abort because of a QuotaExceededError error
  72706. transaction.onabort = function (event) {
  72707. try {
  72708. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  72709. var error = event.srcElement['error'];
  72710. if (error && error.name === "QuotaExceededError") {
  72711. _this.hasReachedQuota = true;
  72712. }
  72713. }
  72714. catch (ex) { }
  72715. callback(fileData);
  72716. };
  72717. transaction.oncomplete = function (event) {
  72718. callback(fileData);
  72719. };
  72720. var newFile;
  72721. if (targetStore === "scenes") {
  72722. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  72723. }
  72724. else {
  72725. newFile = { textureUrl: url, data: fileData };
  72726. }
  72727. try {
  72728. // Put the scene into the database
  72729. var addRequest = transaction.objectStore(targetStore).put(newFile);
  72730. addRequest.onsuccess = function (event) {
  72731. };
  72732. addRequest.onerror = function (event) {
  72733. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  72734. };
  72735. }
  72736. catch (ex) {
  72737. callback(fileData);
  72738. }
  72739. }
  72740. else {
  72741. callback(fileData);
  72742. }
  72743. }
  72744. else {
  72745. if (xhr.status >= 400 && errorCallback) {
  72746. errorCallback(xhr);
  72747. }
  72748. else {
  72749. callback();
  72750. }
  72751. }
  72752. }, false);
  72753. xhr.addEventListener("error", function (event) {
  72754. BABYLON.Tools.Error("error on XHR request.");
  72755. callback();
  72756. }, false);
  72757. xhr.send();
  72758. }
  72759. else {
  72760. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  72761. callback();
  72762. }
  72763. };
  72764. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  72765. Database.IsUASupportingBlobStorage = true;
  72766. /** Gets a boolean indicating if Database storate is enabled */
  72767. Database.IDBStorageEnabled = true;
  72768. Database._ParseURL = function (url) {
  72769. var a = document.createElement('a');
  72770. a.href = url;
  72771. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  72772. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  72773. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  72774. return absLocation;
  72775. };
  72776. Database._ReturnFullUrlLocation = function (url) {
  72777. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  72778. return (Database._ParseURL(window.location.href) + url);
  72779. }
  72780. else {
  72781. return url;
  72782. }
  72783. };
  72784. return Database;
  72785. }());
  72786. BABYLON.Database = Database;
  72787. })(BABYLON || (BABYLON = {}));
  72788. //# sourceMappingURL=babylon.database.js.map
  72789. var BABYLON;
  72790. (function (BABYLON) {
  72791. var FresnelParameters = /** @class */ (function () {
  72792. function FresnelParameters() {
  72793. this._isEnabled = true;
  72794. this.leftColor = BABYLON.Color3.White();
  72795. this.rightColor = BABYLON.Color3.Black();
  72796. this.bias = 0;
  72797. this.power = 1;
  72798. }
  72799. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  72800. get: function () {
  72801. return this._isEnabled;
  72802. },
  72803. set: function (value) {
  72804. if (this._isEnabled === value) {
  72805. return;
  72806. }
  72807. this._isEnabled = value;
  72808. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  72809. },
  72810. enumerable: true,
  72811. configurable: true
  72812. });
  72813. FresnelParameters.prototype.clone = function () {
  72814. var newFresnelParameters = new FresnelParameters();
  72815. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  72816. return newFresnelParameters;
  72817. };
  72818. FresnelParameters.prototype.serialize = function () {
  72819. var serializationObject = {};
  72820. serializationObject.isEnabled = this.isEnabled;
  72821. serializationObject.leftColor = this.leftColor.asArray();
  72822. serializationObject.rightColor = this.rightColor.asArray();
  72823. serializationObject.bias = this.bias;
  72824. serializationObject.power = this.power;
  72825. return serializationObject;
  72826. };
  72827. FresnelParameters.Parse = function (parsedFresnelParameters) {
  72828. var fresnelParameters = new FresnelParameters();
  72829. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  72830. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  72831. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  72832. fresnelParameters.bias = parsedFresnelParameters.bias;
  72833. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  72834. return fresnelParameters;
  72835. };
  72836. return FresnelParameters;
  72837. }());
  72838. BABYLON.FresnelParameters = FresnelParameters;
  72839. })(BABYLON || (BABYLON = {}));
  72840. //# sourceMappingURL=babylon.fresnelParameters.js.map
  72841. var BABYLON;
  72842. (function (BABYLON) {
  72843. var MultiMaterial = /** @class */ (function (_super) {
  72844. __extends(MultiMaterial, _super);
  72845. function MultiMaterial(name, scene) {
  72846. var _this = _super.call(this, name, scene, true) || this;
  72847. scene.multiMaterials.push(_this);
  72848. _this.subMaterials = new Array();
  72849. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  72850. return _this;
  72851. }
  72852. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  72853. get: function () {
  72854. return this._subMaterials;
  72855. },
  72856. set: function (value) {
  72857. this._subMaterials = value;
  72858. this._hookArray(value);
  72859. },
  72860. enumerable: true,
  72861. configurable: true
  72862. });
  72863. MultiMaterial.prototype._hookArray = function (array) {
  72864. var _this = this;
  72865. var oldPush = array.push;
  72866. array.push = function () {
  72867. var items = [];
  72868. for (var _i = 0; _i < arguments.length; _i++) {
  72869. items[_i] = arguments[_i];
  72870. }
  72871. var result = oldPush.apply(array, items);
  72872. _this._markAllSubMeshesAsTexturesDirty();
  72873. return result;
  72874. };
  72875. var oldSplice = array.splice;
  72876. array.splice = function (index, deleteCount) {
  72877. var deleted = oldSplice.apply(array, [index, deleteCount]);
  72878. _this._markAllSubMeshesAsTexturesDirty();
  72879. return deleted;
  72880. };
  72881. };
  72882. // Properties
  72883. MultiMaterial.prototype.getSubMaterial = function (index) {
  72884. if (index < 0 || index >= this.subMaterials.length) {
  72885. return this.getScene().defaultMaterial;
  72886. }
  72887. return this.subMaterials[index];
  72888. };
  72889. MultiMaterial.prototype.getActiveTextures = function () {
  72890. var _a;
  72891. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  72892. if (subMaterial) {
  72893. return subMaterial.getActiveTextures();
  72894. }
  72895. else {
  72896. return [];
  72897. }
  72898. }));
  72899. };
  72900. // Methods
  72901. MultiMaterial.prototype.getClassName = function () {
  72902. return "MultiMaterial";
  72903. };
  72904. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  72905. for (var index = 0; index < this.subMaterials.length; index++) {
  72906. var subMaterial = this.subMaterials[index];
  72907. if (subMaterial) {
  72908. if (subMaterial.storeEffectOnSubMeshes) {
  72909. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  72910. return false;
  72911. }
  72912. continue;
  72913. }
  72914. if (!subMaterial.isReady(mesh)) {
  72915. return false;
  72916. }
  72917. }
  72918. }
  72919. return true;
  72920. };
  72921. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  72922. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  72923. for (var index = 0; index < this.subMaterials.length; index++) {
  72924. var subMaterial = null;
  72925. var current = this.subMaterials[index];
  72926. if (cloneChildren && current) {
  72927. subMaterial = current.clone(name + "-" + current.name);
  72928. }
  72929. else {
  72930. subMaterial = this.subMaterials[index];
  72931. }
  72932. newMultiMaterial.subMaterials.push(subMaterial);
  72933. }
  72934. return newMultiMaterial;
  72935. };
  72936. MultiMaterial.prototype.serialize = function () {
  72937. var serializationObject = {};
  72938. serializationObject.name = this.name;
  72939. serializationObject.id = this.id;
  72940. if (BABYLON.Tags) {
  72941. serializationObject.tags = BABYLON.Tags.GetTags(this);
  72942. }
  72943. serializationObject.materials = [];
  72944. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  72945. var subMat = this.subMaterials[matIndex];
  72946. if (subMat) {
  72947. serializationObject.materials.push(subMat.id);
  72948. }
  72949. else {
  72950. serializationObject.materials.push(null);
  72951. }
  72952. }
  72953. return serializationObject;
  72954. };
  72955. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  72956. var scene = this.getScene();
  72957. if (!scene) {
  72958. return;
  72959. }
  72960. var index = scene.multiMaterials.indexOf(this);
  72961. if (index >= 0) {
  72962. scene.multiMaterials.splice(index, 1);
  72963. }
  72964. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  72965. };
  72966. return MultiMaterial;
  72967. }(BABYLON.Material));
  72968. BABYLON.MultiMaterial = MultiMaterial;
  72969. })(BABYLON || (BABYLON = {}));
  72970. //# sourceMappingURL=babylon.multiMaterial.js.map
  72971. var BABYLON;
  72972. (function (BABYLON) {
  72973. var FreeCameraTouchInput = /** @class */ (function () {
  72974. function FreeCameraTouchInput() {
  72975. this._offsetX = null;
  72976. this._offsetY = null;
  72977. this._pointerPressed = new Array();
  72978. this.touchAngularSensibility = 200000.0;
  72979. this.touchMoveSensibility = 250.0;
  72980. }
  72981. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  72982. var _this = this;
  72983. var previousPosition = null;
  72984. if (this._pointerInput === undefined) {
  72985. this._onLostFocus = function (evt) {
  72986. _this._offsetX = null;
  72987. _this._offsetY = null;
  72988. };
  72989. this._pointerInput = function (p, s) {
  72990. var evt = p.event;
  72991. if (evt.pointerType === "mouse") {
  72992. return;
  72993. }
  72994. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  72995. if (!noPreventDefault) {
  72996. evt.preventDefault();
  72997. }
  72998. _this._pointerPressed.push(evt.pointerId);
  72999. if (_this._pointerPressed.length !== 1) {
  73000. return;
  73001. }
  73002. previousPosition = {
  73003. x: evt.clientX,
  73004. y: evt.clientY
  73005. };
  73006. }
  73007. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  73008. if (!noPreventDefault) {
  73009. evt.preventDefault();
  73010. }
  73011. var index = _this._pointerPressed.indexOf(evt.pointerId);
  73012. if (index === -1) {
  73013. return;
  73014. }
  73015. _this._pointerPressed.splice(index, 1);
  73016. if (index != 0) {
  73017. return;
  73018. }
  73019. previousPosition = null;
  73020. _this._offsetX = null;
  73021. _this._offsetY = null;
  73022. }
  73023. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  73024. if (!noPreventDefault) {
  73025. evt.preventDefault();
  73026. }
  73027. if (!previousPosition) {
  73028. return;
  73029. }
  73030. var index = _this._pointerPressed.indexOf(evt.pointerId);
  73031. if (index != 0) {
  73032. return;
  73033. }
  73034. _this._offsetX = evt.clientX - previousPosition.x;
  73035. _this._offsetY = -(evt.clientY - previousPosition.y);
  73036. }
  73037. };
  73038. }
  73039. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  73040. if (this._onLostFocus) {
  73041. element.addEventListener("blur", this._onLostFocus);
  73042. }
  73043. };
  73044. FreeCameraTouchInput.prototype.detachControl = function (element) {
  73045. if (this._pointerInput && element) {
  73046. if (this._observer) {
  73047. this.camera.getScene().onPointerObservable.remove(this._observer);
  73048. this._observer = null;
  73049. }
  73050. if (this._onLostFocus) {
  73051. element.removeEventListener("blur", this._onLostFocus);
  73052. this._onLostFocus = null;
  73053. }
  73054. this._pointerPressed = [];
  73055. this._offsetX = null;
  73056. this._offsetY = null;
  73057. }
  73058. };
  73059. FreeCameraTouchInput.prototype.checkInputs = function () {
  73060. if (this._offsetX && this._offsetY) {
  73061. var camera = this.camera;
  73062. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  73063. if (this._pointerPressed.length > 1) {
  73064. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  73065. }
  73066. else {
  73067. var speed = camera._computeLocalCameraSpeed();
  73068. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  73069. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  73070. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  73071. }
  73072. }
  73073. };
  73074. FreeCameraTouchInput.prototype.getClassName = function () {
  73075. return "FreeCameraTouchInput";
  73076. };
  73077. FreeCameraTouchInput.prototype.getSimpleName = function () {
  73078. return "touch";
  73079. };
  73080. __decorate([
  73081. BABYLON.serialize()
  73082. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  73083. __decorate([
  73084. BABYLON.serialize()
  73085. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  73086. return FreeCameraTouchInput;
  73087. }());
  73088. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  73089. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  73090. })(BABYLON || (BABYLON = {}));
  73091. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  73092. var BABYLON;
  73093. (function (BABYLON) {
  73094. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  73095. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  73096. });
  73097. // We're mainly based on the logic defined into the FreeCamera code
  73098. var TouchCamera = /** @class */ (function (_super) {
  73099. __extends(TouchCamera, _super);
  73100. //-- end properties for backward compatibility for inputs
  73101. function TouchCamera(name, position, scene) {
  73102. var _this = _super.call(this, name, position, scene) || this;
  73103. _this.inputs.addTouch();
  73104. _this._setupInputs();
  73105. return _this;
  73106. }
  73107. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  73108. //-- Begin properties for backward compatibility for inputs
  73109. get: function () {
  73110. var touch = this.inputs.attached["touch"];
  73111. if (touch)
  73112. return touch.touchAngularSensibility;
  73113. return 0;
  73114. },
  73115. set: function (value) {
  73116. var touch = this.inputs.attached["touch"];
  73117. if (touch)
  73118. touch.touchAngularSensibility = value;
  73119. },
  73120. enumerable: true,
  73121. configurable: true
  73122. });
  73123. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  73124. get: function () {
  73125. var touch = this.inputs.attached["touch"];
  73126. if (touch)
  73127. return touch.touchMoveSensibility;
  73128. return 0;
  73129. },
  73130. set: function (value) {
  73131. var touch = this.inputs.attached["touch"];
  73132. if (touch)
  73133. touch.touchMoveSensibility = value;
  73134. },
  73135. enumerable: true,
  73136. configurable: true
  73137. });
  73138. TouchCamera.prototype.getClassName = function () {
  73139. return "TouchCamera";
  73140. };
  73141. /** @hidden */
  73142. TouchCamera.prototype._setupInputs = function () {
  73143. var mouse = this.inputs.attached["mouse"];
  73144. if (mouse) {
  73145. mouse.touchEnabled = false;
  73146. }
  73147. };
  73148. return TouchCamera;
  73149. }(BABYLON.FreeCamera));
  73150. BABYLON.TouchCamera = TouchCamera;
  73151. })(BABYLON || (BABYLON = {}));
  73152. //# sourceMappingURL=babylon.touchCamera.js.map
  73153. var BABYLON;
  73154. (function (BABYLON) {
  73155. var ProceduralTexture = /** @class */ (function (_super) {
  73156. __extends(ProceduralTexture, _super);
  73157. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  73158. if (fallbackTexture === void 0) { fallbackTexture = null; }
  73159. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73160. if (isCube === void 0) { isCube = false; }
  73161. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  73162. _this.isCube = isCube;
  73163. _this.isEnabled = true;
  73164. _this._currentRefreshId = -1;
  73165. _this._refreshRate = 1;
  73166. _this._vertexBuffers = {};
  73167. _this._uniforms = new Array();
  73168. _this._samplers = new Array();
  73169. /** @hidden */
  73170. _this._textures = {};
  73171. _this._floats = {};
  73172. _this._ints = {};
  73173. _this._floatsArrays = {};
  73174. _this._colors3 = {};
  73175. _this._colors4 = {};
  73176. _this._vectors2 = {};
  73177. _this._vectors3 = {};
  73178. _this._matrices = {};
  73179. _this._fallbackTextureUsed = false;
  73180. _this._cachedDefines = "";
  73181. scene = _this.getScene();
  73182. scene.proceduralTextures.push(_this);
  73183. _this._engine = scene.getEngine();
  73184. _this.name = name;
  73185. _this.isRenderTarget = true;
  73186. _this._size = size;
  73187. _this._generateMipMaps = generateMipMaps;
  73188. _this.setFragment(fragment);
  73189. _this._fallbackTexture = fallbackTexture;
  73190. if (isCube) {
  73191. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  73192. _this.setFloat("face", 0);
  73193. }
  73194. else {
  73195. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  73196. }
  73197. // VBO
  73198. var vertices = [];
  73199. vertices.push(1, 1);
  73200. vertices.push(-1, 1);
  73201. vertices.push(-1, -1);
  73202. vertices.push(1, -1);
  73203. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  73204. _this._createIndexBuffer();
  73205. return _this;
  73206. }
  73207. ProceduralTexture.prototype._createIndexBuffer = function () {
  73208. var engine = this._engine;
  73209. // Indices
  73210. var indices = [];
  73211. indices.push(0);
  73212. indices.push(1);
  73213. indices.push(2);
  73214. indices.push(0);
  73215. indices.push(2);
  73216. indices.push(3);
  73217. this._indexBuffer = engine.createIndexBuffer(indices);
  73218. };
  73219. /** @hidden */
  73220. ProceduralTexture.prototype._rebuild = function () {
  73221. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73222. if (vb) {
  73223. vb._rebuild();
  73224. }
  73225. this._createIndexBuffer();
  73226. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  73227. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  73228. }
  73229. };
  73230. ProceduralTexture.prototype.reset = function () {
  73231. if (this._effect === undefined) {
  73232. return;
  73233. }
  73234. var engine = this._engine;
  73235. engine._releaseEffect(this._effect);
  73236. };
  73237. ProceduralTexture.prototype._getDefines = function () {
  73238. return "";
  73239. };
  73240. ProceduralTexture.prototype.isReady = function () {
  73241. var _this = this;
  73242. var engine = this._engine;
  73243. var shaders;
  73244. if (!this._fragment) {
  73245. return false;
  73246. }
  73247. if (this._fallbackTextureUsed) {
  73248. return true;
  73249. }
  73250. var defines = this._getDefines();
  73251. if (this._effect && defines === this._cachedDefines && this._effect.isReady()) {
  73252. return true;
  73253. }
  73254. if (this._fragment.fragmentElement !== undefined) {
  73255. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  73256. }
  73257. else {
  73258. shaders = { vertex: "procedural", fragment: this._fragment };
  73259. }
  73260. this._cachedDefines = defines;
  73261. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, defines, undefined, undefined, function () {
  73262. _this.releaseInternalTexture();
  73263. if (_this._fallbackTexture) {
  73264. _this._texture = _this._fallbackTexture._texture;
  73265. if (_this._texture) {
  73266. _this._texture.incrementReferences();
  73267. }
  73268. }
  73269. _this._fallbackTextureUsed = true;
  73270. });
  73271. return this._effect.isReady();
  73272. };
  73273. ProceduralTexture.prototype.resetRefreshCounter = function () {
  73274. this._currentRefreshId = -1;
  73275. };
  73276. ProceduralTexture.prototype.setFragment = function (fragment) {
  73277. this._fragment = fragment;
  73278. };
  73279. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  73280. get: function () {
  73281. return this._refreshRate;
  73282. },
  73283. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  73284. set: function (value) {
  73285. this._refreshRate = value;
  73286. this.resetRefreshCounter();
  73287. },
  73288. enumerable: true,
  73289. configurable: true
  73290. });
  73291. /** @hidden */
  73292. ProceduralTexture.prototype._shouldRender = function () {
  73293. if (!this.isEnabled || !this.isReady() || !this._texture) {
  73294. return false;
  73295. }
  73296. if (this._fallbackTextureUsed) {
  73297. return false;
  73298. }
  73299. if (this._currentRefreshId === -1) { // At least render once
  73300. this._currentRefreshId = 1;
  73301. return true;
  73302. }
  73303. if (this.refreshRate === this._currentRefreshId) {
  73304. this._currentRefreshId = 1;
  73305. return true;
  73306. }
  73307. this._currentRefreshId++;
  73308. return false;
  73309. };
  73310. ProceduralTexture.prototype.getRenderSize = function () {
  73311. return this._size;
  73312. };
  73313. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  73314. if (this._fallbackTextureUsed) {
  73315. return;
  73316. }
  73317. this.releaseInternalTexture();
  73318. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  73319. // Update properties
  73320. this._size = size;
  73321. this._generateMipMaps = generateMipMaps;
  73322. };
  73323. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  73324. if (this._uniforms.indexOf(uniformName) === -1) {
  73325. this._uniforms.push(uniformName);
  73326. }
  73327. };
  73328. ProceduralTexture.prototype.setTexture = function (name, texture) {
  73329. if (this._samplers.indexOf(name) === -1) {
  73330. this._samplers.push(name);
  73331. }
  73332. this._textures[name] = texture;
  73333. return this;
  73334. };
  73335. ProceduralTexture.prototype.setFloat = function (name, value) {
  73336. this._checkUniform(name);
  73337. this._floats[name] = value;
  73338. return this;
  73339. };
  73340. /**
  73341. * Set the value of an uniform to an integer value
  73342. * @param name defines the name of the uniform
  73343. * @param value defines the value to set
  73344. * @returns the current procedural texture
  73345. */
  73346. ProceduralTexture.prototype.setInt = function (name, value) {
  73347. this._checkUniform(name);
  73348. this._ints[name] = value;
  73349. return this;
  73350. };
  73351. ProceduralTexture.prototype.setFloats = function (name, value) {
  73352. this._checkUniform(name);
  73353. this._floatsArrays[name] = value;
  73354. return this;
  73355. };
  73356. ProceduralTexture.prototype.setColor3 = function (name, value) {
  73357. this._checkUniform(name);
  73358. this._colors3[name] = value;
  73359. return this;
  73360. };
  73361. ProceduralTexture.prototype.setColor4 = function (name, value) {
  73362. this._checkUniform(name);
  73363. this._colors4[name] = value;
  73364. return this;
  73365. };
  73366. ProceduralTexture.prototype.setVector2 = function (name, value) {
  73367. this._checkUniform(name);
  73368. this._vectors2[name] = value;
  73369. return this;
  73370. };
  73371. ProceduralTexture.prototype.setVector3 = function (name, value) {
  73372. this._checkUniform(name);
  73373. this._vectors3[name] = value;
  73374. return this;
  73375. };
  73376. ProceduralTexture.prototype.setMatrix = function (name, value) {
  73377. this._checkUniform(name);
  73378. this._matrices[name] = value;
  73379. return this;
  73380. };
  73381. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  73382. var scene = this.getScene();
  73383. if (!scene) {
  73384. return;
  73385. }
  73386. var engine = this._engine;
  73387. // Render
  73388. engine.enableEffect(this._effect);
  73389. engine.setState(false);
  73390. // Texture
  73391. for (var name in this._textures) {
  73392. this._effect.setTexture(name, this._textures[name]);
  73393. }
  73394. // Float
  73395. for (name in this._ints) {
  73396. this._effect.setInt(name, this._ints[name]);
  73397. }
  73398. // Float
  73399. for (name in this._floats) {
  73400. this._effect.setFloat(name, this._floats[name]);
  73401. }
  73402. // Floats
  73403. for (name in this._floatsArrays) {
  73404. this._effect.setArray(name, this._floatsArrays[name]);
  73405. }
  73406. // Color3
  73407. for (name in this._colors3) {
  73408. this._effect.setColor3(name, this._colors3[name]);
  73409. }
  73410. // Color4
  73411. for (name in this._colors4) {
  73412. var color = this._colors4[name];
  73413. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  73414. }
  73415. // Vector2
  73416. for (name in this._vectors2) {
  73417. this._effect.setVector2(name, this._vectors2[name]);
  73418. }
  73419. // Vector3
  73420. for (name in this._vectors3) {
  73421. this._effect.setVector3(name, this._vectors3[name]);
  73422. }
  73423. // Matrix
  73424. for (name in this._matrices) {
  73425. this._effect.setMatrix(name, this._matrices[name]);
  73426. }
  73427. if (!this._texture) {
  73428. return;
  73429. }
  73430. if (this.isCube) {
  73431. for (var face = 0; face < 6; face++) {
  73432. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  73433. // VBOs
  73434. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  73435. this._effect.setFloat("face", face);
  73436. // Clear
  73437. engine.clear(scene.clearColor, true, true, true);
  73438. // Draw order
  73439. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  73440. // Mipmaps
  73441. if (face === 5) {
  73442. engine.generateMipMapsForCubemap(this._texture);
  73443. }
  73444. }
  73445. }
  73446. else {
  73447. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  73448. // VBOs
  73449. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  73450. // Clear
  73451. engine.clear(scene.clearColor, true, true, true);
  73452. // Draw order
  73453. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  73454. }
  73455. // Unbind
  73456. engine.unBindFramebuffer(this._texture, this.isCube);
  73457. if (this.onGenerated) {
  73458. this.onGenerated();
  73459. }
  73460. };
  73461. ProceduralTexture.prototype.clone = function () {
  73462. var textureSize = this.getSize();
  73463. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  73464. // Base texture
  73465. newTexture.hasAlpha = this.hasAlpha;
  73466. newTexture.level = this.level;
  73467. // RenderTarget Texture
  73468. newTexture.coordinatesMode = this.coordinatesMode;
  73469. return newTexture;
  73470. };
  73471. ProceduralTexture.prototype.dispose = function () {
  73472. var scene = this.getScene();
  73473. if (!scene) {
  73474. return;
  73475. }
  73476. var index = scene.proceduralTextures.indexOf(this);
  73477. if (index >= 0) {
  73478. scene.proceduralTextures.splice(index, 1);
  73479. }
  73480. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73481. if (vertexBuffer) {
  73482. vertexBuffer.dispose();
  73483. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  73484. }
  73485. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  73486. this._indexBuffer = null;
  73487. }
  73488. _super.prototype.dispose.call(this);
  73489. };
  73490. __decorate([
  73491. BABYLON.serialize()
  73492. ], ProceduralTexture.prototype, "_size", void 0);
  73493. __decorate([
  73494. BABYLON.serialize()
  73495. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  73496. __decorate([
  73497. BABYLON.serialize()
  73498. ], ProceduralTexture.prototype, "isEnabled", void 0);
  73499. __decorate([
  73500. BABYLON.serialize()
  73501. ], ProceduralTexture.prototype, "refreshRate", null);
  73502. return ProceduralTexture;
  73503. }(BABYLON.Texture));
  73504. BABYLON.ProceduralTexture = ProceduralTexture;
  73505. })(BABYLON || (BABYLON = {}));
  73506. //# sourceMappingURL=babylon.proceduralTexture.js.map
  73507. var BABYLON;
  73508. (function (BABYLON) {
  73509. var CustomProceduralTexture = /** @class */ (function (_super) {
  73510. __extends(CustomProceduralTexture, _super);
  73511. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  73512. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  73513. _this._animate = true;
  73514. _this._time = 0;
  73515. _this._texturePath = texturePath;
  73516. //Try to load json
  73517. _this.loadJson(texturePath);
  73518. _this.refreshRate = 1;
  73519. return _this;
  73520. }
  73521. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  73522. var _this = this;
  73523. var noConfigFile = function () {
  73524. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  73525. try {
  73526. _this.setFragment(_this._texturePath);
  73527. }
  73528. catch (ex) {
  73529. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  73530. }
  73531. };
  73532. var configFileUrl = jsonUrl + "/config.json";
  73533. var xhr = new XMLHttpRequest();
  73534. xhr.open("GET", configFileUrl, true);
  73535. xhr.addEventListener("load", function () {
  73536. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  73537. try {
  73538. _this._config = JSON.parse(xhr.response);
  73539. _this.updateShaderUniforms();
  73540. _this.updateTextures();
  73541. _this.setFragment(_this._texturePath + "/custom");
  73542. _this._animate = _this._config.animate;
  73543. _this.refreshRate = _this._config.refreshrate;
  73544. }
  73545. catch (ex) {
  73546. noConfigFile();
  73547. }
  73548. }
  73549. else {
  73550. noConfigFile();
  73551. }
  73552. }, false);
  73553. xhr.addEventListener("error", function () {
  73554. noConfigFile();
  73555. }, false);
  73556. try {
  73557. xhr.send();
  73558. }
  73559. catch (ex) {
  73560. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  73561. }
  73562. };
  73563. CustomProceduralTexture.prototype.isReady = function () {
  73564. if (!_super.prototype.isReady.call(this)) {
  73565. return false;
  73566. }
  73567. for (var name in this._textures) {
  73568. var texture = this._textures[name];
  73569. if (!texture.isReady()) {
  73570. return false;
  73571. }
  73572. }
  73573. return true;
  73574. };
  73575. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  73576. var scene = this.getScene();
  73577. if (this._animate && scene) {
  73578. this._time += scene.getAnimationRatio() * 0.03;
  73579. this.updateShaderUniforms();
  73580. }
  73581. _super.prototype.render.call(this, useCameraPostProcess);
  73582. };
  73583. CustomProceduralTexture.prototype.updateTextures = function () {
  73584. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  73585. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  73586. }
  73587. };
  73588. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  73589. if (this._config) {
  73590. for (var j = 0; j < this._config.uniforms.length; j++) {
  73591. var uniform = this._config.uniforms[j];
  73592. switch (uniform.type) {
  73593. case "float":
  73594. this.setFloat(uniform.name, uniform.value);
  73595. break;
  73596. case "color3":
  73597. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  73598. break;
  73599. case "color4":
  73600. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  73601. break;
  73602. case "vector2":
  73603. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  73604. break;
  73605. case "vector3":
  73606. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  73607. break;
  73608. }
  73609. }
  73610. }
  73611. this.setFloat("time", this._time);
  73612. };
  73613. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  73614. get: function () {
  73615. return this._animate;
  73616. },
  73617. set: function (value) {
  73618. this._animate = value;
  73619. },
  73620. enumerable: true,
  73621. configurable: true
  73622. });
  73623. return CustomProceduralTexture;
  73624. }(BABYLON.ProceduralTexture));
  73625. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  73626. })(BABYLON || (BABYLON = {}));
  73627. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  73628. var BABYLON;
  73629. (function (BABYLON) {
  73630. var FreeCameraGamepadInput = /** @class */ (function () {
  73631. function FreeCameraGamepadInput() {
  73632. this.gamepadAngularSensibility = 200;
  73633. this.gamepadMoveSensibility = 40;
  73634. // private members
  73635. this._cameraTransform = BABYLON.Matrix.Identity();
  73636. this._deltaTransform = BABYLON.Vector3.Zero();
  73637. this._vector3 = BABYLON.Vector3.Zero();
  73638. this._vector2 = BABYLON.Vector2.Zero();
  73639. }
  73640. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  73641. var _this = this;
  73642. var manager = this.camera.getScene().gamepadManager;
  73643. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  73644. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  73645. // prioritize XBOX gamepads.
  73646. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  73647. _this.gamepad = gamepad;
  73648. }
  73649. }
  73650. });
  73651. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  73652. if (_this.gamepad === gamepad) {
  73653. _this.gamepad = null;
  73654. }
  73655. });
  73656. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  73657. };
  73658. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  73659. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  73660. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  73661. this.gamepad = null;
  73662. };
  73663. FreeCameraGamepadInput.prototype.checkInputs = function () {
  73664. if (this.gamepad && this.gamepad.leftStick) {
  73665. var camera = this.camera;
  73666. var LSValues = this.gamepad.leftStick;
  73667. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  73668. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  73669. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  73670. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  73671. var RSValues = this.gamepad.rightStick;
  73672. if (RSValues) {
  73673. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  73674. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  73675. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  73676. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  73677. }
  73678. else {
  73679. RSValues = { x: 0, y: 0 };
  73680. }
  73681. if (!camera.rotationQuaternion) {
  73682. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  73683. }
  73684. else {
  73685. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  73686. }
  73687. var speed = camera._computeLocalCameraSpeed() * 50.0;
  73688. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  73689. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  73690. camera.cameraDirection.addInPlace(this._deltaTransform);
  73691. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  73692. camera.cameraRotation.addInPlace(this._vector2);
  73693. }
  73694. };
  73695. FreeCameraGamepadInput.prototype.getClassName = function () {
  73696. return "FreeCameraGamepadInput";
  73697. };
  73698. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  73699. return "gamepad";
  73700. };
  73701. __decorate([
  73702. BABYLON.serialize()
  73703. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  73704. __decorate([
  73705. BABYLON.serialize()
  73706. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  73707. return FreeCameraGamepadInput;
  73708. }());
  73709. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  73710. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  73711. })(BABYLON || (BABYLON = {}));
  73712. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  73713. var BABYLON;
  73714. (function (BABYLON) {
  73715. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  73716. function ArcRotateCameraGamepadInput() {
  73717. this.gamepadRotationSensibility = 80;
  73718. this.gamepadMoveSensibility = 40;
  73719. }
  73720. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  73721. var _this = this;
  73722. var manager = this.camera.getScene().gamepadManager;
  73723. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  73724. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  73725. // prioritize XBOX gamepads.
  73726. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  73727. _this.gamepad = gamepad;
  73728. }
  73729. }
  73730. });
  73731. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  73732. if (_this.gamepad === gamepad) {
  73733. _this.gamepad = null;
  73734. }
  73735. });
  73736. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  73737. };
  73738. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  73739. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  73740. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  73741. this.gamepad = null;
  73742. };
  73743. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  73744. if (this.gamepad) {
  73745. var camera = this.camera;
  73746. var RSValues = this.gamepad.rightStick;
  73747. if (RSValues) {
  73748. if (RSValues.x != 0) {
  73749. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  73750. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  73751. camera.inertialAlphaOffset += normalizedRX;
  73752. }
  73753. }
  73754. if (RSValues.y != 0) {
  73755. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  73756. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  73757. camera.inertialBetaOffset += normalizedRY;
  73758. }
  73759. }
  73760. }
  73761. var LSValues = this.gamepad.leftStick;
  73762. if (LSValues && LSValues.y != 0) {
  73763. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  73764. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  73765. this.camera.inertialRadiusOffset -= normalizedLY;
  73766. }
  73767. }
  73768. }
  73769. };
  73770. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  73771. return "ArcRotateCameraGamepadInput";
  73772. };
  73773. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  73774. return "gamepad";
  73775. };
  73776. __decorate([
  73777. BABYLON.serialize()
  73778. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  73779. __decorate([
  73780. BABYLON.serialize()
  73781. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  73782. return ArcRotateCameraGamepadInput;
  73783. }());
  73784. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  73785. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  73786. })(BABYLON || (BABYLON = {}));
  73787. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  73788. var BABYLON;
  73789. (function (BABYLON) {
  73790. var GamepadManager = /** @class */ (function () {
  73791. function GamepadManager(_scene) {
  73792. var _this = this;
  73793. this._scene = _scene;
  73794. this._babylonGamepads = [];
  73795. this._oneGamepadConnected = false;
  73796. /** @hidden */
  73797. this._isMonitoring = false;
  73798. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  73799. if (!BABYLON.Tools.IsWindowObjectExist()) {
  73800. this._gamepadEventSupported = false;
  73801. }
  73802. else {
  73803. this._gamepadEventSupported = 'GamepadEvent' in window;
  73804. this._gamepadSupport = (navigator.getGamepads ||
  73805. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  73806. }
  73807. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  73808. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  73809. for (var i in _this._babylonGamepads) {
  73810. var gamepad = _this._babylonGamepads[i];
  73811. if (gamepad && gamepad._isConnected) {
  73812. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  73813. }
  73814. }
  73815. });
  73816. this._onGamepadConnectedEvent = function (evt) {
  73817. var gamepad = evt.gamepad;
  73818. if (gamepad.index in _this._babylonGamepads) {
  73819. if (_this._babylonGamepads[gamepad.index].isConnected) {
  73820. return;
  73821. }
  73822. }
  73823. var newGamepad;
  73824. if (_this._babylonGamepads[gamepad.index]) {
  73825. newGamepad = _this._babylonGamepads[gamepad.index];
  73826. newGamepad.browserGamepad = gamepad;
  73827. newGamepad._isConnected = true;
  73828. }
  73829. else {
  73830. newGamepad = _this._addNewGamepad(gamepad);
  73831. }
  73832. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  73833. _this._startMonitoringGamepads();
  73834. };
  73835. this._onGamepadDisconnectedEvent = function (evt) {
  73836. var gamepad = evt.gamepad;
  73837. // Remove the gamepad from the list of gamepads to monitor.
  73838. for (var i in _this._babylonGamepads) {
  73839. if (_this._babylonGamepads[i].index === gamepad.index) {
  73840. var disconnectedGamepad = _this._babylonGamepads[i];
  73841. disconnectedGamepad._isConnected = false;
  73842. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  73843. break;
  73844. }
  73845. }
  73846. };
  73847. if (this._gamepadSupport) {
  73848. //first add already-connected gamepads
  73849. this._updateGamepadObjects();
  73850. if (this._babylonGamepads.length) {
  73851. this._startMonitoringGamepads();
  73852. }
  73853. // Checking if the gamepad connected event is supported (like in Firefox)
  73854. if (this._gamepadEventSupported) {
  73855. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  73856. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  73857. }
  73858. else {
  73859. this._startMonitoringGamepads();
  73860. }
  73861. }
  73862. }
  73863. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  73864. get: function () {
  73865. return this._babylonGamepads;
  73866. },
  73867. enumerable: true,
  73868. configurable: true
  73869. });
  73870. GamepadManager.prototype.getGamepadByType = function (type) {
  73871. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  73872. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  73873. var gamepad = _a[_i];
  73874. if (gamepad && gamepad.type === type) {
  73875. return gamepad;
  73876. }
  73877. }
  73878. return null;
  73879. };
  73880. GamepadManager.prototype.dispose = function () {
  73881. if (this._gamepadEventSupported) {
  73882. if (this._onGamepadConnectedEvent) {
  73883. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  73884. }
  73885. if (this._onGamepadDisconnectedEvent) {
  73886. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  73887. }
  73888. this._onGamepadConnectedEvent = null;
  73889. this._onGamepadDisconnectedEvent = null;
  73890. }
  73891. this._babylonGamepads.forEach(function (gamepad) {
  73892. gamepad.dispose();
  73893. });
  73894. this.onGamepadConnectedObservable.clear();
  73895. this.onGamepadDisconnectedObservable.clear();
  73896. this._oneGamepadConnected = false;
  73897. this._stopMonitoringGamepads();
  73898. this._babylonGamepads = [];
  73899. };
  73900. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  73901. if (!this._oneGamepadConnected) {
  73902. this._oneGamepadConnected = true;
  73903. }
  73904. var newGamepad;
  73905. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  73906. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  73907. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  73908. }
  73909. // if pose is supported, use the (WebVR) pose enabled controller
  73910. else if (gamepad.pose) {
  73911. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  73912. }
  73913. else {
  73914. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  73915. }
  73916. this._babylonGamepads[newGamepad.index] = newGamepad;
  73917. return newGamepad;
  73918. };
  73919. GamepadManager.prototype._startMonitoringGamepads = function () {
  73920. if (!this._isMonitoring) {
  73921. this._isMonitoring = true;
  73922. //back-comp
  73923. if (!this._scene) {
  73924. this._checkGamepadsStatus();
  73925. }
  73926. }
  73927. };
  73928. GamepadManager.prototype._stopMonitoringGamepads = function () {
  73929. this._isMonitoring = false;
  73930. };
  73931. /** @hidden */
  73932. GamepadManager.prototype._checkGamepadsStatus = function () {
  73933. var _this = this;
  73934. // Hack to be compatible Chrome
  73935. this._updateGamepadObjects();
  73936. for (var i in this._babylonGamepads) {
  73937. var gamepad = this._babylonGamepads[i];
  73938. if (!gamepad || !gamepad.isConnected) {
  73939. continue;
  73940. }
  73941. gamepad.update();
  73942. }
  73943. if (this._isMonitoring && !this._scene) {
  73944. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  73945. }
  73946. };
  73947. // This function is called only on Chrome, which does not properly support
  73948. // connection/disconnection events and forces you to recopy again the gamepad object
  73949. GamepadManager.prototype._updateGamepadObjects = function () {
  73950. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  73951. for (var i = 0; i < gamepads.length; i++) {
  73952. var gamepad = gamepads[i];
  73953. if (gamepad) {
  73954. if (!this._babylonGamepads[gamepad.index]) {
  73955. var newGamepad = this._addNewGamepad(gamepad);
  73956. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  73957. }
  73958. else {
  73959. // Forced to copy again this object for Chrome for unknown reason
  73960. this._babylonGamepads[i].browserGamepad = gamepad;
  73961. if (!this._babylonGamepads[i].isConnected) {
  73962. this._babylonGamepads[i]._isConnected = true;
  73963. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  73964. }
  73965. }
  73966. }
  73967. }
  73968. };
  73969. return GamepadManager;
  73970. }());
  73971. BABYLON.GamepadManager = GamepadManager;
  73972. })(BABYLON || (BABYLON = {}));
  73973. //# sourceMappingURL=babylon.gamepadManager.js.map
  73974. var BABYLON;
  73975. (function (BABYLON) {
  73976. var StickValues = /** @class */ (function () {
  73977. function StickValues(x, y) {
  73978. this.x = x;
  73979. this.y = y;
  73980. }
  73981. return StickValues;
  73982. }());
  73983. BABYLON.StickValues = StickValues;
  73984. var Gamepad = /** @class */ (function () {
  73985. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  73986. if (leftStickX === void 0) { leftStickX = 0; }
  73987. if (leftStickY === void 0) { leftStickY = 1; }
  73988. if (rightStickX === void 0) { rightStickX = 2; }
  73989. if (rightStickY === void 0) { rightStickY = 3; }
  73990. this.id = id;
  73991. this.index = index;
  73992. this.browserGamepad = browserGamepad;
  73993. this._leftStick = { x: 0, y: 0 };
  73994. this._rightStick = { x: 0, y: 0 };
  73995. /** @hidden */
  73996. this._isConnected = true;
  73997. this._invertLeftStickY = false;
  73998. this.type = Gamepad.GAMEPAD;
  73999. this._leftStickAxisX = leftStickX;
  74000. this._leftStickAxisY = leftStickY;
  74001. this._rightStickAxisX = rightStickX;
  74002. this._rightStickAxisY = rightStickY;
  74003. if (this.browserGamepad.axes.length >= 2) {
  74004. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  74005. }
  74006. if (this.browserGamepad.axes.length >= 4) {
  74007. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  74008. }
  74009. }
  74010. Object.defineProperty(Gamepad.prototype, "isConnected", {
  74011. get: function () {
  74012. return this._isConnected;
  74013. },
  74014. enumerable: true,
  74015. configurable: true
  74016. });
  74017. Gamepad.prototype.onleftstickchanged = function (callback) {
  74018. this._onleftstickchanged = callback;
  74019. };
  74020. Gamepad.prototype.onrightstickchanged = function (callback) {
  74021. this._onrightstickchanged = callback;
  74022. };
  74023. Object.defineProperty(Gamepad.prototype, "leftStick", {
  74024. get: function () {
  74025. return this._leftStick;
  74026. },
  74027. set: function (newValues) {
  74028. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  74029. this._onleftstickchanged(newValues);
  74030. }
  74031. this._leftStick = newValues;
  74032. },
  74033. enumerable: true,
  74034. configurable: true
  74035. });
  74036. Object.defineProperty(Gamepad.prototype, "rightStick", {
  74037. get: function () {
  74038. return this._rightStick;
  74039. },
  74040. set: function (newValues) {
  74041. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  74042. this._onrightstickchanged(newValues);
  74043. }
  74044. this._rightStick = newValues;
  74045. },
  74046. enumerable: true,
  74047. configurable: true
  74048. });
  74049. Gamepad.prototype.update = function () {
  74050. if (this._leftStick) {
  74051. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  74052. if (this._invertLeftStickY) {
  74053. this.leftStick.y *= -1;
  74054. }
  74055. }
  74056. if (this._rightStick) {
  74057. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  74058. }
  74059. };
  74060. Gamepad.prototype.dispose = function () {
  74061. };
  74062. Gamepad.GAMEPAD = 0;
  74063. Gamepad.GENERIC = 1;
  74064. Gamepad.XBOX = 2;
  74065. Gamepad.POSE_ENABLED = 3;
  74066. return Gamepad;
  74067. }());
  74068. BABYLON.Gamepad = Gamepad;
  74069. var GenericPad = /** @class */ (function (_super) {
  74070. __extends(GenericPad, _super);
  74071. function GenericPad(id, index, browserGamepad) {
  74072. var _this = _super.call(this, id, index, browserGamepad) || this;
  74073. _this.onButtonDownObservable = new BABYLON.Observable();
  74074. _this.onButtonUpObservable = new BABYLON.Observable();
  74075. _this.type = Gamepad.GENERIC;
  74076. _this._buttons = new Array(browserGamepad.buttons.length);
  74077. return _this;
  74078. }
  74079. GenericPad.prototype.onbuttondown = function (callback) {
  74080. this._onbuttondown = callback;
  74081. };
  74082. GenericPad.prototype.onbuttonup = function (callback) {
  74083. this._onbuttonup = callback;
  74084. };
  74085. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  74086. if (newValue !== currentValue) {
  74087. if (newValue === 1) {
  74088. if (this._onbuttondown) {
  74089. this._onbuttondown(buttonIndex);
  74090. }
  74091. this.onButtonDownObservable.notifyObservers(buttonIndex);
  74092. }
  74093. if (newValue === 0) {
  74094. if (this._onbuttonup) {
  74095. this._onbuttonup(buttonIndex);
  74096. }
  74097. this.onButtonUpObservable.notifyObservers(buttonIndex);
  74098. }
  74099. }
  74100. return newValue;
  74101. };
  74102. GenericPad.prototype.update = function () {
  74103. _super.prototype.update.call(this);
  74104. for (var index = 0; index < this._buttons.length; index++) {
  74105. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  74106. }
  74107. };
  74108. GenericPad.prototype.dispose = function () {
  74109. _super.prototype.dispose.call(this);
  74110. this.onButtonDownObservable.clear();
  74111. this.onButtonUpObservable.clear();
  74112. };
  74113. return GenericPad;
  74114. }(Gamepad));
  74115. BABYLON.GenericPad = GenericPad;
  74116. })(BABYLON || (BABYLON = {}));
  74117. //# sourceMappingURL=babylon.gamepad.js.map
  74118. var BABYLON;
  74119. (function (BABYLON) {
  74120. /**
  74121. * Defines supported buttons for XBox360 compatible gamepads
  74122. */
  74123. var Xbox360Button;
  74124. (function (Xbox360Button) {
  74125. /** A */
  74126. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  74127. /** B */
  74128. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  74129. /** X */
  74130. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  74131. /** Y */
  74132. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  74133. /** Start */
  74134. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  74135. /** Back */
  74136. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  74137. /** Left button */
  74138. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  74139. /** Right button */
  74140. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  74141. /** Left stick */
  74142. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  74143. /** Right stick */
  74144. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  74145. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  74146. /** Defines values for XBox360 DPad */
  74147. var Xbox360Dpad;
  74148. (function (Xbox360Dpad) {
  74149. /** Up */
  74150. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  74151. /** Down */
  74152. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  74153. /** Left */
  74154. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  74155. /** Right */
  74156. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  74157. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  74158. /**
  74159. * Defines a XBox360 gamepad
  74160. */
  74161. var Xbox360Pad = /** @class */ (function (_super) {
  74162. __extends(Xbox360Pad, _super);
  74163. /**
  74164. * Creates a new XBox360 gamepad object
  74165. * @param id defines the id of this gamepad
  74166. * @param index defines its index
  74167. * @param gamepad defines the internal HTML gamepad object
  74168. * @param xboxOne defines if it is a XBox One gamepad
  74169. */
  74170. function Xbox360Pad(id, index, gamepad, xboxOne) {
  74171. if (xboxOne === void 0) { xboxOne = false; }
  74172. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  74173. _this._leftTrigger = 0;
  74174. _this._rightTrigger = 0;
  74175. /** Observable raised when a button is pressed */
  74176. _this.onButtonDownObservable = new BABYLON.Observable();
  74177. /** Observable raised when a button is released */
  74178. _this.onButtonUpObservable = new BABYLON.Observable();
  74179. /** Observable raised when a pad is pressed */
  74180. _this.onPadDownObservable = new BABYLON.Observable();
  74181. /** Observable raised when a pad is released */
  74182. _this.onPadUpObservable = new BABYLON.Observable();
  74183. _this._buttonA = 0;
  74184. _this._buttonB = 0;
  74185. _this._buttonX = 0;
  74186. _this._buttonY = 0;
  74187. _this._buttonBack = 0;
  74188. _this._buttonStart = 0;
  74189. _this._buttonLB = 0;
  74190. _this._buttonRB = 0;
  74191. _this._buttonLeftStick = 0;
  74192. _this._buttonRightStick = 0;
  74193. _this._dPadUp = 0;
  74194. _this._dPadDown = 0;
  74195. _this._dPadLeft = 0;
  74196. _this._dPadRight = 0;
  74197. _this._isXboxOnePad = false;
  74198. _this.type = BABYLON.Gamepad.XBOX;
  74199. _this._isXboxOnePad = xboxOne;
  74200. return _this;
  74201. }
  74202. /**
  74203. * Defines the callback to call when left trigger is pressed
  74204. * @param callback defines the callback to use
  74205. */
  74206. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  74207. this._onlefttriggerchanged = callback;
  74208. };
  74209. /**
  74210. * Defines the callback to call when right trigger is pressed
  74211. * @param callback defines the callback to use
  74212. */
  74213. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  74214. this._onrighttriggerchanged = callback;
  74215. };
  74216. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  74217. /**
  74218. * Gets or sets left trigger value
  74219. */
  74220. get: function () {
  74221. return this._leftTrigger;
  74222. },
  74223. set: function (newValue) {
  74224. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  74225. this._onlefttriggerchanged(newValue);
  74226. }
  74227. this._leftTrigger = newValue;
  74228. },
  74229. enumerable: true,
  74230. configurable: true
  74231. });
  74232. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  74233. /**
  74234. * Gets or sets right trigger value
  74235. */
  74236. get: function () {
  74237. return this._rightTrigger;
  74238. },
  74239. set: function (newValue) {
  74240. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  74241. this._onrighttriggerchanged(newValue);
  74242. }
  74243. this._rightTrigger = newValue;
  74244. },
  74245. enumerable: true,
  74246. configurable: true
  74247. });
  74248. /**
  74249. * Defines the callback to call when a button is pressed
  74250. * @param callback defines the callback to use
  74251. */
  74252. Xbox360Pad.prototype.onbuttondown = function (callback) {
  74253. this._onbuttondown = callback;
  74254. };
  74255. /**
  74256. * Defines the callback to call when a button is released
  74257. * @param callback defines the callback to use
  74258. */
  74259. Xbox360Pad.prototype.onbuttonup = function (callback) {
  74260. this._onbuttonup = callback;
  74261. };
  74262. /**
  74263. * Defines the callback to call when a pad is pressed
  74264. * @param callback defines the callback to use
  74265. */
  74266. Xbox360Pad.prototype.ondpaddown = function (callback) {
  74267. this._ondpaddown = callback;
  74268. };
  74269. /**
  74270. * Defines the callback to call when a pad is released
  74271. * @param callback defines the callback to use
  74272. */
  74273. Xbox360Pad.prototype.ondpadup = function (callback) {
  74274. this._ondpadup = callback;
  74275. };
  74276. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  74277. if (newValue !== currentValue) {
  74278. if (newValue === 1) {
  74279. if (this._onbuttondown) {
  74280. this._onbuttondown(buttonType);
  74281. }
  74282. this.onButtonDownObservable.notifyObservers(buttonType);
  74283. }
  74284. if (newValue === 0) {
  74285. if (this._onbuttonup) {
  74286. this._onbuttonup(buttonType);
  74287. }
  74288. this.onButtonUpObservable.notifyObservers(buttonType);
  74289. }
  74290. }
  74291. return newValue;
  74292. };
  74293. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  74294. if (newValue !== currentValue) {
  74295. if (newValue === 1) {
  74296. if (this._ondpaddown) {
  74297. this._ondpaddown(buttonType);
  74298. }
  74299. this.onPadDownObservable.notifyObservers(buttonType);
  74300. }
  74301. if (newValue === 0) {
  74302. if (this._ondpadup) {
  74303. this._ondpadup(buttonType);
  74304. }
  74305. this.onPadUpObservable.notifyObservers(buttonType);
  74306. }
  74307. }
  74308. return newValue;
  74309. };
  74310. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  74311. /** Gets or sets value of A button */
  74312. get: function () {
  74313. return this._buttonA;
  74314. },
  74315. set: function (value) {
  74316. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  74317. },
  74318. enumerable: true,
  74319. configurable: true
  74320. });
  74321. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  74322. /** Gets or sets value of B button */
  74323. get: function () {
  74324. return this._buttonB;
  74325. },
  74326. set: function (value) {
  74327. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  74328. },
  74329. enumerable: true,
  74330. configurable: true
  74331. });
  74332. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  74333. /** Gets or sets value of X button */
  74334. get: function () {
  74335. return this._buttonX;
  74336. },
  74337. set: function (value) {
  74338. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  74339. },
  74340. enumerable: true,
  74341. configurable: true
  74342. });
  74343. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  74344. /** Gets or sets value of Y button */
  74345. get: function () {
  74346. return this._buttonY;
  74347. },
  74348. set: function (value) {
  74349. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  74350. },
  74351. enumerable: true,
  74352. configurable: true
  74353. });
  74354. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  74355. /** Gets or sets value of Start button */
  74356. get: function () {
  74357. return this._buttonStart;
  74358. },
  74359. set: function (value) {
  74360. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  74361. },
  74362. enumerable: true,
  74363. configurable: true
  74364. });
  74365. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  74366. /** Gets or sets value of Back button */
  74367. get: function () {
  74368. return this._buttonBack;
  74369. },
  74370. set: function (value) {
  74371. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  74372. },
  74373. enumerable: true,
  74374. configurable: true
  74375. });
  74376. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  74377. /** Gets or sets value of Left button */
  74378. get: function () {
  74379. return this._buttonLB;
  74380. },
  74381. set: function (value) {
  74382. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  74383. },
  74384. enumerable: true,
  74385. configurable: true
  74386. });
  74387. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  74388. /** Gets or sets value of Right button */
  74389. get: function () {
  74390. return this._buttonRB;
  74391. },
  74392. set: function (value) {
  74393. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  74394. },
  74395. enumerable: true,
  74396. configurable: true
  74397. });
  74398. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  74399. /** Gets or sets value of left stick */
  74400. get: function () {
  74401. return this._buttonLeftStick;
  74402. },
  74403. set: function (value) {
  74404. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  74405. },
  74406. enumerable: true,
  74407. configurable: true
  74408. });
  74409. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  74410. /** Gets or sets value of right stick */
  74411. get: function () {
  74412. return this._buttonRightStick;
  74413. },
  74414. set: function (value) {
  74415. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  74416. },
  74417. enumerable: true,
  74418. configurable: true
  74419. });
  74420. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  74421. /** Gets or sets value of DPad up */
  74422. get: function () {
  74423. return this._dPadUp;
  74424. },
  74425. set: function (value) {
  74426. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  74427. },
  74428. enumerable: true,
  74429. configurable: true
  74430. });
  74431. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  74432. /** Gets or sets value of DPad down */
  74433. get: function () {
  74434. return this._dPadDown;
  74435. },
  74436. set: function (value) {
  74437. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  74438. },
  74439. enumerable: true,
  74440. configurable: true
  74441. });
  74442. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  74443. /** Gets or sets value of DPad left */
  74444. get: function () {
  74445. return this._dPadLeft;
  74446. },
  74447. set: function (value) {
  74448. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  74449. },
  74450. enumerable: true,
  74451. configurable: true
  74452. });
  74453. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  74454. /** Gets or sets value of DPad right */
  74455. get: function () {
  74456. return this._dPadRight;
  74457. },
  74458. set: function (value) {
  74459. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  74460. },
  74461. enumerable: true,
  74462. configurable: true
  74463. });
  74464. /**
  74465. * Force the gamepad to synchronize with device values
  74466. */
  74467. Xbox360Pad.prototype.update = function () {
  74468. _super.prototype.update.call(this);
  74469. if (this._isXboxOnePad) {
  74470. this.buttonA = this.browserGamepad.buttons[0].value;
  74471. this.buttonB = this.browserGamepad.buttons[1].value;
  74472. this.buttonX = this.browserGamepad.buttons[2].value;
  74473. this.buttonY = this.browserGamepad.buttons[3].value;
  74474. this.buttonLB = this.browserGamepad.buttons[4].value;
  74475. this.buttonRB = this.browserGamepad.buttons[5].value;
  74476. this.leftTrigger = this.browserGamepad.axes[2];
  74477. this.rightTrigger = this.browserGamepad.axes[5];
  74478. this.buttonBack = this.browserGamepad.buttons[9].value;
  74479. this.buttonStart = this.browserGamepad.buttons[8].value;
  74480. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  74481. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  74482. this.dPadUp = this.browserGamepad.buttons[11].value;
  74483. this.dPadDown = this.browserGamepad.buttons[12].value;
  74484. this.dPadLeft = this.browserGamepad.buttons[13].value;
  74485. this.dPadRight = this.browserGamepad.buttons[14].value;
  74486. }
  74487. else {
  74488. this.buttonA = this.browserGamepad.buttons[0].value;
  74489. this.buttonB = this.browserGamepad.buttons[1].value;
  74490. this.buttonX = this.browserGamepad.buttons[2].value;
  74491. this.buttonY = this.browserGamepad.buttons[3].value;
  74492. this.buttonLB = this.browserGamepad.buttons[4].value;
  74493. this.buttonRB = this.browserGamepad.buttons[5].value;
  74494. this.leftTrigger = this.browserGamepad.buttons[6].value;
  74495. this.rightTrigger = this.browserGamepad.buttons[7].value;
  74496. this.buttonBack = this.browserGamepad.buttons[8].value;
  74497. this.buttonStart = this.browserGamepad.buttons[9].value;
  74498. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  74499. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  74500. this.dPadUp = this.browserGamepad.buttons[12].value;
  74501. this.dPadDown = this.browserGamepad.buttons[13].value;
  74502. this.dPadLeft = this.browserGamepad.buttons[14].value;
  74503. this.dPadRight = this.browserGamepad.buttons[15].value;
  74504. }
  74505. };
  74506. Xbox360Pad.prototype.dispose = function () {
  74507. _super.prototype.dispose.call(this);
  74508. this.onButtonDownObservable.clear();
  74509. this.onButtonUpObservable.clear();
  74510. this.onPadDownObservable.clear();
  74511. this.onPadUpObservable.clear();
  74512. };
  74513. return Xbox360Pad;
  74514. }(BABYLON.Gamepad));
  74515. BABYLON.Xbox360Pad = Xbox360Pad;
  74516. })(BABYLON || (BABYLON = {}));
  74517. //# sourceMappingURL=babylon.xboxGamepad.js.map
  74518. var BABYLON;
  74519. (function (BABYLON) {
  74520. /**
  74521. * Defines the types of pose enabled controllers that are supported
  74522. */
  74523. var PoseEnabledControllerType;
  74524. (function (PoseEnabledControllerType) {
  74525. /**
  74526. * HTC Vive
  74527. */
  74528. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  74529. /**
  74530. * Oculus Rift
  74531. */
  74532. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  74533. /**
  74534. * Windows mixed reality
  74535. */
  74536. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  74537. /**
  74538. * Samsung gear VR
  74539. */
  74540. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  74541. /**
  74542. * Google Daydream
  74543. */
  74544. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  74545. /**
  74546. * Generic
  74547. */
  74548. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  74549. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  74550. /**
  74551. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  74552. */
  74553. var PoseEnabledControllerHelper = /** @class */ (function () {
  74554. function PoseEnabledControllerHelper() {
  74555. }
  74556. /**
  74557. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  74558. * @param vrGamepad the gamepad to initialized
  74559. * @returns a vr controller of the type the gamepad identified as
  74560. */
  74561. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  74562. // Oculus Touch
  74563. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  74564. return new BABYLON.OculusTouchController(vrGamepad);
  74565. }
  74566. // Windows Mixed Reality controllers
  74567. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  74568. return new BABYLON.WindowsMotionController(vrGamepad);
  74569. }
  74570. // HTC Vive
  74571. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  74572. return new BABYLON.ViveController(vrGamepad);
  74573. }
  74574. // Samsung/Oculus Gear VR or Oculus Go
  74575. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  74576. return new BABYLON.GearVRController(vrGamepad);
  74577. }
  74578. // Google Daydream
  74579. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  74580. return new BABYLON.DaydreamController(vrGamepad);
  74581. }
  74582. // Generic
  74583. else {
  74584. return new BABYLON.GenericController(vrGamepad);
  74585. }
  74586. };
  74587. return PoseEnabledControllerHelper;
  74588. }());
  74589. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  74590. /**
  74591. * Defines the PoseEnabledController object that contains state of a vr capable controller
  74592. */
  74593. var PoseEnabledController = /** @class */ (function (_super) {
  74594. __extends(PoseEnabledController, _super);
  74595. /**
  74596. * Creates a new PoseEnabledController from a gamepad
  74597. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  74598. */
  74599. function PoseEnabledController(browserGamepad) {
  74600. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  74601. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  74602. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  74603. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  74604. /**
  74605. * The device position in babylon space
  74606. */
  74607. _this.devicePosition = BABYLON.Vector3.Zero();
  74608. /**
  74609. * The device rotation in babylon space
  74610. */
  74611. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  74612. /**
  74613. * The scale factor of the device in babylon space
  74614. */
  74615. _this.deviceScaleFactor = 1;
  74616. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  74617. /**
  74618. * Internal, matrix used to convert room space to babylon space
  74619. * @hidden
  74620. */
  74621. _this._deviceToWorld = BABYLON.Matrix.Identity();
  74622. /**
  74623. * Node to be used when casting a ray from the controller
  74624. * @hidden
  74625. */
  74626. _this._pointingPoseNode = null;
  74627. _this._workingMatrix = BABYLON.Matrix.Identity();
  74628. /**
  74629. * @hidden
  74630. */
  74631. _this._meshAttachedObservable = new BABYLON.Observable();
  74632. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  74633. _this.controllerType = PoseEnabledControllerType.GENERIC;
  74634. _this.position = BABYLON.Vector3.Zero();
  74635. _this.rotationQuaternion = new BABYLON.Quaternion();
  74636. _this._calculatedPosition = BABYLON.Vector3.Zero();
  74637. _this._calculatedRotation = new BABYLON.Quaternion();
  74638. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  74639. return _this;
  74640. }
  74641. /**
  74642. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  74643. */
  74644. PoseEnabledController.prototype.update = function () {
  74645. _super.prototype.update.call(this);
  74646. this._updatePoseAndMesh();
  74647. };
  74648. /**
  74649. * Updates only the pose device and mesh without doing any button event checking
  74650. */
  74651. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  74652. var pose = this.browserGamepad.pose;
  74653. this.updateFromDevice(pose);
  74654. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  74655. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  74656. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  74657. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  74658. if (this._mesh) {
  74659. this._mesh.position.copyFrom(this.devicePosition);
  74660. if (this._mesh.rotationQuaternion) {
  74661. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  74662. }
  74663. }
  74664. };
  74665. /**
  74666. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  74667. * @param poseData raw pose fromthe device
  74668. */
  74669. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  74670. if (poseData) {
  74671. this.rawPose = poseData;
  74672. if (poseData.position) {
  74673. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  74674. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  74675. this._deviceRoomPosition.z *= -1;
  74676. }
  74677. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  74678. this._calculatedPosition.addInPlace(this.position);
  74679. }
  74680. var pose = this.rawPose;
  74681. if (poseData.orientation && pose.orientation) {
  74682. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  74683. if (this._mesh) {
  74684. if (this._mesh.getScene().useRightHandedSystem) {
  74685. this._deviceRoomRotationQuaternion.z *= -1;
  74686. this._deviceRoomRotationQuaternion.w *= -1;
  74687. }
  74688. else {
  74689. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  74690. }
  74691. }
  74692. // if the camera is set, rotate to the camera's rotation
  74693. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  74694. }
  74695. }
  74696. };
  74697. /**
  74698. * Attaches a mesh to the controller
  74699. * @param mesh the mesh to be attached
  74700. */
  74701. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  74702. if (this._mesh) {
  74703. this._mesh.parent = null;
  74704. }
  74705. this._mesh = mesh;
  74706. if (this._poseControlledCamera) {
  74707. this._mesh.parent = this._poseControlledCamera;
  74708. }
  74709. if (!this._mesh.rotationQuaternion) {
  74710. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  74711. }
  74712. // 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
  74713. this._updatePoseAndMesh();
  74714. if (this._pointingPoseNode) {
  74715. var parents = [];
  74716. var obj = this._pointingPoseNode;
  74717. while (obj.parent) {
  74718. parents.push(obj.parent);
  74719. obj = obj.parent;
  74720. }
  74721. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  74722. }
  74723. this._meshAttachedObservable.notifyObservers(mesh);
  74724. };
  74725. /**
  74726. * Attaches the controllers mesh to a camera
  74727. * @param camera the camera the mesh should be attached to
  74728. */
  74729. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  74730. this._poseControlledCamera = camera;
  74731. if (this._mesh) {
  74732. this._mesh.parent = this._poseControlledCamera;
  74733. }
  74734. };
  74735. /**
  74736. * Disposes of the controller
  74737. */
  74738. PoseEnabledController.prototype.dispose = function () {
  74739. if (this._mesh) {
  74740. this._mesh.dispose();
  74741. }
  74742. this._mesh = null;
  74743. _super.prototype.dispose.call(this);
  74744. };
  74745. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  74746. /**
  74747. * The mesh that is attached to the controller
  74748. */
  74749. get: function () {
  74750. return this._mesh;
  74751. },
  74752. enumerable: true,
  74753. configurable: true
  74754. });
  74755. /**
  74756. * Gets the ray of the controller in the direction the controller is pointing
  74757. * @param length the length the resulting ray should be
  74758. * @returns a ray in the direction the controller is pointing
  74759. */
  74760. PoseEnabledController.prototype.getForwardRay = function (length) {
  74761. if (length === void 0) { length = 100; }
  74762. if (!this.mesh) {
  74763. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  74764. }
  74765. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  74766. var origin = m.getTranslation();
  74767. var forward = new BABYLON.Vector3(0, 0, -1);
  74768. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  74769. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  74770. return new BABYLON.Ray(origin, direction, length);
  74771. };
  74772. /**
  74773. * Name of the child mesh that can be used to cast a ray from the controller
  74774. */
  74775. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  74776. return PoseEnabledController;
  74777. }(BABYLON.Gamepad));
  74778. BABYLON.PoseEnabledController = PoseEnabledController;
  74779. })(BABYLON || (BABYLON = {}));
  74780. //# sourceMappingURL=babylon.poseEnabledController.js.map
  74781. var BABYLON;
  74782. (function (BABYLON) {
  74783. /**
  74784. * Defines the WebVRController object that represents controllers tracked in 3D space
  74785. */
  74786. var WebVRController = /** @class */ (function (_super) {
  74787. __extends(WebVRController, _super);
  74788. /**
  74789. * Creates a new WebVRController from a gamepad
  74790. * @param vrGamepad the gamepad that the WebVRController should be created from
  74791. */
  74792. function WebVRController(vrGamepad) {
  74793. var _this = _super.call(this, vrGamepad) || this;
  74794. // Observables
  74795. /**
  74796. * Fired when the trigger state has changed
  74797. */
  74798. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  74799. /**
  74800. * Fired when the main button state has changed
  74801. */
  74802. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  74803. /**
  74804. * Fired when the secondary button state has changed
  74805. */
  74806. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  74807. /**
  74808. * Fired when the pad state has changed
  74809. */
  74810. _this.onPadStateChangedObservable = new BABYLON.Observable();
  74811. /**
  74812. * Fired when controllers stick values have changed
  74813. */
  74814. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  74815. /**
  74816. * X and Y axis corrisponding to the controllers joystick
  74817. */
  74818. _this.pad = { x: 0, y: 0 };
  74819. // avoid GC, store state in a tmp object
  74820. _this._changes = {
  74821. pressChanged: false,
  74822. touchChanged: false,
  74823. valueChanged: false,
  74824. changed: false
  74825. };
  74826. _this._buttons = new Array(vrGamepad.buttons.length);
  74827. _this.hand = vrGamepad.hand;
  74828. return _this;
  74829. }
  74830. /**
  74831. * Fired when a controller button's state has changed
  74832. * @param callback the callback containing the button that was modified
  74833. */
  74834. WebVRController.prototype.onButtonStateChange = function (callback) {
  74835. this._onButtonStateChange = callback;
  74836. };
  74837. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  74838. /**
  74839. * The default controller model for the controller
  74840. */
  74841. get: function () {
  74842. return this._defaultModel;
  74843. },
  74844. enumerable: true,
  74845. configurable: true
  74846. });
  74847. /**
  74848. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  74849. */
  74850. WebVRController.prototype.update = function () {
  74851. _super.prototype.update.call(this);
  74852. for (var index = 0; index < this._buttons.length; index++) {
  74853. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  74854. }
  74855. ;
  74856. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  74857. this.pad.x = this.leftStick.x;
  74858. this.pad.y = this.leftStick.y;
  74859. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  74860. }
  74861. };
  74862. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  74863. if (!newState) {
  74864. newState = {
  74865. pressed: false,
  74866. touched: false,
  74867. value: 0
  74868. };
  74869. }
  74870. if (!currentState) {
  74871. this._buttons[buttonIndex] = {
  74872. pressed: newState.pressed,
  74873. touched: newState.touched,
  74874. value: newState.value
  74875. };
  74876. return;
  74877. }
  74878. this._checkChanges(newState, currentState);
  74879. if (this._changes.changed) {
  74880. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  74881. this._handleButtonChange(buttonIndex, newState, this._changes);
  74882. }
  74883. this._buttons[buttonIndex].pressed = newState.pressed;
  74884. this._buttons[buttonIndex].touched = newState.touched;
  74885. // oculus triggers are never 0, thou not touched.
  74886. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  74887. };
  74888. WebVRController.prototype._checkChanges = function (newState, currentState) {
  74889. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  74890. this._changes.touchChanged = newState.touched !== currentState.touched;
  74891. this._changes.valueChanged = newState.value !== currentState.value;
  74892. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  74893. return this._changes;
  74894. };
  74895. /**
  74896. * Disposes of th webVRCOntroller
  74897. */
  74898. WebVRController.prototype.dispose = function () {
  74899. _super.prototype.dispose.call(this);
  74900. this.onTriggerStateChangedObservable.clear();
  74901. this.onMainButtonStateChangedObservable.clear();
  74902. this.onSecondaryButtonStateChangedObservable.clear();
  74903. this.onPadStateChangedObservable.clear();
  74904. this.onPadValuesChangedObservable.clear();
  74905. };
  74906. return WebVRController;
  74907. }(BABYLON.PoseEnabledController));
  74908. BABYLON.WebVRController = WebVRController;
  74909. })(BABYLON || (BABYLON = {}));
  74910. //# sourceMappingURL=babylon.webVRController.js.map
  74911. var BABYLON;
  74912. (function (BABYLON) {
  74913. /**
  74914. * Oculus Touch Controller
  74915. */
  74916. var OculusTouchController = /** @class */ (function (_super) {
  74917. __extends(OculusTouchController, _super);
  74918. /**
  74919. * Creates a new OculusTouchController from a gamepad
  74920. * @param vrGamepad the gamepad that the controller should be created from
  74921. */
  74922. function OculusTouchController(vrGamepad) {
  74923. var _this = _super.call(this, vrGamepad) || this;
  74924. /**
  74925. * Fired when the secondary trigger on this controller is modified
  74926. */
  74927. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  74928. /**
  74929. * Fired when the thumb rest on this controller is modified
  74930. */
  74931. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  74932. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  74933. return _this;
  74934. }
  74935. /**
  74936. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  74937. * @param scene scene in which to add meshes
  74938. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  74939. */
  74940. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  74941. var _this = this;
  74942. var meshName;
  74943. // Hand
  74944. if (this.hand === 'left') {
  74945. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  74946. }
  74947. else { // Right is the default if no hand is specified
  74948. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  74949. }
  74950. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  74951. /*
  74952. Parent Mesh name: oculus_touch_left
  74953. - body
  74954. - trigger
  74955. - thumbstick
  74956. - grip
  74957. - button_y
  74958. - button_x
  74959. - button_enter
  74960. */
  74961. _this._defaultModel = newMeshes[1];
  74962. _this.attachToMesh(_this._defaultModel);
  74963. if (meshLoaded) {
  74964. meshLoaded(_this._defaultModel);
  74965. }
  74966. });
  74967. };
  74968. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  74969. /**
  74970. * Fired when the A button on this controller is modified
  74971. */
  74972. get: function () {
  74973. if (this.hand === 'right') {
  74974. return this.onMainButtonStateChangedObservable;
  74975. }
  74976. else {
  74977. throw new Error('No A button on left hand');
  74978. }
  74979. },
  74980. enumerable: true,
  74981. configurable: true
  74982. });
  74983. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  74984. /**
  74985. * Fired when the B button on this controller is modified
  74986. */
  74987. get: function () {
  74988. if (this.hand === 'right') {
  74989. return this.onSecondaryButtonStateChangedObservable;
  74990. }
  74991. else {
  74992. throw new Error('No B button on left hand');
  74993. }
  74994. },
  74995. enumerable: true,
  74996. configurable: true
  74997. });
  74998. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  74999. /**
  75000. * Fired when the X button on this controller is modified
  75001. */
  75002. get: function () {
  75003. if (this.hand === 'left') {
  75004. return this.onMainButtonStateChangedObservable;
  75005. }
  75006. else {
  75007. throw new Error('No X button on right hand');
  75008. }
  75009. },
  75010. enumerable: true,
  75011. configurable: true
  75012. });
  75013. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  75014. /**
  75015. * Fired when the Y button on this controller is modified
  75016. */
  75017. get: function () {
  75018. if (this.hand === 'left') {
  75019. return this.onSecondaryButtonStateChangedObservable;
  75020. }
  75021. else {
  75022. throw new Error('No Y button on right hand');
  75023. }
  75024. },
  75025. enumerable: true,
  75026. configurable: true
  75027. });
  75028. /**
  75029. * Called once for each button that changed state since the last frame
  75030. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  75031. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  75032. * 2) secondary trigger (same)
  75033. * 3) A (right) X (left), touch, pressed = value
  75034. * 4) B / Y
  75035. * 5) thumb rest
  75036. * @param buttonIdx Which button index changed
  75037. * @param state New state of the button
  75038. * @param changes Which properties on the state changed since last frame
  75039. */
  75040. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  75041. var notifyObject = state; //{ state: state, changes: changes };
  75042. var triggerDirection = this.hand === 'right' ? -1 : 1;
  75043. switch (buttonIdx) {
  75044. case 0:
  75045. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  75046. return;
  75047. case 1: // index trigger
  75048. if (this._defaultModel) {
  75049. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  75050. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  75051. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  75052. }
  75053. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  75054. return;
  75055. case 2: // secondary trigger
  75056. if (this._defaultModel) {
  75057. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  75058. }
  75059. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  75060. return;
  75061. case 3:
  75062. if (this._defaultModel) {
  75063. if (notifyObject.pressed) {
  75064. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  75065. }
  75066. else {
  75067. (this._defaultModel.getChildren()[1]).position.y = 0;
  75068. }
  75069. }
  75070. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  75071. return;
  75072. case 4:
  75073. if (this._defaultModel) {
  75074. if (notifyObject.pressed) {
  75075. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  75076. }
  75077. else {
  75078. (this._defaultModel.getChildren()[2]).position.y = 0;
  75079. }
  75080. }
  75081. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  75082. return;
  75083. case 5:
  75084. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  75085. return;
  75086. }
  75087. };
  75088. /**
  75089. * Base Url for the controller model.
  75090. */
  75091. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  75092. /**
  75093. * File name for the left controller model.
  75094. */
  75095. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  75096. /**
  75097. * File name for the right controller model.
  75098. */
  75099. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  75100. return OculusTouchController;
  75101. }(BABYLON.WebVRController));
  75102. BABYLON.OculusTouchController = OculusTouchController;
  75103. })(BABYLON || (BABYLON = {}));
  75104. //# sourceMappingURL=babylon.oculusTouchController.js.map
  75105. var BABYLON;
  75106. (function (BABYLON) {
  75107. /**
  75108. * Vive Controller
  75109. */
  75110. var ViveController = /** @class */ (function (_super) {
  75111. __extends(ViveController, _super);
  75112. /**
  75113. * Creates a new ViveController from a gamepad
  75114. * @param vrGamepad the gamepad that the controller should be created from
  75115. */
  75116. function ViveController(vrGamepad) {
  75117. var _this = _super.call(this, vrGamepad) || this;
  75118. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  75119. _this._invertLeftStickY = true;
  75120. return _this;
  75121. }
  75122. /**
  75123. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  75124. * @param scene scene in which to add meshes
  75125. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  75126. */
  75127. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  75128. var _this = this;
  75129. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  75130. /*
  75131. Parent Mesh name: ViveWand
  75132. - body
  75133. - r_gripper
  75134. - l_gripper
  75135. - menu_button
  75136. - system_button
  75137. - trackpad
  75138. - trigger
  75139. - LED
  75140. */
  75141. _this._defaultModel = newMeshes[1];
  75142. _this.attachToMesh(_this._defaultModel);
  75143. if (meshLoaded) {
  75144. meshLoaded(_this._defaultModel);
  75145. }
  75146. });
  75147. };
  75148. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  75149. /**
  75150. * Fired when the left button on this controller is modified
  75151. */
  75152. get: function () {
  75153. return this.onMainButtonStateChangedObservable;
  75154. },
  75155. enumerable: true,
  75156. configurable: true
  75157. });
  75158. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  75159. /**
  75160. * Fired when the right button on this controller is modified
  75161. */
  75162. get: function () {
  75163. return this.onMainButtonStateChangedObservable;
  75164. },
  75165. enumerable: true,
  75166. configurable: true
  75167. });
  75168. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  75169. /**
  75170. * Fired when the menu button on this controller is modified
  75171. */
  75172. get: function () {
  75173. return this.onSecondaryButtonStateChangedObservable;
  75174. },
  75175. enumerable: true,
  75176. configurable: true
  75177. });
  75178. /**
  75179. * Called once for each button that changed state since the last frame
  75180. * Vive mapping:
  75181. * 0: touchpad
  75182. * 1: trigger
  75183. * 2: left AND right buttons
  75184. * 3: menu button
  75185. * @param buttonIdx Which button index changed
  75186. * @param state New state of the button
  75187. * @param changes Which properties on the state changed since last frame
  75188. */
  75189. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  75190. var notifyObject = state; //{ state: state, changes: changes };
  75191. switch (buttonIdx) {
  75192. case 0:
  75193. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  75194. return;
  75195. case 1: // index trigger
  75196. if (this._defaultModel) {
  75197. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  75198. }
  75199. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  75200. return;
  75201. case 2: // left AND right button
  75202. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  75203. return;
  75204. case 3:
  75205. if (this._defaultModel) {
  75206. if (notifyObject.pressed) {
  75207. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  75208. }
  75209. else {
  75210. (this._defaultModel.getChildren()[2]).position.y = 0;
  75211. }
  75212. }
  75213. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  75214. return;
  75215. }
  75216. };
  75217. /**
  75218. * Base Url for the controller model.
  75219. */
  75220. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  75221. /**
  75222. * File name for the controller model.
  75223. */
  75224. ViveController.MODEL_FILENAME = 'wand.babylon';
  75225. return ViveController;
  75226. }(BABYLON.WebVRController));
  75227. BABYLON.ViveController = ViveController;
  75228. })(BABYLON || (BABYLON = {}));
  75229. //# sourceMappingURL=babylon.viveController.js.map
  75230. var BABYLON;
  75231. (function (BABYLON) {
  75232. /**
  75233. * Generic Controller
  75234. */
  75235. var GenericController = /** @class */ (function (_super) {
  75236. __extends(GenericController, _super);
  75237. /**
  75238. * Creates a new GenericController from a gamepad
  75239. * @param vrGamepad the gamepad that the controller should be created from
  75240. */
  75241. function GenericController(vrGamepad) {
  75242. return _super.call(this, vrGamepad) || this;
  75243. }
  75244. /**
  75245. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  75246. * @param scene scene in which to add meshes
  75247. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  75248. */
  75249. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  75250. var _this = this;
  75251. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  75252. _this._defaultModel = newMeshes[1];
  75253. _this.attachToMesh(_this._defaultModel);
  75254. if (meshLoaded) {
  75255. meshLoaded(_this._defaultModel);
  75256. }
  75257. });
  75258. };
  75259. /**
  75260. * Called once for each button that changed state since the last frame
  75261. * @param buttonIdx Which button index changed
  75262. * @param state New state of the button
  75263. * @param changes Which properties on the state changed since last frame
  75264. */
  75265. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  75266. console.log("Button id: " + buttonIdx + "state: ");
  75267. console.dir(state);
  75268. };
  75269. /**
  75270. * Base Url for the controller model.
  75271. */
  75272. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  75273. /**
  75274. * File name for the controller model.
  75275. */
  75276. GenericController.MODEL_FILENAME = 'generic.babylon';
  75277. return GenericController;
  75278. }(BABYLON.WebVRController));
  75279. BABYLON.GenericController = GenericController;
  75280. })(BABYLON || (BABYLON = {}));
  75281. //# sourceMappingURL=babylon.genericController.js.map
  75282. var BABYLON;
  75283. (function (BABYLON) {
  75284. /**
  75285. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  75286. */
  75287. var LoadedMeshInfo = /** @class */ (function () {
  75288. function LoadedMeshInfo() {
  75289. /**
  75290. * Map of the button meshes contained in the controller
  75291. */
  75292. this.buttonMeshes = {};
  75293. /**
  75294. * Map of the axis meshes contained in the controller
  75295. */
  75296. this.axisMeshes = {};
  75297. }
  75298. return LoadedMeshInfo;
  75299. }());
  75300. /**
  75301. * Defines the WindowsMotionController object that the state of the windows motion controller
  75302. */
  75303. var WindowsMotionController = /** @class */ (function (_super) {
  75304. __extends(WindowsMotionController, _super);
  75305. /**
  75306. * Creates a new WindowsMotionController from a gamepad
  75307. * @param vrGamepad the gamepad that the controller should be created from
  75308. */
  75309. function WindowsMotionController(vrGamepad) {
  75310. var _this = _super.call(this, vrGamepad) || this;
  75311. _this._mapping = {
  75312. // Semantic button names
  75313. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  75314. // A mapping of the button name to glTF model node name
  75315. // that should be transformed by button value.
  75316. buttonMeshNames: {
  75317. 'trigger': 'SELECT',
  75318. 'menu': 'MENU',
  75319. 'grip': 'GRASP',
  75320. 'thumbstick': 'THUMBSTICK_PRESS',
  75321. 'trackpad': 'TOUCHPAD_PRESS'
  75322. },
  75323. // This mapping is used to translate from the Motion Controller to Babylon semantics
  75324. buttonObservableNames: {
  75325. 'trigger': 'onTriggerStateChangedObservable',
  75326. 'menu': 'onSecondaryButtonStateChangedObservable',
  75327. 'grip': 'onMainButtonStateChangedObservable',
  75328. 'thumbstick': 'onPadStateChangedObservable',
  75329. 'trackpad': 'onTrackpadChangedObservable'
  75330. },
  75331. // A mapping of the axis name to glTF model node name
  75332. // that should be transformed by axis value.
  75333. // This array mirrors the browserGamepad.axes array, such that
  75334. // the mesh corresponding to axis 0 is in this array index 0.
  75335. axisMeshNames: [
  75336. 'THUMBSTICK_X',
  75337. 'THUMBSTICK_Y',
  75338. 'TOUCHPAD_TOUCH_X',
  75339. 'TOUCHPAD_TOUCH_Y'
  75340. ],
  75341. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  75342. };
  75343. /**
  75344. * Fired when the trackpad on this controller is clicked
  75345. */
  75346. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  75347. /**
  75348. * Fired when the trackpad on this controller is modified
  75349. */
  75350. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  75351. /**
  75352. * The current x and y values of this controller's trackpad
  75353. */
  75354. _this.trackpad = { x: 0, y: 0 };
  75355. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  75356. _this._loadedMeshInfo = null;
  75357. return _this;
  75358. }
  75359. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  75360. /**
  75361. * Fired when the trigger on this controller is modified
  75362. */
  75363. get: function () {
  75364. return this.onTriggerStateChangedObservable;
  75365. },
  75366. enumerable: true,
  75367. configurable: true
  75368. });
  75369. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  75370. /**
  75371. * Fired when the menu button on this controller is modified
  75372. */
  75373. get: function () {
  75374. return this.onSecondaryButtonStateChangedObservable;
  75375. },
  75376. enumerable: true,
  75377. configurable: true
  75378. });
  75379. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  75380. /**
  75381. * Fired when the grip button on this controller is modified
  75382. */
  75383. get: function () {
  75384. return this.onMainButtonStateChangedObservable;
  75385. },
  75386. enumerable: true,
  75387. configurable: true
  75388. });
  75389. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  75390. /**
  75391. * Fired when the thumbstick button on this controller is modified
  75392. */
  75393. get: function () {
  75394. return this.onPadStateChangedObservable;
  75395. },
  75396. enumerable: true,
  75397. configurable: true
  75398. });
  75399. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  75400. /**
  75401. * Fired when the touchpad button on this controller is modified
  75402. */
  75403. get: function () {
  75404. return this.onTrackpadChangedObservable;
  75405. },
  75406. enumerable: true,
  75407. configurable: true
  75408. });
  75409. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  75410. /**
  75411. * Fired when the touchpad values on this controller are modified
  75412. */
  75413. get: function () {
  75414. return this.onTrackpadValuesChangedObservable;
  75415. },
  75416. enumerable: true,
  75417. configurable: true
  75418. });
  75419. WindowsMotionController.prototype._updateTrackpad = function () {
  75420. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  75421. this.trackpad.x = this.browserGamepad["axes"][2];
  75422. this.trackpad.y = this.browserGamepad["axes"][3];
  75423. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  75424. }
  75425. };
  75426. /**
  75427. * Called once per frame by the engine.
  75428. */
  75429. WindowsMotionController.prototype.update = function () {
  75430. _super.prototype.update.call(this);
  75431. if (this.browserGamepad.axes) {
  75432. this._updateTrackpad();
  75433. // Only need to animate axes if there is a loaded mesh
  75434. if (this._loadedMeshInfo) {
  75435. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  75436. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  75437. }
  75438. }
  75439. }
  75440. };
  75441. /**
  75442. * Called once for each button that changed state since the last frame
  75443. * @param buttonIdx Which button index changed
  75444. * @param state New state of the button
  75445. * @param changes Which properties on the state changed since last frame
  75446. */
  75447. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  75448. var buttonName = this._mapping.buttons[buttonIdx];
  75449. if (!buttonName) {
  75450. return;
  75451. }
  75452. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  75453. this._updateTrackpad();
  75454. // Only emit events for buttons that we know how to map from index to name
  75455. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  75456. if (observable) {
  75457. observable.notifyObservers(state);
  75458. }
  75459. this._lerpButtonTransform(buttonName, state.value);
  75460. };
  75461. /**
  75462. * Moves the buttons on the controller mesh based on their current state
  75463. * @param buttonName the name of the button to move
  75464. * @param buttonValue the value of the button which determines the buttons new position
  75465. */
  75466. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  75467. // If there is no loaded mesh, there is nothing to transform.
  75468. if (!this._loadedMeshInfo) {
  75469. return;
  75470. }
  75471. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  75472. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  75473. return;
  75474. }
  75475. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  75476. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  75477. };
  75478. /**
  75479. * Moves the axis on the controller mesh based on its current state
  75480. * @param axis the index of the axis
  75481. * @param axisValue the value of the axis which determines the meshes new position
  75482. * @hidden
  75483. */
  75484. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  75485. if (!this._loadedMeshInfo) {
  75486. return;
  75487. }
  75488. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  75489. if (!meshInfo) {
  75490. return;
  75491. }
  75492. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  75493. return;
  75494. }
  75495. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  75496. var lerpValue = axisValue * 0.5 + 0.5;
  75497. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  75498. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  75499. };
  75500. /**
  75501. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  75502. * @param scene scene in which to add meshes
  75503. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  75504. */
  75505. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  75506. var _this = this;
  75507. if (forceDefault === void 0) { forceDefault = false; }
  75508. var path;
  75509. var filename;
  75510. // Checking if GLB loader is present
  75511. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  75512. // Determine the device specific folder based on the ID suffix
  75513. var device = 'default';
  75514. if (this.id && !forceDefault) {
  75515. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  75516. device = ((match && match[0]) || device);
  75517. }
  75518. // Hand
  75519. if (this.hand === 'left') {
  75520. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  75521. }
  75522. else { // Right is the default if no hand is specified
  75523. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  75524. }
  75525. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  75526. }
  75527. else {
  75528. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  75529. path = BABYLON.GenericController.MODEL_BASE_URL;
  75530. filename = BABYLON.GenericController.MODEL_FILENAME;
  75531. }
  75532. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  75533. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  75534. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  75535. if (!_this._loadedMeshInfo) {
  75536. return;
  75537. }
  75538. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  75539. _this.attachToMesh(_this._defaultModel);
  75540. if (meshLoaded) {
  75541. meshLoaded(_this._defaultModel);
  75542. }
  75543. }, null, function (scene, message) {
  75544. BABYLON.Tools.Log(message);
  75545. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  75546. if (!forceDefault) {
  75547. _this.initControllerMesh(scene, meshLoaded, true);
  75548. }
  75549. });
  75550. };
  75551. /**
  75552. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  75553. * can be transformed by button presses and axes values, based on this._mapping.
  75554. *
  75555. * @param scene scene in which the meshes exist
  75556. * @param meshes list of meshes that make up the controller model to process
  75557. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  75558. */
  75559. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  75560. var loadedMeshInfo = null;
  75561. // Create a new mesh to contain the glTF hierarchy
  75562. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  75563. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  75564. var childMesh = null;
  75565. for (var i = 0; i < meshes.length; i++) {
  75566. var mesh = meshes[i];
  75567. if (!mesh.parent) {
  75568. // Exclude controller meshes from picking results
  75569. mesh.isPickable = false;
  75570. // Handle root node, attach to the new parentMesh
  75571. childMesh = mesh;
  75572. break;
  75573. }
  75574. }
  75575. if (childMesh) {
  75576. childMesh.setParent(parentMesh);
  75577. // Create our mesh info. Note that this method will always return non-null.
  75578. loadedMeshInfo = this.createMeshInfo(parentMesh);
  75579. }
  75580. else {
  75581. BABYLON.Tools.Warn('Could not find root node in model file.');
  75582. }
  75583. return loadedMeshInfo;
  75584. };
  75585. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  75586. var loadedMeshInfo = new LoadedMeshInfo();
  75587. var i;
  75588. loadedMeshInfo.rootNode = rootNode;
  75589. // Reset the caches
  75590. loadedMeshInfo.buttonMeshes = {};
  75591. loadedMeshInfo.axisMeshes = {};
  75592. // Button Meshes
  75593. for (i = 0; i < this._mapping.buttons.length; i++) {
  75594. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  75595. if (!buttonMeshName) {
  75596. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  75597. continue;
  75598. }
  75599. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  75600. if (!buttonMesh) {
  75601. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  75602. continue;
  75603. }
  75604. var buttonMeshInfo = {
  75605. index: i,
  75606. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  75607. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  75608. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  75609. };
  75610. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  75611. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  75612. }
  75613. else {
  75614. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  75615. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  75616. '(VALUE: ' + !!buttonMeshInfo.value +
  75617. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  75618. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  75619. ')');
  75620. }
  75621. }
  75622. // Axis Meshes
  75623. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  75624. var axisMeshName = this._mapping.axisMeshNames[i];
  75625. if (!axisMeshName) {
  75626. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  75627. continue;
  75628. }
  75629. var axisMesh = getChildByName(rootNode, axisMeshName);
  75630. if (!axisMesh) {
  75631. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  75632. continue;
  75633. }
  75634. var axisMeshInfo = {
  75635. index: i,
  75636. value: getImmediateChildByName(axisMesh, 'VALUE'),
  75637. min: getImmediateChildByName(axisMesh, 'MIN'),
  75638. max: getImmediateChildByName(axisMesh, 'MAX')
  75639. };
  75640. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  75641. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  75642. }
  75643. else {
  75644. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  75645. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  75646. '(VALUE: ' + !!axisMeshInfo.value +
  75647. ', MIN: ' + !!axisMeshInfo.min +
  75648. ', MAX:' + !!axisMeshInfo.max +
  75649. ')');
  75650. }
  75651. }
  75652. // Pointing Ray
  75653. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  75654. if (!loadedMeshInfo.pointingPoseNode) {
  75655. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  75656. }
  75657. else {
  75658. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  75659. }
  75660. return loadedMeshInfo;
  75661. // Look through all children recursively. This will return null if no mesh exists with the given name.
  75662. function getChildByName(node, name) {
  75663. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  75664. }
  75665. // Look through only immediate children. This will return null if no mesh exists with the given name.
  75666. function getImmediateChildByName(node, name) {
  75667. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  75668. }
  75669. };
  75670. /**
  75671. * Gets the ray of the controller in the direction the controller is pointing
  75672. * @param length the length the resulting ray should be
  75673. * @returns a ray in the direction the controller is pointing
  75674. */
  75675. WindowsMotionController.prototype.getForwardRay = function (length) {
  75676. if (length === void 0) { length = 100; }
  75677. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  75678. return _super.prototype.getForwardRay.call(this, length);
  75679. }
  75680. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  75681. var origin = m.getTranslation();
  75682. var forward = new BABYLON.Vector3(0, 0, -1);
  75683. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  75684. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  75685. return new BABYLON.Ray(origin, direction, length);
  75686. };
  75687. /**
  75688. * Disposes of the controller
  75689. */
  75690. WindowsMotionController.prototype.dispose = function () {
  75691. _super.prototype.dispose.call(this);
  75692. this.onTrackpadChangedObservable.clear();
  75693. };
  75694. /**
  75695. * The base url used to load the left and right controller models
  75696. */
  75697. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  75698. /**
  75699. * The name of the left controller model file
  75700. */
  75701. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  75702. /**
  75703. * The name of the right controller model file
  75704. */
  75705. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  75706. /**
  75707. * The controller name prefix for this controller type
  75708. */
  75709. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  75710. /**
  75711. * The controller id pattern for this controller type
  75712. */
  75713. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  75714. return WindowsMotionController;
  75715. }(BABYLON.WebVRController));
  75716. BABYLON.WindowsMotionController = WindowsMotionController;
  75717. })(BABYLON || (BABYLON = {}));
  75718. //# sourceMappingURL=babylon.windowsMotionController.js.map
  75719. var BABYLON;
  75720. (function (BABYLON) {
  75721. /**
  75722. * Gear VR Controller
  75723. */
  75724. var GearVRController = /** @class */ (function (_super) {
  75725. __extends(GearVRController, _super);
  75726. /**
  75727. * Creates a new GearVRController from a gamepad
  75728. * @param vrGamepad the gamepad that the controller should be created from
  75729. */
  75730. function GearVRController(vrGamepad) {
  75731. var _this = _super.call(this, vrGamepad) || this;
  75732. _this._maxRotationDistFromHeadset = Math.PI / 5;
  75733. _this._draggedRoomRotation = 0;
  75734. _this._tmpVector = new BABYLON.Vector3();
  75735. _this._buttonIndexToObservableNameMap = [
  75736. 'onTrackpadChangedObservable',
  75737. 'onTriggerStateChangedObservable' // Trigger
  75738. ];
  75739. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  75740. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  75741. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  75742. return _this;
  75743. }
  75744. /**
  75745. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  75746. * @param poseData raw pose fromthe device
  75747. */
  75748. GearVRController.prototype.updateFromDevice = function (poseData) {
  75749. _super.prototype.updateFromDevice.call(this, poseData);
  75750. if (BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera) {
  75751. if (BABYLON.Engine.LastCreatedScene.activeCamera.deviceRotationQuaternion) {
  75752. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  75753. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(this._tmpVector);
  75754. // Find the radian distance away that the headset is from the controllers rotation
  75755. var distanceAway = Math.atan2(Math.sin(this._tmpVector.y - this._draggedRoomRotation), Math.cos(this._tmpVector.y - this._draggedRoomRotation));
  75756. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  75757. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  75758. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  75759. this._draggedRoomRotation += rotationAmount;
  75760. // Rotate controller around headset
  75761. var sin = Math.sin(-rotationAmount);
  75762. var cos = Math.cos(-rotationAmount);
  75763. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  75764. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  75765. }
  75766. }
  75767. }
  75768. };
  75769. /**
  75770. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  75771. * @param scene scene in which to add meshes
  75772. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  75773. */
  75774. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  75775. var _this = this;
  75776. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  75777. // Offset the controller so it will rotate around the users wrist
  75778. var mesh = new BABYLON.Mesh("", scene);
  75779. newMeshes[1].parent = mesh;
  75780. newMeshes[1].position.z = -0.15;
  75781. _this._defaultModel = mesh;
  75782. _this.attachToMesh(_this._defaultModel);
  75783. if (meshLoaded) {
  75784. meshLoaded(_this._defaultModel);
  75785. }
  75786. });
  75787. };
  75788. /**
  75789. * Called once for each button that changed state since the last frame
  75790. * @param buttonIdx Which button index changed
  75791. * @param state New state of the button
  75792. * @param changes Which properties on the state changed since last frame
  75793. */
  75794. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  75795. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  75796. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  75797. // Only emit events for buttons that we know how to map from index to observable
  75798. var observable = this[observableName];
  75799. if (observable) {
  75800. observable.notifyObservers(state);
  75801. }
  75802. }
  75803. };
  75804. /**
  75805. * Base Url for the controller model.
  75806. */
  75807. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  75808. /**
  75809. * File name for the controller model.
  75810. */
  75811. GearVRController.MODEL_FILENAME = 'generic.babylon';
  75812. /**
  75813. * Gamepad Id prefix used to identify this controller.
  75814. */
  75815. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  75816. return GearVRController;
  75817. }(BABYLON.WebVRController));
  75818. BABYLON.GearVRController = GearVRController;
  75819. })(BABYLON || (BABYLON = {}));
  75820. //# sourceMappingURL=babylon.gearVRController.js.map
  75821. var BABYLON;
  75822. (function (BABYLON) {
  75823. /**
  75824. * Google Daydream controller
  75825. */
  75826. var DaydreamController = /** @class */ (function (_super) {
  75827. __extends(DaydreamController, _super);
  75828. /**
  75829. * Creates a new DaydreamController from a gamepad
  75830. * @param vrGamepad the gamepad that the controller should be created from
  75831. */
  75832. function DaydreamController(vrGamepad) {
  75833. var _this = _super.call(this, vrGamepad) || this;
  75834. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  75835. return _this;
  75836. }
  75837. /**
  75838. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  75839. * @param scene scene in which to add meshes
  75840. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  75841. */
  75842. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  75843. var _this = this;
  75844. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  75845. _this._defaultModel = newMeshes[1];
  75846. _this.attachToMesh(_this._defaultModel);
  75847. if (meshLoaded) {
  75848. meshLoaded(_this._defaultModel);
  75849. }
  75850. });
  75851. };
  75852. /**
  75853. * Called once for each button that changed state since the last frame
  75854. * @param buttonIdx Which button index changed
  75855. * @param state New state of the button
  75856. * @param changes Which properties on the state changed since last frame
  75857. */
  75858. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  75859. // Daydream controller only has 1 GamepadButton (on the trackpad).
  75860. if (buttonIdx === 0) {
  75861. var observable = this.onTriggerStateChangedObservable;
  75862. if (observable) {
  75863. observable.notifyObservers(state);
  75864. }
  75865. }
  75866. else {
  75867. // If the app or home buttons are ever made available
  75868. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  75869. }
  75870. };
  75871. /**
  75872. * Base Url for the controller model.
  75873. */
  75874. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  75875. /**
  75876. * File name for the controller model.
  75877. */
  75878. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  75879. /**
  75880. * Gamepad Id prefix used to identify Daydream Controller.
  75881. */
  75882. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  75883. return DaydreamController;
  75884. }(BABYLON.WebVRController));
  75885. BABYLON.DaydreamController = DaydreamController;
  75886. })(BABYLON || (BABYLON = {}));
  75887. //# sourceMappingURL=babylon.daydreamController.js.map
  75888. var BABYLON;
  75889. (function (BABYLON) {
  75890. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  75891. get: function () {
  75892. if (!this._gamepadManager) {
  75893. this._gamepadManager = new BABYLON.GamepadManager(this);
  75894. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  75895. if (!component) {
  75896. component = new GamepadSystemSceneComponent(this);
  75897. this._addComponent(component);
  75898. }
  75899. }
  75900. return this._gamepadManager;
  75901. },
  75902. enumerable: true,
  75903. configurable: true
  75904. });
  75905. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  75906. this.add(new BABYLON.FreeCameraGamepadInput());
  75907. return this;
  75908. };
  75909. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  75910. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  75911. return this;
  75912. };
  75913. /**
  75914. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  75915. */
  75916. var GamepadSystemSceneComponent = /** @class */ (function () {
  75917. /**
  75918. * Creates a new instance of the component for the given scene
  75919. * @param scene Defines the scene to register the component in
  75920. */
  75921. function GamepadSystemSceneComponent(scene) {
  75922. /**
  75923. * The component name helpfull to identify the component in the list of scene components.
  75924. */
  75925. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  75926. this.scene = scene;
  75927. }
  75928. /**
  75929. * Registers the component in a given scene
  75930. */
  75931. GamepadSystemSceneComponent.prototype.register = function () {
  75932. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  75933. };
  75934. /**
  75935. * Rebuilds the elements related to this component in case of
  75936. * context lost for instance.
  75937. */
  75938. GamepadSystemSceneComponent.prototype.rebuild = function () {
  75939. // Nothing to do for gamepads
  75940. };
  75941. /**
  75942. * Disposes the component and the associated ressources
  75943. */
  75944. GamepadSystemSceneComponent.prototype.dispose = function () {
  75945. var gamepadManager = this.scene._gamepadManager;
  75946. if (gamepadManager) {
  75947. gamepadManager.dispose();
  75948. this.scene._gamepadManager = null;
  75949. }
  75950. };
  75951. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  75952. var gamepadManager = this.scene._gamepadManager;
  75953. if (gamepadManager && gamepadManager._isMonitoring) {
  75954. gamepadManager._checkGamepadsStatus();
  75955. }
  75956. };
  75957. return GamepadSystemSceneComponent;
  75958. }());
  75959. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  75960. })(BABYLON || (BABYLON = {}));
  75961. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  75962. var BABYLON;
  75963. (function (BABYLON) {
  75964. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  75965. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  75966. });
  75967. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  75968. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  75969. });
  75970. var FollowCamera = /** @class */ (function (_super) {
  75971. __extends(FollowCamera, _super);
  75972. function FollowCamera(name, position, scene, lockedTarget) {
  75973. if (lockedTarget === void 0) { lockedTarget = null; }
  75974. var _this = _super.call(this, name, position, scene) || this;
  75975. _this.radius = 12;
  75976. _this.rotationOffset = 0;
  75977. _this.heightOffset = 4;
  75978. _this.cameraAcceleration = 0.05;
  75979. _this.maxCameraSpeed = 20;
  75980. _this.lockedTarget = lockedTarget;
  75981. return _this;
  75982. }
  75983. FollowCamera.prototype.getRadians = function (degrees) {
  75984. return degrees * Math.PI / 180;
  75985. };
  75986. FollowCamera.prototype.follow = function (cameraTarget) {
  75987. if (!cameraTarget)
  75988. return;
  75989. var yRotation;
  75990. if (cameraTarget.rotationQuaternion) {
  75991. var rotMatrix = new BABYLON.Matrix();
  75992. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  75993. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  75994. }
  75995. else {
  75996. yRotation = cameraTarget.rotation.y;
  75997. }
  75998. var radians = this.getRadians(this.rotationOffset) + yRotation;
  75999. var targetPosition = cameraTarget.getAbsolutePosition();
  76000. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  76001. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  76002. var dx = targetX - this.position.x;
  76003. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  76004. var dz = (targetZ) - this.position.z;
  76005. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  76006. var vy = dy * this.cameraAcceleration;
  76007. var vz = dz * this.cameraAcceleration * 2;
  76008. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  76009. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  76010. }
  76011. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  76012. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  76013. }
  76014. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  76015. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  76016. }
  76017. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  76018. this.setTarget(targetPosition);
  76019. };
  76020. /** @hidden */
  76021. FollowCamera.prototype._checkInputs = function () {
  76022. _super.prototype._checkInputs.call(this);
  76023. if (this.lockedTarget) {
  76024. this.follow(this.lockedTarget);
  76025. }
  76026. };
  76027. FollowCamera.prototype.getClassName = function () {
  76028. return "FollowCamera";
  76029. };
  76030. __decorate([
  76031. BABYLON.serialize()
  76032. ], FollowCamera.prototype, "radius", void 0);
  76033. __decorate([
  76034. BABYLON.serialize()
  76035. ], FollowCamera.prototype, "rotationOffset", void 0);
  76036. __decorate([
  76037. BABYLON.serialize()
  76038. ], FollowCamera.prototype, "heightOffset", void 0);
  76039. __decorate([
  76040. BABYLON.serialize()
  76041. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  76042. __decorate([
  76043. BABYLON.serialize()
  76044. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  76045. __decorate([
  76046. BABYLON.serializeAsMeshReference("lockedTargetId")
  76047. ], FollowCamera.prototype, "lockedTarget", void 0);
  76048. return FollowCamera;
  76049. }(BABYLON.TargetCamera));
  76050. BABYLON.FollowCamera = FollowCamera;
  76051. var ArcFollowCamera = /** @class */ (function (_super) {
  76052. __extends(ArcFollowCamera, _super);
  76053. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  76054. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  76055. _this.alpha = alpha;
  76056. _this.beta = beta;
  76057. _this.radius = radius;
  76058. _this.target = target;
  76059. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  76060. _this.follow();
  76061. return _this;
  76062. }
  76063. ArcFollowCamera.prototype.follow = function () {
  76064. if (!this.target) {
  76065. return;
  76066. }
  76067. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  76068. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  76069. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  76070. var targetPosition = this.target.getAbsolutePosition();
  76071. this.position = targetPosition.add(this._cartesianCoordinates);
  76072. this.setTarget(targetPosition);
  76073. };
  76074. /** @hidden */
  76075. ArcFollowCamera.prototype._checkInputs = function () {
  76076. _super.prototype._checkInputs.call(this);
  76077. this.follow();
  76078. };
  76079. ArcFollowCamera.prototype.getClassName = function () {
  76080. return "ArcFollowCamera";
  76081. };
  76082. return ArcFollowCamera;
  76083. }(BABYLON.TargetCamera));
  76084. BABYLON.ArcFollowCamera = ArcFollowCamera;
  76085. })(BABYLON || (BABYLON = {}));
  76086. //# sourceMappingURL=babylon.followCamera.js.map
  76087. var BABYLON;
  76088. (function (BABYLON) {
  76089. // We're mainly based on the logic defined into the FreeCamera code
  76090. var UniversalCamera = /** @class */ (function (_super) {
  76091. __extends(UniversalCamera, _super);
  76092. //-- end properties for backward compatibility for inputs
  76093. function UniversalCamera(name, position, scene) {
  76094. var _this = _super.call(this, name, position, scene) || this;
  76095. _this.inputs.addGamepad();
  76096. return _this;
  76097. }
  76098. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  76099. //-- Begin properties for backward compatibility for inputs
  76100. get: function () {
  76101. var gamepad = this.inputs.attached["gamepad"];
  76102. if (gamepad)
  76103. return gamepad.gamepadAngularSensibility;
  76104. return 0;
  76105. },
  76106. set: function (value) {
  76107. var gamepad = this.inputs.attached["gamepad"];
  76108. if (gamepad)
  76109. gamepad.gamepadAngularSensibility = value;
  76110. },
  76111. enumerable: true,
  76112. configurable: true
  76113. });
  76114. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  76115. get: function () {
  76116. var gamepad = this.inputs.attached["gamepad"];
  76117. if (gamepad)
  76118. return gamepad.gamepadMoveSensibility;
  76119. return 0;
  76120. },
  76121. set: function (value) {
  76122. var gamepad = this.inputs.attached["gamepad"];
  76123. if (gamepad)
  76124. gamepad.gamepadMoveSensibility = value;
  76125. },
  76126. enumerable: true,
  76127. configurable: true
  76128. });
  76129. UniversalCamera.prototype.getClassName = function () {
  76130. return "UniversalCamera";
  76131. };
  76132. return UniversalCamera;
  76133. }(BABYLON.TouchCamera));
  76134. BABYLON.UniversalCamera = UniversalCamera;
  76135. })(BABYLON || (BABYLON = {}));
  76136. //# sourceMappingURL=babylon.universalCamera.js.map
  76137. var BABYLON;
  76138. (function (BABYLON) {
  76139. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  76140. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  76141. });
  76142. // We're mainly based on the logic defined into the FreeCamera code
  76143. var GamepadCamera = /** @class */ (function (_super) {
  76144. __extends(GamepadCamera, _super);
  76145. //-- end properties for backward compatibility for inputs
  76146. function GamepadCamera(name, position, scene) {
  76147. return _super.call(this, name, position, scene) || this;
  76148. }
  76149. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  76150. //-- Begin properties for backward compatibility for inputs
  76151. get: function () {
  76152. var gamepad = this.inputs.attached["gamepad"];
  76153. if (gamepad)
  76154. return gamepad.gamepadAngularSensibility;
  76155. return 0;
  76156. },
  76157. set: function (value) {
  76158. var gamepad = this.inputs.attached["gamepad"];
  76159. if (gamepad)
  76160. gamepad.gamepadAngularSensibility = value;
  76161. },
  76162. enumerable: true,
  76163. configurable: true
  76164. });
  76165. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  76166. get: function () {
  76167. var gamepad = this.inputs.attached["gamepad"];
  76168. if (gamepad)
  76169. return gamepad.gamepadMoveSensibility;
  76170. return 0;
  76171. },
  76172. set: function (value) {
  76173. var gamepad = this.inputs.attached["gamepad"];
  76174. if (gamepad)
  76175. gamepad.gamepadMoveSensibility = value;
  76176. },
  76177. enumerable: true,
  76178. configurable: true
  76179. });
  76180. GamepadCamera.prototype.getClassName = function () {
  76181. return "GamepadCamera";
  76182. };
  76183. return GamepadCamera;
  76184. }(BABYLON.UniversalCamera));
  76185. BABYLON.GamepadCamera = GamepadCamera;
  76186. })(BABYLON || (BABYLON = {}));
  76187. //# sourceMappingURL=babylon.gamepadCamera.js.map
  76188. var BABYLON;
  76189. (function (BABYLON) {
  76190. var PostProcessRenderPipelineManager = /** @class */ (function () {
  76191. function PostProcessRenderPipelineManager() {
  76192. this._renderPipelines = {};
  76193. }
  76194. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  76195. this._renderPipelines[renderPipeline._name] = renderPipeline;
  76196. };
  76197. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  76198. if (unique === void 0) { unique = false; }
  76199. var renderPipeline = this._renderPipelines[renderPipelineName];
  76200. if (!renderPipeline) {
  76201. return;
  76202. }
  76203. renderPipeline._attachCameras(cameras, unique);
  76204. };
  76205. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  76206. var renderPipeline = this._renderPipelines[renderPipelineName];
  76207. if (!renderPipeline) {
  76208. return;
  76209. }
  76210. renderPipeline._detachCameras(cameras);
  76211. };
  76212. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  76213. var renderPipeline = this._renderPipelines[renderPipelineName];
  76214. if (!renderPipeline) {
  76215. return;
  76216. }
  76217. renderPipeline._enableEffect(renderEffectName, cameras);
  76218. };
  76219. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  76220. var renderPipeline = this._renderPipelines[renderPipelineName];
  76221. if (!renderPipeline) {
  76222. return;
  76223. }
  76224. renderPipeline._disableEffect(renderEffectName, cameras);
  76225. };
  76226. PostProcessRenderPipelineManager.prototype.update = function () {
  76227. for (var renderPipelineName in this._renderPipelines) {
  76228. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  76229. var pipeline = this._renderPipelines[renderPipelineName];
  76230. if (!pipeline.isSupported) {
  76231. pipeline.dispose();
  76232. delete this._renderPipelines[renderPipelineName];
  76233. }
  76234. else {
  76235. pipeline._update();
  76236. }
  76237. }
  76238. }
  76239. };
  76240. /** @hidden */
  76241. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  76242. for (var renderPipelineName in this._renderPipelines) {
  76243. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  76244. var pipeline = this._renderPipelines[renderPipelineName];
  76245. pipeline._rebuild();
  76246. }
  76247. }
  76248. };
  76249. PostProcessRenderPipelineManager.prototype.dispose = function () {
  76250. for (var renderPipelineName in this._renderPipelines) {
  76251. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  76252. var pipeline = this._renderPipelines[renderPipelineName];
  76253. pipeline.dispose();
  76254. }
  76255. }
  76256. };
  76257. return PostProcessRenderPipelineManager;
  76258. }());
  76259. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  76260. })(BABYLON || (BABYLON = {}));
  76261. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  76262. var BABYLON;
  76263. (function (BABYLON) {
  76264. Object.defineProperty(BABYLON.Scene.prototype, "postProcessRenderPipelineManager", {
  76265. get: function () {
  76266. if (!this._postProcessRenderPipelineManager) {
  76267. // Register the G Buffer component to the scene.
  76268. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);
  76269. if (!component) {
  76270. component = new PostProcessRenderPipelineManagerSceneComponent(this);
  76271. this._addComponent(component);
  76272. }
  76273. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  76274. }
  76275. return this._postProcessRenderPipelineManager;
  76276. },
  76277. enumerable: true,
  76278. configurable: true
  76279. });
  76280. /**
  76281. * Defines the Render Pipeline scene component responsible to rendering pipelines
  76282. */
  76283. var PostProcessRenderPipelineManagerSceneComponent = /** @class */ (function () {
  76284. /**
  76285. * Creates a new instance of the component for the given scene
  76286. * @param scene Defines the scene to register the component in
  76287. */
  76288. function PostProcessRenderPipelineManagerSceneComponent(scene) {
  76289. /**
  76290. * The component name helpfull to identify the component in the list of scene components.
  76291. */
  76292. this.name = BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER;
  76293. this.scene = scene;
  76294. }
  76295. /**
  76296. * Registers the component in a given scene
  76297. */
  76298. PostProcessRenderPipelineManagerSceneComponent.prototype.register = function () {
  76299. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets);
  76300. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_REBUILDGEOMETRY_POSTPROCESSRENDERPIPELINEMANAGER, this, this._rebuildGeometry);
  76301. };
  76302. /**
  76303. * Rebuilds the elements related to this component in case of
  76304. * context lost for instance.
  76305. */
  76306. PostProcessRenderPipelineManagerSceneComponent.prototype.rebuild = function () {
  76307. // Nothing to do for this component
  76308. };
  76309. /**
  76310. * Disposes the component and the associated ressources
  76311. */
  76312. PostProcessRenderPipelineManagerSceneComponent.prototype.dispose = function () {
  76313. if (this.scene._postProcessRenderPipelineManager) {
  76314. this.scene._postProcessRenderPipelineManager.dispose();
  76315. }
  76316. };
  76317. PostProcessRenderPipelineManagerSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  76318. if (this.scene._postProcessRenderPipelineManager) {
  76319. this.scene._postProcessRenderPipelineManager.update();
  76320. }
  76321. };
  76322. PostProcessRenderPipelineManagerSceneComponent.prototype._rebuildGeometry = function () {
  76323. if (this.scene._postProcessRenderPipelineManager) {
  76324. this.scene._postProcessRenderPipelineManager._rebuild();
  76325. }
  76326. };
  76327. return PostProcessRenderPipelineManagerSceneComponent;
  76328. }());
  76329. BABYLON.PostProcessRenderPipelineManagerSceneComponent = PostProcessRenderPipelineManagerSceneComponent;
  76330. })(BABYLON || (BABYLON = {}));
  76331. //# sourceMappingURL=babylon.postProcessRenderPipelineManagerSceneComponent.js.map
  76332. var BABYLON;
  76333. (function (BABYLON) {
  76334. /**
  76335. * This represents a set of one or more post processes in Babylon.
  76336. * A post process can be used to apply a shader to a texture after it is rendered.
  76337. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  76338. */
  76339. var PostProcessRenderEffect = /** @class */ (function () {
  76340. /**
  76341. * Instantiates a post process render effect.
  76342. * A post process can be used to apply a shader to a texture after it is rendered.
  76343. * @param engine The engine the effect is tied to
  76344. * @param name The name of the effect
  76345. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  76346. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  76347. */
  76348. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  76349. this._name = name;
  76350. this._singleInstance = singleInstance || true;
  76351. this._getPostProcesses = getPostProcesses;
  76352. this._cameras = {};
  76353. this._indicesForCamera = {};
  76354. this._postProcesses = {};
  76355. }
  76356. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  76357. /**
  76358. * Checks if all the post processes in the effect are supported.
  76359. */
  76360. get: function () {
  76361. for (var index in this._postProcesses) {
  76362. if (this._postProcesses.hasOwnProperty(index)) {
  76363. var pps = this._postProcesses[index];
  76364. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  76365. if (!pps[ppIndex].isSupported) {
  76366. return false;
  76367. }
  76368. }
  76369. }
  76370. }
  76371. return true;
  76372. },
  76373. enumerable: true,
  76374. configurable: true
  76375. });
  76376. /**
  76377. * Updates the current state of the effect
  76378. * @hidden
  76379. */
  76380. PostProcessRenderEffect.prototype._update = function () {
  76381. };
  76382. /**
  76383. * Attaches the effect on cameras
  76384. * @param cameras The camera to attach to.
  76385. * @hidden
  76386. */
  76387. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  76388. var _this = this;
  76389. var cameraKey;
  76390. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  76391. if (!cams) {
  76392. return;
  76393. }
  76394. for (var i = 0; i < cams.length; i++) {
  76395. var camera = cams[i];
  76396. var cameraName = camera.name;
  76397. if (this._singleInstance) {
  76398. cameraKey = 0;
  76399. }
  76400. else {
  76401. cameraKey = cameraName;
  76402. }
  76403. if (!this._postProcesses[cameraKey]) {
  76404. var postProcess = this._getPostProcesses();
  76405. if (postProcess) {
  76406. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  76407. }
  76408. }
  76409. if (!this._indicesForCamera[cameraName]) {
  76410. this._indicesForCamera[cameraName] = [];
  76411. }
  76412. this._postProcesses[cameraKey].forEach(function (postProcess) {
  76413. var index = camera.attachPostProcess(postProcess);
  76414. _this._indicesForCamera[cameraName].push(index);
  76415. });
  76416. if (!this._cameras[cameraName]) {
  76417. this._cameras[cameraName] = camera;
  76418. }
  76419. }
  76420. };
  76421. /**
  76422. * Detatches the effect on cameras
  76423. * @param cameras The camera to detatch from.
  76424. * @hidden
  76425. */
  76426. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  76427. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  76428. if (!cams) {
  76429. return;
  76430. }
  76431. for (var i = 0; i < cams.length; i++) {
  76432. var camera = cams[i];
  76433. var cameraName = camera.name;
  76434. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  76435. camera.detachPostProcess(postProcess);
  76436. });
  76437. if (this._cameras[cameraName]) {
  76438. //this._indicesForCamera.splice(index, 1);
  76439. this._cameras[cameraName] = null;
  76440. }
  76441. }
  76442. };
  76443. /**
  76444. * Enables the effect on given cameras
  76445. * @param cameras The camera to enable.
  76446. * @hidden
  76447. */
  76448. PostProcessRenderEffect.prototype._enable = function (cameras) {
  76449. var _this = this;
  76450. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  76451. if (!cams) {
  76452. return;
  76453. }
  76454. for (var i = 0; i < cams.length; i++) {
  76455. var camera = cams[i];
  76456. var cameraName = camera.name;
  76457. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  76458. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  76459. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  76460. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  76461. });
  76462. }
  76463. }
  76464. }
  76465. };
  76466. /**
  76467. * Disables the effect on the given cameras
  76468. * @param cameras The camera to disable.
  76469. * @hidden
  76470. */
  76471. PostProcessRenderEffect.prototype._disable = function (cameras) {
  76472. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  76473. if (!cams) {
  76474. return;
  76475. }
  76476. for (var i = 0; i < cams.length; i++) {
  76477. var camera = cams[i];
  76478. var cameraName = camera.name;
  76479. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  76480. camera.detachPostProcess(postProcess);
  76481. });
  76482. }
  76483. };
  76484. /**
  76485. * Gets a list of the post processes contained in the effect.
  76486. * @param camera The camera to get the post processes on.
  76487. * @returns The list of the post processes in the effect.
  76488. */
  76489. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  76490. if (this._singleInstance) {
  76491. return this._postProcesses[0];
  76492. }
  76493. else {
  76494. if (!camera) {
  76495. return null;
  76496. }
  76497. return this._postProcesses[camera.name];
  76498. }
  76499. };
  76500. return PostProcessRenderEffect;
  76501. }());
  76502. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  76503. })(BABYLON || (BABYLON = {}));
  76504. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  76505. var BABYLON;
  76506. (function (BABYLON) {
  76507. var PostProcessRenderPipeline = /** @class */ (function () {
  76508. function PostProcessRenderPipeline(engine, name) {
  76509. this.engine = engine;
  76510. this._name = name;
  76511. this._renderEffects = {};
  76512. this._renderEffectsForIsolatedPass = new Array();
  76513. this._cameras = [];
  76514. }
  76515. PostProcessRenderPipeline.prototype.getClassName = function () {
  76516. return "PostProcessRenderPipeline";
  76517. };
  76518. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  76519. get: function () {
  76520. for (var renderEffectName in this._renderEffects) {
  76521. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  76522. if (!this._renderEffects[renderEffectName].isSupported) {
  76523. return false;
  76524. }
  76525. }
  76526. }
  76527. return true;
  76528. },
  76529. enumerable: true,
  76530. configurable: true
  76531. });
  76532. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  76533. this._renderEffects[renderEffect._name] = renderEffect;
  76534. };
  76535. // private
  76536. /** @hidden */
  76537. PostProcessRenderPipeline.prototype._rebuild = function () {
  76538. };
  76539. /** @hidden */
  76540. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  76541. var renderEffects = this._renderEffects[renderEffectName];
  76542. if (!renderEffects) {
  76543. return;
  76544. }
  76545. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  76546. };
  76547. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  76548. var renderEffects = this._renderEffects[renderEffectName];
  76549. if (!renderEffects) {
  76550. return;
  76551. }
  76552. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  76553. };
  76554. /** @hidden */
  76555. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  76556. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  76557. if (!cams) {
  76558. return;
  76559. }
  76560. var indicesToDelete = [];
  76561. var i;
  76562. for (i = 0; i < cams.length; i++) {
  76563. var camera = cams[i];
  76564. var cameraName = camera.name;
  76565. if (this._cameras.indexOf(camera) === -1) {
  76566. this._cameras[cameraName] = camera;
  76567. }
  76568. else if (unique) {
  76569. indicesToDelete.push(i);
  76570. }
  76571. }
  76572. for (i = 0; i < indicesToDelete.length; i++) {
  76573. cameras.splice(indicesToDelete[i], 1);
  76574. }
  76575. for (var renderEffectName in this._renderEffects) {
  76576. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  76577. this._renderEffects[renderEffectName]._attachCameras(cams);
  76578. }
  76579. }
  76580. };
  76581. /** @hidden */
  76582. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  76583. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  76584. if (!cams) {
  76585. return;
  76586. }
  76587. for (var renderEffectName in this._renderEffects) {
  76588. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  76589. this._renderEffects[renderEffectName]._detachCameras(cams);
  76590. }
  76591. }
  76592. for (var i = 0; i < cams.length; i++) {
  76593. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  76594. }
  76595. };
  76596. /** @hidden */
  76597. PostProcessRenderPipeline.prototype._update = function () {
  76598. for (var renderEffectName in this._renderEffects) {
  76599. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  76600. this._renderEffects[renderEffectName]._update();
  76601. }
  76602. }
  76603. for (var i = 0; i < this._cameras.length; i++) {
  76604. var cameraName = this._cameras[i].name;
  76605. if (this._renderEffectsForIsolatedPass[cameraName]) {
  76606. this._renderEffectsForIsolatedPass[cameraName]._update();
  76607. }
  76608. }
  76609. };
  76610. /** @hidden */
  76611. PostProcessRenderPipeline.prototype._reset = function () {
  76612. this._renderEffects = {};
  76613. this._renderEffectsForIsolatedPass = new Array();
  76614. };
  76615. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  76616. // 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)
  76617. var effectKeys = Object.keys(this._renderEffects);
  76618. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  76619. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  76620. if (postProcesses) {
  76621. postProcesses[0].samples = sampleCount;
  76622. return true;
  76623. }
  76624. }
  76625. return false;
  76626. };
  76627. PostProcessRenderPipeline.prototype.dispose = function () {
  76628. // Must be implemented by children
  76629. };
  76630. __decorate([
  76631. BABYLON.serialize()
  76632. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  76633. return PostProcessRenderPipeline;
  76634. }());
  76635. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  76636. })(BABYLON || (BABYLON = {}));
  76637. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  76638. var BABYLON;
  76639. (function (BABYLON) {
  76640. /**
  76641. * This represents a depth renderer in Babylon.
  76642. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  76643. */
  76644. var DepthRenderer = /** @class */ (function () {
  76645. /**
  76646. * Instantiates a depth renderer
  76647. * @param scene The scene the renderer belongs to
  76648. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  76649. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  76650. */
  76651. function DepthRenderer(scene, type, camera) {
  76652. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  76653. if (camera === void 0) { camera = null; }
  76654. var _this = this;
  76655. this._scene = scene;
  76656. // Register the G Buffer component to the scene.
  76657. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER);
  76658. if (!component) {
  76659. component = new BABYLON.DepthRendererSceneComponent(scene);
  76660. scene._addComponent(component);
  76661. }
  76662. this._camera = camera;
  76663. var engine = scene.getEngine();
  76664. // Render target
  76665. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  76666. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76667. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76668. this._depthMap.refreshRate = 1;
  76669. this._depthMap.renderParticles = false;
  76670. this._depthMap.renderList = null;
  76671. // Camera to get depth map from to support multiple concurrent cameras
  76672. this._depthMap.activeCamera = this._camera;
  76673. this._depthMap.ignoreCameraViewport = true;
  76674. this._depthMap.useCameraPostProcesses = false;
  76675. // set default depth value to 1.0 (far away)
  76676. this._depthMap.onClearObservable.add(function (engine) {
  76677. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  76678. });
  76679. // Custom render function
  76680. var renderSubMesh = function (subMesh) {
  76681. var mesh = subMesh.getRenderingMesh();
  76682. var scene = _this._scene;
  76683. var engine = scene.getEngine();
  76684. var material = subMesh.getMaterial();
  76685. if (!material) {
  76686. return;
  76687. }
  76688. // Culling and reverse (right handed system)
  76689. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  76690. // Managing instances
  76691. var batch = mesh._getInstancesRenderList(subMesh._id);
  76692. if (batch.mustReturn) {
  76693. return;
  76694. }
  76695. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76696. var camera = _this._camera || scene.activeCamera;
  76697. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  76698. engine.enableEffect(_this._effect);
  76699. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  76700. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76701. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  76702. // Alpha test
  76703. if (material && material.needAlphaTesting()) {
  76704. var alphaTexture = material.getAlphaTestTexture();
  76705. if (alphaTexture) {
  76706. _this._effect.setTexture("diffuseSampler", alphaTexture);
  76707. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76708. }
  76709. }
  76710. // Bones
  76711. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76712. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76713. }
  76714. // Draw
  76715. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76716. }
  76717. };
  76718. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76719. var index;
  76720. if (depthOnlySubMeshes.length) {
  76721. engine.setColorWrite(false);
  76722. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76723. renderSubMesh(depthOnlySubMeshes.data[index]);
  76724. }
  76725. engine.setColorWrite(true);
  76726. }
  76727. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76728. renderSubMesh(opaqueSubMeshes.data[index]);
  76729. }
  76730. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76731. renderSubMesh(alphaTestSubMeshes.data[index]);
  76732. }
  76733. };
  76734. }
  76735. /**
  76736. * Creates the depth rendering effect and checks if the effect is ready.
  76737. * @param subMesh The submesh to be used to render the depth map of
  76738. * @param useInstances If multiple world instances should be used
  76739. * @returns if the depth renderer is ready to render the depth map
  76740. */
  76741. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  76742. var material = subMesh.getMaterial();
  76743. if (material.disableDepthWrite) {
  76744. return false;
  76745. }
  76746. var defines = [];
  76747. var attribs = [BABYLON.VertexBuffer.PositionKind];
  76748. var mesh = subMesh.getMesh();
  76749. // Alpha test
  76750. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  76751. defines.push("#define ALPHATEST");
  76752. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76753. attribs.push(BABYLON.VertexBuffer.UVKind);
  76754. defines.push("#define UV1");
  76755. }
  76756. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76757. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76758. defines.push("#define UV2");
  76759. }
  76760. }
  76761. // Bones
  76762. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76763. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76764. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76765. if (mesh.numBoneInfluencers > 4) {
  76766. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76767. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76768. }
  76769. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76770. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76771. }
  76772. else {
  76773. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76774. }
  76775. // Instances
  76776. if (useInstances) {
  76777. defines.push("#define INSTANCES");
  76778. attribs.push("world0");
  76779. attribs.push("world1");
  76780. attribs.push("world2");
  76781. attribs.push("world3");
  76782. }
  76783. // Get correct effect
  76784. var join = defines.join("\n");
  76785. if (this._cachedDefines !== join) {
  76786. this._cachedDefines = join;
  76787. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  76788. }
  76789. return this._effect.isReady();
  76790. };
  76791. /**
  76792. * Gets the texture which the depth map will be written to.
  76793. * @returns The depth map texture
  76794. */
  76795. DepthRenderer.prototype.getDepthMap = function () {
  76796. return this._depthMap;
  76797. };
  76798. /**
  76799. * Disposes of the depth renderer.
  76800. */
  76801. DepthRenderer.prototype.dispose = function () {
  76802. this._depthMap.dispose();
  76803. };
  76804. return DepthRenderer;
  76805. }());
  76806. BABYLON.DepthRenderer = DepthRenderer;
  76807. })(BABYLON || (BABYLON = {}));
  76808. //# sourceMappingURL=babylon.depthRenderer.js.map
  76809. var BABYLON;
  76810. (function (BABYLON) {
  76811. BABYLON.Scene.prototype.enableDepthRenderer = function (camera) {
  76812. camera = camera || this.activeCamera;
  76813. if (!camera) {
  76814. throw "No camera available to enable depth renderer";
  76815. }
  76816. if (!this._depthRenderer) {
  76817. this._depthRenderer = {};
  76818. }
  76819. if (!this._depthRenderer[camera.id]) {
  76820. var textureType = 0;
  76821. if (this.getEngine().getCaps().textureHalfFloatRender) {
  76822. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  76823. }
  76824. else if (this.getEngine().getCaps().textureFloatRender) {
  76825. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76826. }
  76827. else {
  76828. throw "Depth renderer does not support int texture type";
  76829. }
  76830. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  76831. }
  76832. return this._depthRenderer[camera.id];
  76833. };
  76834. BABYLON.Scene.prototype.disableDepthRenderer = function (camera) {
  76835. camera = camera || this.activeCamera;
  76836. if (!camera || !this._depthRenderer || !this._depthRenderer[camera.id]) {
  76837. return;
  76838. }
  76839. this._depthRenderer[camera.id].dispose();
  76840. delete this._depthRenderer[camera.id];
  76841. };
  76842. /**
  76843. * Defines the Depth Renderer scene component responsible to manage a depth buffer usefull
  76844. * in several rendering techniques.
  76845. */
  76846. var DepthRendererSceneComponent = /** @class */ (function () {
  76847. /**
  76848. * Creates a new instance of the component for the given scene
  76849. * @param scene Defines the scene to register the component in
  76850. */
  76851. function DepthRendererSceneComponent(scene) {
  76852. /**
  76853. * The component name helpfull to identify the component in the list of scene components.
  76854. */
  76855. this.name = BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER;
  76856. this.scene = scene;
  76857. }
  76858. /**
  76859. * Registers the component in a given scene
  76860. */
  76861. DepthRendererSceneComponent.prototype.register = function () {
  76862. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets);
  76863. };
  76864. /**
  76865. * Rebuilds the elements related to this component in case of
  76866. * context lost for instance.
  76867. */
  76868. DepthRendererSceneComponent.prototype.rebuild = function () {
  76869. // Nothing to do for this component
  76870. };
  76871. /**
  76872. * Disposes the component and the associated ressources
  76873. */
  76874. DepthRendererSceneComponent.prototype.dispose = function () {
  76875. for (var key in this.scene._depthRenderer) {
  76876. this.scene._depthRenderer[key].dispose();
  76877. }
  76878. };
  76879. DepthRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  76880. if (this.scene._depthRenderer) {
  76881. for (var key in this.scene._depthRenderer) {
  76882. renderTargets.push(this.scene._depthRenderer[key].getDepthMap());
  76883. }
  76884. }
  76885. };
  76886. return DepthRendererSceneComponent;
  76887. }());
  76888. BABYLON.DepthRendererSceneComponent = DepthRendererSceneComponent;
  76889. })(BABYLON || (BABYLON = {}));
  76890. //# sourceMappingURL=babylon.depthRendererSceneComponent.js.map
  76891. var BABYLON;
  76892. (function (BABYLON) {
  76893. /**
  76894. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  76895. */
  76896. var GeometryBufferRenderer = /** @class */ (function () {
  76897. /**
  76898. * Creates a new G Buffer for the scene
  76899. * @param scene The scene the buffer belongs to
  76900. * @param ratio How big is the buffer related to the main canvas.
  76901. */
  76902. function GeometryBufferRenderer(scene, ratio) {
  76903. if (ratio === void 0) { ratio = 1; }
  76904. this._enablePosition = false;
  76905. this._scene = scene;
  76906. this._ratio = ratio;
  76907. // Register the G Buffer component to the scene.
  76908. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER);
  76909. if (!component) {
  76910. component = new BABYLON.GeometryBufferRendererSceneComponent(scene);
  76911. scene._addComponent(component);
  76912. }
  76913. // Render target
  76914. this._createRenderTargets();
  76915. }
  76916. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  76917. /**
  76918. * Set the render list (meshes to be rendered) used in the G buffer.
  76919. */
  76920. set: function (meshes) {
  76921. this._multiRenderTarget.renderList = meshes;
  76922. },
  76923. enumerable: true,
  76924. configurable: true
  76925. });
  76926. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  76927. /**
  76928. * Gets wether or not G buffer are supported by the running hardware.
  76929. * This requires draw buffer supports
  76930. */
  76931. get: function () {
  76932. return this._multiRenderTarget.isSupported;
  76933. },
  76934. enumerable: true,
  76935. configurable: true
  76936. });
  76937. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  76938. /**
  76939. * Gets wether or not position are enabled for the G buffer.
  76940. */
  76941. get: function () {
  76942. return this._enablePosition;
  76943. },
  76944. /**
  76945. * Sets wether or not position are enabled for the G buffer.
  76946. */
  76947. set: function (enable) {
  76948. this._enablePosition = enable;
  76949. this.dispose();
  76950. this._createRenderTargets();
  76951. },
  76952. enumerable: true,
  76953. configurable: true
  76954. });
  76955. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  76956. /**
  76957. * Gets the scene associated with the buffer.
  76958. */
  76959. get: function () {
  76960. return this._scene;
  76961. },
  76962. enumerable: true,
  76963. configurable: true
  76964. });
  76965. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  76966. /**
  76967. * Gets the ratio used by the buffer during its creation.
  76968. * How big is the buffer related to the main canvas.
  76969. */
  76970. get: function () {
  76971. return this._ratio;
  76972. },
  76973. enumerable: true,
  76974. configurable: true
  76975. });
  76976. /**
  76977. * Checks wether everything is ready to render a submesh to the G buffer.
  76978. * @param subMesh the submesh to check readiness for
  76979. * @param useInstances is the mesh drawn using instance or not
  76980. * @returns true if ready otherwise false
  76981. */
  76982. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  76983. var material = subMesh.getMaterial();
  76984. if (material && material.disableDepthWrite) {
  76985. return false;
  76986. }
  76987. var defines = [];
  76988. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76989. var mesh = subMesh.getMesh();
  76990. // Alpha test
  76991. if (material && material.needAlphaTesting()) {
  76992. defines.push("#define ALPHATEST");
  76993. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76994. attribs.push(BABYLON.VertexBuffer.UVKind);
  76995. defines.push("#define UV1");
  76996. }
  76997. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76998. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76999. defines.push("#define UV2");
  77000. }
  77001. }
  77002. // Buffers
  77003. if (this._enablePosition) {
  77004. defines.push("#define POSITION");
  77005. }
  77006. // Bones
  77007. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  77008. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77009. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77010. if (mesh.numBoneInfluencers > 4) {
  77011. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  77012. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  77013. }
  77014. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77015. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  77016. }
  77017. else {
  77018. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77019. }
  77020. // Instances
  77021. if (useInstances) {
  77022. defines.push("#define INSTANCES");
  77023. attribs.push("world0");
  77024. attribs.push("world1");
  77025. attribs.push("world2");
  77026. attribs.push("world3");
  77027. }
  77028. // Get correct effect
  77029. var join = defines.join("\n");
  77030. if (this._cachedDefines !== join) {
  77031. this._cachedDefines = join;
  77032. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  77033. }
  77034. return this._effect.isReady();
  77035. };
  77036. /**
  77037. * Gets the current underlying G Buffer.
  77038. * @returns the buffer
  77039. */
  77040. GeometryBufferRenderer.prototype.getGBuffer = function () {
  77041. return this._multiRenderTarget;
  77042. };
  77043. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  77044. /**
  77045. * Gets the number of samples used to render the buffer (anti aliasing).
  77046. */
  77047. get: function () {
  77048. return this._multiRenderTarget.samples;
  77049. },
  77050. /**
  77051. * Sets the number of samples used to render the buffer (anti aliasing).
  77052. */
  77053. set: function (value) {
  77054. this._multiRenderTarget.samples = value;
  77055. },
  77056. enumerable: true,
  77057. configurable: true
  77058. });
  77059. /**
  77060. * Disposes the renderer and frees up associated resources.
  77061. */
  77062. GeometryBufferRenderer.prototype.dispose = function () {
  77063. this.getGBuffer().dispose();
  77064. };
  77065. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  77066. var _this = this;
  77067. var engine = this._scene.getEngine();
  77068. var count = this._enablePosition ? 3 : 2;
  77069. 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 });
  77070. if (!this.isSupported) {
  77071. return;
  77072. }
  77073. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77074. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77075. this._multiRenderTarget.refreshRate = 1;
  77076. this._multiRenderTarget.renderParticles = false;
  77077. this._multiRenderTarget.renderList = null;
  77078. // set default depth value to 1.0 (far away)
  77079. this._multiRenderTarget.onClearObservable.add(function (engine) {
  77080. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  77081. });
  77082. // Custom render function
  77083. var renderSubMesh = function (subMesh) {
  77084. var mesh = subMesh.getRenderingMesh();
  77085. var scene = _this._scene;
  77086. var engine = scene.getEngine();
  77087. var material = subMesh.getMaterial();
  77088. if (!material) {
  77089. return;
  77090. }
  77091. // Culling
  77092. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  77093. // Managing instances
  77094. var batch = mesh._getInstancesRenderList(subMesh._id);
  77095. if (batch.mustReturn) {
  77096. return;
  77097. }
  77098. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  77099. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  77100. engine.enableEffect(_this._effect);
  77101. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  77102. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  77103. _this._effect.setMatrix("view", scene.getViewMatrix());
  77104. // Alpha test
  77105. if (material && material.needAlphaTesting()) {
  77106. var alphaTexture = material.getAlphaTestTexture();
  77107. if (alphaTexture) {
  77108. _this._effect.setTexture("diffuseSampler", alphaTexture);
  77109. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  77110. }
  77111. }
  77112. // Bones
  77113. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77114. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77115. }
  77116. // Draw
  77117. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  77118. }
  77119. };
  77120. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77121. var index;
  77122. if (depthOnlySubMeshes.length) {
  77123. engine.setColorWrite(false);
  77124. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77125. renderSubMesh(depthOnlySubMeshes.data[index]);
  77126. }
  77127. engine.setColorWrite(true);
  77128. }
  77129. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77130. renderSubMesh(opaqueSubMeshes.data[index]);
  77131. }
  77132. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77133. renderSubMesh(alphaTestSubMeshes.data[index]);
  77134. }
  77135. };
  77136. };
  77137. return GeometryBufferRenderer;
  77138. }());
  77139. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  77140. })(BABYLON || (BABYLON = {}));
  77141. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  77142. var BABYLON;
  77143. (function (BABYLON) {
  77144. Object.defineProperty(BABYLON.Scene.prototype, "geometryBufferRenderer", {
  77145. get: function () {
  77146. this._geometryBufferRenderer;
  77147. },
  77148. set: function (value) {
  77149. if (value && value.isSupported) {
  77150. this._geometryBufferRenderer = value;
  77151. }
  77152. ;
  77153. },
  77154. enumerable: true,
  77155. configurable: true
  77156. });
  77157. BABYLON.Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  77158. if (ratio === void 0) { ratio = 1; }
  77159. if (this._geometryBufferRenderer) {
  77160. return this._geometryBufferRenderer;
  77161. }
  77162. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  77163. if (!this._geometryBufferRenderer.isSupported) {
  77164. this._geometryBufferRenderer = null;
  77165. }
  77166. return this._geometryBufferRenderer;
  77167. };
  77168. BABYLON.Scene.prototype.disableGeometryBufferRenderer = function () {
  77169. if (!this._geometryBufferRenderer) {
  77170. return;
  77171. }
  77172. this._geometryBufferRenderer.dispose();
  77173. this._geometryBufferRenderer = null;
  77174. };
  77175. /**
  77176. * Defines the Geometry Buffer scene component responsible to manage a G-Buffer usefull
  77177. * in several rendering techniques.
  77178. */
  77179. var GeometryBufferRendererSceneComponent = /** @class */ (function () {
  77180. /**
  77181. * Creates a new instance of the component for the given scene
  77182. * @param scene Defines the scene to register the component in
  77183. */
  77184. function GeometryBufferRendererSceneComponent(scene) {
  77185. /**
  77186. * The component name helpfull to identify the component in the list of scene components.
  77187. */
  77188. this.name = BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER;
  77189. this.scene = scene;
  77190. }
  77191. /**
  77192. * Registers the component in a given scene
  77193. */
  77194. GeometryBufferRendererSceneComponent.prototype.register = function () {
  77195. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets);
  77196. };
  77197. /**
  77198. * Rebuilds the elements related to this component in case of
  77199. * context lost for instance.
  77200. */
  77201. GeometryBufferRendererSceneComponent.prototype.rebuild = function () {
  77202. // Nothing to do for this component
  77203. };
  77204. /**
  77205. * Disposes the component and the associated ressources
  77206. */
  77207. GeometryBufferRendererSceneComponent.prototype.dispose = function () {
  77208. // Nothing to do for this component
  77209. };
  77210. GeometryBufferRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  77211. if (this.scene._geometryBufferRenderer) {
  77212. renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer());
  77213. }
  77214. };
  77215. return GeometryBufferRendererSceneComponent;
  77216. }());
  77217. BABYLON.GeometryBufferRendererSceneComponent = GeometryBufferRendererSceneComponent;
  77218. })(BABYLON || (BABYLON = {}));
  77219. //# sourceMappingURL=babylon.geometryBufferRendererSceneComponent.js.map
  77220. var BABYLON;
  77221. (function (BABYLON) {
  77222. var SSAORenderingPipeline = /** @class */ (function (_super) {
  77223. __extends(SSAORenderingPipeline, _super);
  77224. /**
  77225. * @constructor
  77226. * @param {string} name - The rendering pipeline name
  77227. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  77228. * @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 }
  77229. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  77230. */
  77231. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  77232. var _this = _super.call(this, scene.getEngine(), name) || this;
  77233. // Members
  77234. /**
  77235. * The PassPostProcess id in the pipeline that contains the original scene color
  77236. */
  77237. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  77238. /**
  77239. * The SSAO PostProcess id in the pipeline
  77240. */
  77241. _this.SSAORenderEffect = "SSAORenderEffect";
  77242. /**
  77243. * The horizontal blur PostProcess id in the pipeline
  77244. */
  77245. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  77246. /**
  77247. * The vertical blur PostProcess id in the pipeline
  77248. */
  77249. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  77250. /**
  77251. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  77252. */
  77253. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  77254. /**
  77255. * The output strength of the SSAO post-process. Default value is 1.0.
  77256. */
  77257. _this.totalStrength = 1.0;
  77258. /**
  77259. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  77260. */
  77261. _this.radius = 0.0001;
  77262. /**
  77263. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  77264. * Must not be equal to fallOff and superior to fallOff.
  77265. * Default value is 0.975
  77266. */
  77267. _this.area = 0.0075;
  77268. /**
  77269. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  77270. * Must not be equal to area and inferior to area.
  77271. * Default value is 0.0
  77272. */
  77273. _this.fallOff = 0.000001;
  77274. /**
  77275. * The base color of the SSAO post-process
  77276. * The final result is "base + ssao" between [0, 1]
  77277. */
  77278. _this.base = 0.5;
  77279. _this._firstUpdate = true;
  77280. _this._scene = scene;
  77281. // Set up assets
  77282. _this._createRandomTexture();
  77283. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  77284. var ssaoRatio = ratio.ssaoRatio || ratio;
  77285. var combineRatio = ratio.combineRatio || ratio;
  77286. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  77287. _this._createSSAOPostProcess(ssaoRatio);
  77288. _this._createBlurPostProcess(ssaoRatio);
  77289. _this._createSSAOCombinePostProcess(combineRatio);
  77290. // Set up pipeline
  77291. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  77292. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  77293. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  77294. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  77295. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  77296. // Finish
  77297. scene.postProcessRenderPipelineManager.addPipeline(_this);
  77298. if (cameras)
  77299. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  77300. return _this;
  77301. }
  77302. // Public Methods
  77303. /**
  77304. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  77305. */
  77306. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  77307. if (disableDepthRender === void 0) { disableDepthRender = false; }
  77308. for (var i = 0; i < this._scene.cameras.length; i++) {
  77309. var camera = this._scene.cameras[i];
  77310. this._originalColorPostProcess.dispose(camera);
  77311. this._ssaoPostProcess.dispose(camera);
  77312. this._blurHPostProcess.dispose(camera);
  77313. this._blurVPostProcess.dispose(camera);
  77314. this._ssaoCombinePostProcess.dispose(camera);
  77315. }
  77316. this._randomTexture.dispose();
  77317. if (disableDepthRender)
  77318. this._scene.disableDepthRenderer();
  77319. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  77320. _super.prototype.dispose.call(this);
  77321. };
  77322. // Private Methods
  77323. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  77324. var _this = this;
  77325. var size = 16;
  77326. 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);
  77327. 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);
  77328. this._blurHPostProcess.onActivateObservable.add(function () {
  77329. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  77330. _this._blurHPostProcess.kernel = size * dw;
  77331. });
  77332. this._blurVPostProcess.onActivateObservable.add(function () {
  77333. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  77334. _this._blurVPostProcess.kernel = size * dw;
  77335. });
  77336. };
  77337. /** @hidden */
  77338. SSAORenderingPipeline.prototype._rebuild = function () {
  77339. this._firstUpdate = true;
  77340. _super.prototype._rebuild.call(this);
  77341. };
  77342. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  77343. var _this = this;
  77344. var numSamples = 16;
  77345. var sampleSphere = [
  77346. 0.5381, 0.1856, -0.4319,
  77347. 0.1379, 0.2486, 0.4430,
  77348. 0.3371, 0.5679, -0.0057,
  77349. -0.6999, -0.0451, -0.0019,
  77350. 0.0689, -0.1598, -0.8547,
  77351. 0.0560, 0.0069, -0.1843,
  77352. -0.0146, 0.1402, 0.0762,
  77353. 0.0100, -0.1924, -0.0344,
  77354. -0.3577, -0.5301, -0.4358,
  77355. -0.3169, 0.1063, 0.0158,
  77356. 0.0103, -0.5869, 0.0046,
  77357. -0.0897, -0.4940, 0.3287,
  77358. 0.7119, -0.0154, -0.0918,
  77359. -0.0533, 0.0596, -0.5411,
  77360. 0.0352, -0.0631, 0.5460,
  77361. -0.4776, 0.2847, -0.0271
  77362. ];
  77363. var samplesFactor = 1.0 / numSamples;
  77364. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  77365. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  77366. "area", "fallOff", "base", "range", "viewport"
  77367. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  77368. this._ssaoPostProcess.onApply = function (effect) {
  77369. if (_this._firstUpdate) {
  77370. effect.setArray3("sampleSphere", sampleSphere);
  77371. effect.setFloat("samplesFactor", samplesFactor);
  77372. effect.setFloat("randTextureTiles", 4.0);
  77373. }
  77374. effect.setFloat("totalStrength", _this.totalStrength);
  77375. effect.setFloat("radius", _this.radius);
  77376. effect.setFloat("area", _this.area);
  77377. effect.setFloat("fallOff", _this.fallOff);
  77378. effect.setFloat("base", _this.base);
  77379. effect.setTexture("textureSampler", _this._depthTexture);
  77380. effect.setTexture("randomSampler", _this._randomTexture);
  77381. };
  77382. };
  77383. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  77384. var _this = this;
  77385. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  77386. this._ssaoCombinePostProcess.onApply = function (effect) {
  77387. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  77388. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  77389. };
  77390. };
  77391. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  77392. var size = 512;
  77393. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  77394. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  77395. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  77396. var context = this._randomTexture.getContext();
  77397. var rand = function (min, max) {
  77398. return Math.random() * (max - min) + min;
  77399. };
  77400. var randVector = BABYLON.Vector3.Zero();
  77401. for (var x = 0; x < size; x++) {
  77402. for (var y = 0; y < size; y++) {
  77403. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  77404. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  77405. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  77406. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  77407. context.fillRect(x, y, 1, 1);
  77408. }
  77409. }
  77410. this._randomTexture.update(false);
  77411. };
  77412. __decorate([
  77413. BABYLON.serialize()
  77414. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  77415. __decorate([
  77416. BABYLON.serialize()
  77417. ], SSAORenderingPipeline.prototype, "radius", void 0);
  77418. __decorate([
  77419. BABYLON.serialize()
  77420. ], SSAORenderingPipeline.prototype, "area", void 0);
  77421. __decorate([
  77422. BABYLON.serialize()
  77423. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  77424. __decorate([
  77425. BABYLON.serialize()
  77426. ], SSAORenderingPipeline.prototype, "base", void 0);
  77427. return SSAORenderingPipeline;
  77428. }(BABYLON.PostProcessRenderPipeline));
  77429. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  77430. })(BABYLON || (BABYLON = {}));
  77431. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  77432. var BABYLON;
  77433. (function (BABYLON) {
  77434. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  77435. __extends(SSAO2RenderingPipeline, _super);
  77436. /**
  77437. * @constructor
  77438. * @param {string} name - The rendering pipeline name
  77439. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  77440. * @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 }
  77441. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  77442. */
  77443. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  77444. var _this = _super.call(this, scene.getEngine(), name) || this;
  77445. // Members
  77446. /**
  77447. * The PassPostProcess id in the pipeline that contains the original scene color
  77448. */
  77449. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  77450. /**
  77451. * The SSAO PostProcess id in the pipeline
  77452. */
  77453. _this.SSAORenderEffect = "SSAORenderEffect";
  77454. /**
  77455. * The horizontal blur PostProcess id in the pipeline
  77456. */
  77457. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  77458. /**
  77459. * The vertical blur PostProcess id in the pipeline
  77460. */
  77461. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  77462. /**
  77463. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  77464. */
  77465. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  77466. /**
  77467. * The output strength of the SSAO post-process. Default value is 1.0.
  77468. */
  77469. _this.totalStrength = 1.0;
  77470. /**
  77471. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  77472. */
  77473. _this.maxZ = 100.0;
  77474. /**
  77475. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  77476. */
  77477. _this.minZAspect = 0.2;
  77478. _this._samples = 8;
  77479. _this._textureSamples = 1;
  77480. /**
  77481. * Are we using bilateral blur ?
  77482. */
  77483. _this._expensiveBlur = true;
  77484. /**
  77485. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  77486. */
  77487. _this.radius = 2.0;
  77488. /**
  77489. * The base color of the SSAO post-process
  77490. * The final result is "base + ssao" between [0, 1]
  77491. */
  77492. _this.base = 0;
  77493. _this._firstUpdate = true;
  77494. _this._bits = new Uint32Array(1);
  77495. _this._scene = scene;
  77496. _this._ratio = ratio;
  77497. if (!_this.isSupported) {
  77498. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  77499. return _this;
  77500. }
  77501. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  77502. var blurRatio = _this._ratio.blurRatio || ratio;
  77503. // Set up assets
  77504. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  77505. _this._createRandomTexture();
  77506. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  77507. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  77508. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  77509. _this._originalColorPostProcess.samples = _this.textureSamples;
  77510. _this._createSSAOPostProcess(1.0);
  77511. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  77512. _this._createSSAOCombinePostProcess(blurRatio);
  77513. // Set up pipeline
  77514. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  77515. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  77516. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  77517. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  77518. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  77519. // Finish
  77520. scene.postProcessRenderPipelineManager.addPipeline(_this);
  77521. if (cameras)
  77522. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  77523. return _this;
  77524. }
  77525. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  77526. get: function () {
  77527. return this._samples;
  77528. },
  77529. /**
  77530. * Number of samples used for the SSAO calculations. Default value is 8
  77531. */
  77532. set: function (n) {
  77533. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  77534. this._samples = n;
  77535. this._sampleSphere = this._generateHemisphere();
  77536. this._firstUpdate = true;
  77537. },
  77538. enumerable: true,
  77539. configurable: true
  77540. });
  77541. Object.defineProperty(SSAO2RenderingPipeline.prototype, "textureSamples", {
  77542. get: function () {
  77543. return this._textureSamples;
  77544. },
  77545. /**
  77546. * Number of samples to use for antialiasing
  77547. */
  77548. set: function (n) {
  77549. this._textureSamples = n;
  77550. this._originalColorPostProcess.samples = n;
  77551. this._blurHPostProcess.samples = n;
  77552. this._blurVPostProcess.samples = n;
  77553. this._ssaoPostProcess.samples = n;
  77554. this._ssaoCombinePostProcess.samples = n;
  77555. },
  77556. enumerable: true,
  77557. configurable: true
  77558. });
  77559. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  77560. get: function () {
  77561. return this._expensiveBlur;
  77562. },
  77563. set: function (b) {
  77564. 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"]);
  77565. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  77566. this._expensiveBlur = b;
  77567. this._firstUpdate = true;
  77568. },
  77569. enumerable: true,
  77570. configurable: true
  77571. });
  77572. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  77573. /**
  77574. * Support test.
  77575. */
  77576. get: function () {
  77577. var engine = BABYLON.Engine.LastCreatedEngine;
  77578. if (!engine) {
  77579. return false;
  77580. }
  77581. return engine.getCaps().drawBuffersExtension;
  77582. },
  77583. enumerable: true,
  77584. configurable: true
  77585. });
  77586. // Public Methods
  77587. /**
  77588. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  77589. */
  77590. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  77591. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  77592. for (var i = 0; i < this._scene.cameras.length; i++) {
  77593. var camera = this._scene.cameras[i];
  77594. this._originalColorPostProcess.dispose(camera);
  77595. this._ssaoPostProcess.dispose(camera);
  77596. this._blurHPostProcess.dispose(camera);
  77597. this._blurVPostProcess.dispose(camera);
  77598. this._ssaoCombinePostProcess.dispose(camera);
  77599. }
  77600. this._randomTexture.dispose();
  77601. if (disableGeometryBufferRenderer)
  77602. this._scene.disableGeometryBufferRenderer();
  77603. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  77604. _super.prototype.dispose.call(this);
  77605. };
  77606. // Private Methods
  77607. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  77608. var _this = this;
  77609. this._samplerOffsets = [];
  77610. var expensive = this.expensiveBlur;
  77611. for (var i = -8; i < 8; i++) {
  77612. this._samplerOffsets.push(i * 2 + 0.5);
  77613. }
  77614. 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");
  77615. this._blurHPostProcess.onApply = function (effect) {
  77616. if (!_this._scene.activeCamera) {
  77617. return;
  77618. }
  77619. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  77620. effect.setFloat("near", _this._scene.activeCamera.minZ);
  77621. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  77622. effect.setFloat("radius", _this.radius);
  77623. effect.setTexture("depthSampler", _this._depthTexture);
  77624. if (_this._firstUpdate) {
  77625. effect.setArray("samplerOffsets", _this._samplerOffsets);
  77626. }
  77627. };
  77628. 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");
  77629. this._blurVPostProcess.onApply = function (effect) {
  77630. if (!_this._scene.activeCamera) {
  77631. return;
  77632. }
  77633. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  77634. effect.setFloat("near", _this._scene.activeCamera.minZ);
  77635. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  77636. effect.setFloat("radius", _this.radius);
  77637. effect.setTexture("depthSampler", _this._depthTexture);
  77638. if (_this._firstUpdate) {
  77639. effect.setArray("samplerOffsets", _this._samplerOffsets);
  77640. _this._firstUpdate = false;
  77641. }
  77642. };
  77643. this._blurHPostProcess.samples = this.textureSamples;
  77644. this._blurVPostProcess.samples = this.textureSamples;
  77645. };
  77646. /** @hidden */
  77647. SSAO2RenderingPipeline.prototype._rebuild = function () {
  77648. this._firstUpdate = true;
  77649. _super.prototype._rebuild.call(this);
  77650. };
  77651. //Van der Corput radical inverse
  77652. SSAO2RenderingPipeline.prototype._radicalInverse_VdC = function (i) {
  77653. this._bits[0] = i;
  77654. this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0;
  77655. this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | ((this._bits[0] & 0xAAAAAAAA) >>> 1) >>> 0;
  77656. this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | ((this._bits[0] & 0xCCCCCCCC) >>> 2) >>> 0;
  77657. this._bits[0] = ((this._bits[0] & 0x0F0F0F0F) << 4) | ((this._bits[0] & 0xF0F0F0F0) >>> 4) >>> 0;
  77658. this._bits[0] = ((this._bits[0] & 0x00FF00FF) << 8) | ((this._bits[0] & 0xFF00FF00) >>> 8) >>> 0;
  77659. return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296
  77660. };
  77661. SSAO2RenderingPipeline.prototype._hammersley = function (i, n) {
  77662. return [i / n, this._radicalInverse_VdC(i)];
  77663. };
  77664. SSAO2RenderingPipeline.prototype._hemisphereSample_uniform = function (u, v) {
  77665. var phi = v * 2.0 * Math.PI;
  77666. // rejecting samples that are close to tangent plane to avoid z-fighting artifacts
  77667. var cosTheta = 1.0 - (u * 0.85 + 0.15);
  77668. var sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta);
  77669. return new BABYLON.Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);
  77670. };
  77671. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  77672. var numSamples = this.samples;
  77673. var result = [];
  77674. var vector;
  77675. var i = 0;
  77676. while (i < numSamples) {
  77677. if (numSamples < 16) {
  77678. vector = this._hemisphereSample_uniform(Math.random(), Math.random());
  77679. }
  77680. else {
  77681. var rand = this._hammersley(i, numSamples);
  77682. vector = this._hemisphereSample_uniform(rand[0], rand[1]);
  77683. }
  77684. result.push(vector.x, vector.y, vector.z);
  77685. i++;
  77686. }
  77687. return result;
  77688. };
  77689. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  77690. var _this = this;
  77691. var numSamples = this.samples;
  77692. this._sampleSphere = this._generateHemisphere();
  77693. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  77694. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  77695. "base", "range", "projection", "near", "far", "texelSize",
  77696. "xViewport", "yViewport", "maxZ", "minZAspect"
  77697. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  77698. this._ssaoPostProcess.onApply = function (effect) {
  77699. if (_this._firstUpdate) {
  77700. effect.setArray3("sampleSphere", _this._sampleSphere);
  77701. effect.setFloat("randTextureTiles", 32.0);
  77702. }
  77703. if (!_this._scene.activeCamera) {
  77704. return;
  77705. }
  77706. effect.setFloat("samplesFactor", 1 / _this.samples);
  77707. effect.setFloat("totalStrength", _this.totalStrength);
  77708. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  77709. effect.setFloat("radius", _this.radius);
  77710. effect.setFloat("maxZ", _this.maxZ);
  77711. effect.setFloat("minZAspect", _this.minZAspect);
  77712. effect.setFloat("base", _this.base);
  77713. effect.setFloat("near", _this._scene.activeCamera.minZ);
  77714. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  77715. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  77716. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  77717. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  77718. effect.setTexture("textureSampler", _this._depthTexture);
  77719. effect.setTexture("normalSampler", _this._normalTexture);
  77720. effect.setTexture("randomSampler", _this._randomTexture);
  77721. };
  77722. this._ssaoPostProcess.samples = this.textureSamples;
  77723. };
  77724. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  77725. var _this = this;
  77726. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  77727. this._ssaoCombinePostProcess.onApply = function (effect) {
  77728. var viewport = _this._scene.activeCamera.viewport;
  77729. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  77730. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  77731. };
  77732. this._ssaoCombinePostProcess.samples = this.textureSamples;
  77733. };
  77734. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  77735. var size = 128;
  77736. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  77737. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  77738. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  77739. var context = this._randomTexture.getContext();
  77740. var rand = function (min, max) {
  77741. return Math.random() * (max - min) + min;
  77742. };
  77743. var randVector = BABYLON.Vector3.Zero();
  77744. for (var x = 0; x < size; x++) {
  77745. for (var y = 0; y < size; y++) {
  77746. randVector.x = rand(0.0, 1.0);
  77747. randVector.y = rand(0.0, 1.0);
  77748. randVector.z = 0.0;
  77749. randVector.normalize();
  77750. randVector.scaleInPlace(255);
  77751. randVector.x = Math.floor(randVector.x);
  77752. randVector.y = Math.floor(randVector.y);
  77753. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  77754. context.fillRect(x, y, 1, 1);
  77755. }
  77756. }
  77757. this._randomTexture.update(false);
  77758. };
  77759. /**
  77760. * Serialize the rendering pipeline (Used when exporting)
  77761. * @returns the serialized object
  77762. */
  77763. SSAO2RenderingPipeline.prototype.serialize = function () {
  77764. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  77765. serializationObject.customType = "SSAO2RenderingPipeline";
  77766. return serializationObject;
  77767. };
  77768. /**
  77769. * Parse the serialized pipeline
  77770. * @param source Source pipeline.
  77771. * @param scene The scene to load the pipeline to.
  77772. * @param rootUrl The URL of the serialized pipeline.
  77773. * @returns An instantiated pipeline from the serialized object.
  77774. */
  77775. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  77776. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  77777. };
  77778. __decorate([
  77779. BABYLON.serialize()
  77780. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  77781. __decorate([
  77782. BABYLON.serialize()
  77783. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  77784. __decorate([
  77785. BABYLON.serialize()
  77786. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  77787. __decorate([
  77788. BABYLON.serialize("samples")
  77789. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  77790. __decorate([
  77791. BABYLON.serialize("textureSamples")
  77792. ], SSAO2RenderingPipeline.prototype, "_textureSamples", void 0);
  77793. __decorate([
  77794. BABYLON.serialize()
  77795. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  77796. __decorate([
  77797. BABYLON.serialize("expensiveBlur")
  77798. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  77799. __decorate([
  77800. BABYLON.serialize()
  77801. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  77802. __decorate([
  77803. BABYLON.serialize()
  77804. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  77805. return SSAO2RenderingPipeline;
  77806. }(BABYLON.PostProcessRenderPipeline));
  77807. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  77808. })(BABYLON || (BABYLON = {}));
  77809. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  77810. // BABYLON.JS Chromatic Aberration GLSL Shader
  77811. // Author: Olivier Guyot
  77812. // Separates very slightly R, G and B colors on the edges of the screen
  77813. // Inspired by Francois Tarlier & Martins Upitis
  77814. var BABYLON;
  77815. (function (BABYLON) {
  77816. var LensRenderingPipeline = /** @class */ (function (_super) {
  77817. __extends(LensRenderingPipeline, _super);
  77818. /**
  77819. * @constructor
  77820. *
  77821. * Effect parameters are as follow:
  77822. * {
  77823. * chromatic_aberration: number; // from 0 to x (1 for realism)
  77824. * edge_blur: number; // from 0 to x (1 for realism)
  77825. * distortion: number; // from 0 to x (1 for realism)
  77826. * grain_amount: number; // from 0 to 1
  77827. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  77828. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  77829. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  77830. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  77831. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  77832. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  77833. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  77834. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  77835. * }
  77836. * Note: if an effect parameter is unset, effect is disabled
  77837. *
  77838. * @param {string} name - The rendering pipeline name
  77839. * @param {object} parameters - An object containing all parameters (see above)
  77840. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  77841. * @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)
  77842. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  77843. */
  77844. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  77845. if (ratio === void 0) { ratio = 1.0; }
  77846. var _this = _super.call(this, scene.getEngine(), name) || this;
  77847. // Lens effects can be of the following:
  77848. // - chromatic aberration (slight shift of RGB colors)
  77849. // - blur on the edge of the lens
  77850. // - lens distortion
  77851. // - depth-of-field blur & highlights enhancing
  77852. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  77853. // - grain effect (noise or custom texture)
  77854. // Two additional texture samplers are needed:
  77855. // - depth map (for depth-of-field)
  77856. // - grain texture
  77857. /**
  77858. * The chromatic aberration PostProcess id in the pipeline
  77859. */
  77860. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  77861. /**
  77862. * The highlights enhancing PostProcess id in the pipeline
  77863. */
  77864. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  77865. /**
  77866. * The depth-of-field PostProcess id in the pipeline
  77867. */
  77868. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  77869. _this._scene = scene;
  77870. // Fetch texture samplers
  77871. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  77872. if (parameters.grain_texture) {
  77873. _this._grainTexture = parameters.grain_texture;
  77874. }
  77875. else {
  77876. _this._createGrainTexture();
  77877. }
  77878. // save parameters
  77879. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  77880. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  77881. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  77882. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  77883. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  77884. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  77885. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  77886. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  77887. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  77888. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  77889. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  77890. // Create effects
  77891. _this._createChromaticAberrationPostProcess(ratio);
  77892. _this._createHighlightsPostProcess(ratio);
  77893. _this._createDepthOfFieldPostProcess(ratio / 4);
  77894. // Set up pipeline
  77895. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  77896. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  77897. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  77898. if (_this._highlightsGain === -1) {
  77899. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  77900. }
  77901. // Finish
  77902. scene.postProcessRenderPipelineManager.addPipeline(_this);
  77903. if (cameras) {
  77904. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  77905. }
  77906. return _this;
  77907. }
  77908. // public methods (self explanatory)
  77909. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  77910. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  77911. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  77912. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  77913. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  77914. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  77915. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  77916. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  77917. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  77918. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  77919. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  77920. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  77921. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  77922. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  77923. };
  77924. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  77925. this._highlightsPostProcess.updateEffect();
  77926. };
  77927. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  77928. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  77929. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  77930. this._highlightsGain = amount;
  77931. };
  77932. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  77933. if (this._highlightsGain === -1) {
  77934. this._highlightsGain = 1.0;
  77935. }
  77936. this._highlightsThreshold = amount;
  77937. };
  77938. LensRenderingPipeline.prototype.disableHighlights = function () {
  77939. this._highlightsGain = -1;
  77940. };
  77941. /**
  77942. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  77943. */
  77944. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  77945. if (disableDepthRender === void 0) { disableDepthRender = false; }
  77946. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  77947. this._chromaticAberrationPostProcess = null;
  77948. this._highlightsPostProcess = null;
  77949. this._depthOfFieldPostProcess = null;
  77950. this._grainTexture.dispose();
  77951. if (disableDepthRender)
  77952. this._scene.disableDepthRenderer();
  77953. };
  77954. // colors shifting and distortion
  77955. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  77956. var _this = this;
  77957. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  77958. [], // samplers
  77959. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  77960. this._chromaticAberrationPostProcess.onApply = function (effect) {
  77961. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  77962. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  77963. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  77964. effect.setFloat('radialIntensity', 1);
  77965. effect.setFloat2('direction', 17, 17);
  77966. effect.setFloat2('centerPosition', 0.5, 0.5);
  77967. };
  77968. };
  77969. // highlights enhancing
  77970. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  77971. var _this = this;
  77972. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  77973. [], // samplers
  77974. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  77975. this._highlightsPostProcess.onApply = function (effect) {
  77976. effect.setFloat('gain', _this._highlightsGain);
  77977. effect.setFloat('threshold', _this._highlightsThreshold);
  77978. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  77979. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  77980. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  77981. };
  77982. };
  77983. // colors shifting and distortion
  77984. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  77985. var _this = this;
  77986. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  77987. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  77988. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  77989. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  77990. this._depthOfFieldPostProcess.onApply = function (effect) {
  77991. effect.setTexture("depthSampler", _this._depthTexture);
  77992. effect.setTexture("grainSampler", _this._grainTexture);
  77993. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  77994. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  77995. effect.setFloat('grain_amount', _this._grainAmount);
  77996. effect.setBool('blur_noise', _this._blurNoise);
  77997. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  77998. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  77999. effect.setFloat('distortion', _this._distortion);
  78000. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  78001. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  78002. effect.setFloat('aperture', _this._dofAperture);
  78003. effect.setFloat('darken', _this._dofDarken);
  78004. effect.setFloat('edge_blur', _this._edgeBlur);
  78005. effect.setBool('highlights', (_this._highlightsGain !== -1));
  78006. if (_this._scene.activeCamera) {
  78007. effect.setFloat('near', _this._scene.activeCamera.minZ);
  78008. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  78009. }
  78010. };
  78011. };
  78012. // creates a black and white random noise texture, 512x512
  78013. LensRenderingPipeline.prototype._createGrainTexture = function () {
  78014. var size = 512;
  78015. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  78016. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  78017. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  78018. var context = this._grainTexture.getContext();
  78019. var rand = function (min, max) {
  78020. return Math.random() * (max - min) + min;
  78021. };
  78022. var value;
  78023. for (var x = 0; x < size; x++) {
  78024. for (var y = 0; y < size; y++) {
  78025. value = Math.floor(rand(0.42, 0.58) * 255);
  78026. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  78027. context.fillRect(x, y, 1, 1);
  78028. }
  78029. }
  78030. this._grainTexture.update(false);
  78031. };
  78032. return LensRenderingPipeline;
  78033. }(BABYLON.PostProcessRenderPipeline));
  78034. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  78035. })(BABYLON || (BABYLON = {}));
  78036. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  78037. var BABYLON;
  78038. (function (BABYLON) {
  78039. var StandardRenderingPipeline = /** @class */ (function (_super) {
  78040. __extends(StandardRenderingPipeline, _super);
  78041. /**
  78042. * @constructor
  78043. * @param {string} name - The rendering pipeline name
  78044. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  78045. * @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)
  78046. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  78047. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  78048. */
  78049. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  78050. if (originalPostProcess === void 0) { originalPostProcess = null; }
  78051. var _this = _super.call(this, scene.getEngine(), name) || this;
  78052. _this.downSampleX4PostProcess = null;
  78053. _this.brightPassPostProcess = null;
  78054. _this.blurHPostProcesses = [];
  78055. _this.blurVPostProcesses = [];
  78056. _this.textureAdderPostProcess = null;
  78057. _this.volumetricLightPostProcess = null;
  78058. _this.volumetricLightSmoothXPostProcess = null;
  78059. _this.volumetricLightSmoothYPostProcess = null;
  78060. _this.volumetricLightMergePostProces = null;
  78061. _this.volumetricLightFinalPostProcess = null;
  78062. _this.luminancePostProcess = null;
  78063. _this.luminanceDownSamplePostProcesses = [];
  78064. _this.hdrPostProcess = null;
  78065. _this.textureAdderFinalPostProcess = null;
  78066. _this.lensFlareFinalPostProcess = null;
  78067. _this.hdrFinalPostProcess = null;
  78068. _this.lensFlarePostProcess = null;
  78069. _this.lensFlareComposePostProcess = null;
  78070. _this.motionBlurPostProcess = null;
  78071. _this.depthOfFieldPostProcess = null;
  78072. // Values
  78073. _this.brightThreshold = 1.0;
  78074. _this.blurWidth = 512.0;
  78075. _this.horizontalBlur = false;
  78076. _this.exposure = 1.0;
  78077. _this.lensTexture = null;
  78078. _this.volumetricLightCoefficient = 0.2;
  78079. _this.volumetricLightPower = 4.0;
  78080. _this.volumetricLightBlurScale = 64.0;
  78081. _this.sourceLight = null;
  78082. _this.hdrMinimumLuminance = 1.0;
  78083. _this.hdrDecreaseRate = 0.5;
  78084. _this.hdrIncreaseRate = 0.5;
  78085. _this.lensColorTexture = null;
  78086. _this.lensFlareStrength = 20.0;
  78087. _this.lensFlareGhostDispersal = 1.4;
  78088. _this.lensFlareHaloWidth = 0.7;
  78089. _this.lensFlareDistortionStrength = 16.0;
  78090. _this.lensStarTexture = null;
  78091. _this.lensFlareDirtTexture = null;
  78092. _this.depthOfFieldDistance = 10.0;
  78093. _this.depthOfFieldBlurWidth = 64.0;
  78094. _this.motionStrength = 1.0;
  78095. // IAnimatable
  78096. _this.animations = [];
  78097. _this._currentDepthOfFieldSource = null;
  78098. _this._hdrCurrentLuminance = 1.0;
  78099. // Getters and setters
  78100. _this._bloomEnabled = true;
  78101. _this._depthOfFieldEnabled = false;
  78102. _this._vlsEnabled = false;
  78103. _this._lensFlareEnabled = false;
  78104. _this._hdrEnabled = false;
  78105. _this._motionBlurEnabled = false;
  78106. _this._motionBlurSamples = 64.0;
  78107. _this._volumetricLightStepsCount = 50.0;
  78108. _this._cameras = cameras || [];
  78109. // Initialize
  78110. _this._scene = scene;
  78111. _this._basePostProcess = originalPostProcess;
  78112. _this._ratio = ratio;
  78113. // Misc
  78114. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  78115. // Finish
  78116. scene.postProcessRenderPipelineManager.addPipeline(_this);
  78117. _this._buildPipeline();
  78118. return _this;
  78119. }
  78120. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  78121. get: function () {
  78122. return this._bloomEnabled;
  78123. },
  78124. set: function (enabled) {
  78125. if (this._bloomEnabled === enabled) {
  78126. return;
  78127. }
  78128. this._bloomEnabled = enabled;
  78129. this._buildPipeline();
  78130. },
  78131. enumerable: true,
  78132. configurable: true
  78133. });
  78134. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  78135. get: function () {
  78136. return this._depthOfFieldEnabled;
  78137. },
  78138. set: function (enabled) {
  78139. if (this._depthOfFieldEnabled === enabled) {
  78140. return;
  78141. }
  78142. this._depthOfFieldEnabled = enabled;
  78143. this._buildPipeline();
  78144. },
  78145. enumerable: true,
  78146. configurable: true
  78147. });
  78148. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  78149. get: function () {
  78150. return this._lensFlareEnabled;
  78151. },
  78152. set: function (enabled) {
  78153. if (this._lensFlareEnabled === enabled) {
  78154. return;
  78155. }
  78156. this._lensFlareEnabled = enabled;
  78157. this._buildPipeline();
  78158. },
  78159. enumerable: true,
  78160. configurable: true
  78161. });
  78162. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  78163. get: function () {
  78164. return this._hdrEnabled;
  78165. },
  78166. set: function (enabled) {
  78167. if (this._hdrEnabled === enabled) {
  78168. return;
  78169. }
  78170. this._hdrEnabled = enabled;
  78171. this._buildPipeline();
  78172. },
  78173. enumerable: true,
  78174. configurable: true
  78175. });
  78176. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  78177. get: function () {
  78178. return this._vlsEnabled;
  78179. },
  78180. set: function (enabled) {
  78181. if (this._vlsEnabled === enabled) {
  78182. return;
  78183. }
  78184. if (enabled) {
  78185. var geometry = this._scene.enableGeometryBufferRenderer();
  78186. if (!geometry) {
  78187. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  78188. return;
  78189. }
  78190. }
  78191. this._vlsEnabled = enabled;
  78192. this._buildPipeline();
  78193. },
  78194. enumerable: true,
  78195. configurable: true
  78196. });
  78197. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  78198. get: function () {
  78199. return this._motionBlurEnabled;
  78200. },
  78201. set: function (enabled) {
  78202. if (this._motionBlurEnabled === enabled) {
  78203. return;
  78204. }
  78205. this._motionBlurEnabled = enabled;
  78206. this._buildPipeline();
  78207. },
  78208. enumerable: true,
  78209. configurable: true
  78210. });
  78211. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  78212. get: function () {
  78213. return this._volumetricLightStepsCount;
  78214. },
  78215. set: function (count) {
  78216. if (this.volumetricLightPostProcess) {
  78217. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  78218. }
  78219. this._volumetricLightStepsCount = count;
  78220. },
  78221. enumerable: true,
  78222. configurable: true
  78223. });
  78224. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  78225. get: function () {
  78226. return this._motionBlurSamples;
  78227. },
  78228. set: function (samples) {
  78229. if (this.motionBlurPostProcess) {
  78230. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  78231. }
  78232. this._motionBlurSamples = samples;
  78233. },
  78234. enumerable: true,
  78235. configurable: true
  78236. });
  78237. StandardRenderingPipeline.prototype._buildPipeline = function () {
  78238. var _this = this;
  78239. var ratio = this._ratio;
  78240. var scene = this._scene;
  78241. this._disposePostProcesses();
  78242. this._reset();
  78243. // Create pass post-process
  78244. if (!this._basePostProcess) {
  78245. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  78246. this.originalPostProcess.onApply = function (effect) {
  78247. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  78248. };
  78249. }
  78250. else {
  78251. this.originalPostProcess = this._basePostProcess;
  78252. }
  78253. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  78254. this._currentDepthOfFieldSource = this.originalPostProcess;
  78255. if (this._bloomEnabled) {
  78256. // Create down sample X4 post-process
  78257. this._createDownSampleX4PostProcess(scene, ratio / 2);
  78258. // Create bright pass post-process
  78259. this._createBrightPassPostProcess(scene, ratio / 2);
  78260. // Create gaussian blur post-processes (down sampling blurs)
  78261. this._createBlurPostProcesses(scene, ratio / 4, 1);
  78262. // Create texture adder post-process
  78263. this._createTextureAdderPostProcess(scene, ratio);
  78264. // Create depth-of-field source post-process
  78265. 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);
  78266. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  78267. }
  78268. if (this._vlsEnabled) {
  78269. // Create volumetric light
  78270. this._createVolumetricLightPostProcess(scene, ratio);
  78271. // Create volumetric light final post-process
  78272. 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);
  78273. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  78274. }
  78275. if (this._lensFlareEnabled) {
  78276. // Create lens flare post-process
  78277. this._createLensFlarePostProcess(scene, ratio);
  78278. // Create depth-of-field source post-process post lens-flare and disable it now
  78279. 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);
  78280. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  78281. }
  78282. if (this._hdrEnabled) {
  78283. // Create luminance
  78284. this._createLuminancePostProcesses(scene, this._floatTextureType);
  78285. // Create HDR
  78286. this._createHdrPostProcess(scene, ratio);
  78287. // Create depth-of-field source post-process post hdr and disable it now
  78288. 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);
  78289. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  78290. }
  78291. if (this._depthOfFieldEnabled) {
  78292. // Create gaussian blur used by depth-of-field
  78293. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  78294. // Create depth-of-field post-process
  78295. this._createDepthOfFieldPostProcess(scene, ratio);
  78296. }
  78297. if (this._motionBlurEnabled) {
  78298. // Create motion blur post-process
  78299. this._createMotionBlurPostProcess(scene, ratio);
  78300. }
  78301. if (this._cameras !== null) {
  78302. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  78303. }
  78304. };
  78305. // Down Sample X4 Post-Processs
  78306. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  78307. var _this = this;
  78308. var downSampleX4Offsets = new Array(32);
  78309. 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);
  78310. this.downSampleX4PostProcess.onApply = function (effect) {
  78311. var id = 0;
  78312. var width = _this.downSampleX4PostProcess.width;
  78313. var height = _this.downSampleX4PostProcess.height;
  78314. for (var i = -2; i < 2; i++) {
  78315. for (var j = -2; j < 2; j++) {
  78316. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  78317. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  78318. id += 2;
  78319. }
  78320. }
  78321. effect.setArray2("dsOffsets", downSampleX4Offsets);
  78322. };
  78323. // Add to pipeline
  78324. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  78325. };
  78326. // Brightpass Post-Process
  78327. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  78328. var _this = this;
  78329. var brightOffsets = new Array(8);
  78330. 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);
  78331. this.brightPassPostProcess.onApply = function (effect) {
  78332. var sU = (1.0 / _this.brightPassPostProcess.width);
  78333. var sV = (1.0 / _this.brightPassPostProcess.height);
  78334. brightOffsets[0] = -0.5 * sU;
  78335. brightOffsets[1] = 0.5 * sV;
  78336. brightOffsets[2] = 0.5 * sU;
  78337. brightOffsets[3] = 0.5 * sV;
  78338. brightOffsets[4] = -0.5 * sU;
  78339. brightOffsets[5] = -0.5 * sV;
  78340. brightOffsets[6] = 0.5 * sU;
  78341. brightOffsets[7] = -0.5 * sV;
  78342. effect.setArray2("dsOffsets", brightOffsets);
  78343. effect.setFloat("brightThreshold", _this.brightThreshold);
  78344. };
  78345. // Add to pipeline
  78346. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  78347. };
  78348. // Create blur H&V post-processes
  78349. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  78350. var _this = this;
  78351. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  78352. var engine = scene.getEngine();
  78353. 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);
  78354. 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);
  78355. blurX.onActivateObservable.add(function () {
  78356. var dw = blurX.width / engine.getRenderWidth();
  78357. blurX.kernel = _this[blurWidthKey] * dw;
  78358. });
  78359. blurY.onActivateObservable.add(function () {
  78360. var dw = blurY.height / engine.getRenderHeight();
  78361. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  78362. });
  78363. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  78364. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  78365. this.blurHPostProcesses.push(blurX);
  78366. this.blurVPostProcesses.push(blurY);
  78367. };
  78368. // Create texture adder post-process
  78369. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  78370. var _this = this;
  78371. 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);
  78372. this.textureAdderPostProcess.onApply = function (effect) {
  78373. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  78374. effect.setTexture("lensSampler", _this.lensTexture);
  78375. effect.setFloat("exposure", _this.exposure);
  78376. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  78377. };
  78378. // Add to pipeline
  78379. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  78380. };
  78381. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  78382. var _this = this;
  78383. var geometryRenderer = scene.enableGeometryBufferRenderer();
  78384. geometryRenderer.enablePosition = true;
  78385. var geometry = geometryRenderer.getGBuffer();
  78386. // Base post-process
  78387. 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));
  78388. var depthValues = BABYLON.Vector2.Zero();
  78389. this.volumetricLightPostProcess.onApply = function (effect) {
  78390. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  78391. var generator = _this.sourceLight.getShadowGenerator();
  78392. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  78393. effect.setTexture("positionSampler", geometry.textures[2]);
  78394. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  78395. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  78396. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  78397. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  78398. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  78399. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  78400. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  78401. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  78402. effect.setVector2("depthValues", depthValues);
  78403. }
  78404. };
  78405. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  78406. // Smooth
  78407. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  78408. // Merge
  78409. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  78410. this.volumetricLightMergePostProces.onApply = function (effect) {
  78411. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  78412. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  78413. };
  78414. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  78415. };
  78416. // Create luminance
  78417. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  78418. var _this = this;
  78419. // Create luminance
  78420. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  78421. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  78422. var offsets = [];
  78423. this.luminancePostProcess.onApply = function (effect) {
  78424. var sU = (1.0 / _this.luminancePostProcess.width);
  78425. var sV = (1.0 / _this.luminancePostProcess.height);
  78426. offsets[0] = -0.5 * sU;
  78427. offsets[1] = 0.5 * sV;
  78428. offsets[2] = 0.5 * sU;
  78429. offsets[3] = 0.5 * sV;
  78430. offsets[4] = -0.5 * sU;
  78431. offsets[5] = -0.5 * sV;
  78432. offsets[6] = 0.5 * sU;
  78433. offsets[7] = -0.5 * sV;
  78434. effect.setArray2("lumOffsets", offsets);
  78435. };
  78436. // Add to pipeline
  78437. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  78438. // Create down sample luminance
  78439. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  78440. var size = Math.pow(3, i);
  78441. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  78442. if (i === 0) {
  78443. defines += "#define FINAL_DOWN_SAMPLER";
  78444. }
  78445. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  78446. this.luminanceDownSamplePostProcesses.push(postProcess);
  78447. }
  78448. // Create callbacks and add effects
  78449. var lastLuminance = this.luminancePostProcess;
  78450. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  78451. var downSampleOffsets = new Array(18);
  78452. pp.onApply = function (effect) {
  78453. if (!lastLuminance) {
  78454. return;
  78455. }
  78456. var id = 0;
  78457. for (var x = -1; x < 2; x++) {
  78458. for (var y = -1; y < 2; y++) {
  78459. downSampleOffsets[id] = x / lastLuminance.width;
  78460. downSampleOffsets[id + 1] = y / lastLuminance.height;
  78461. id += 2;
  78462. }
  78463. }
  78464. effect.setArray2("dsOffsets", downSampleOffsets);
  78465. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  78466. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  78467. lastLuminance = _this.luminancePostProcess;
  78468. }
  78469. else {
  78470. lastLuminance = pp;
  78471. }
  78472. };
  78473. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  78474. pp.onAfterRender = function (effect) {
  78475. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  78476. 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);
  78477. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  78478. };
  78479. }
  78480. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  78481. });
  78482. };
  78483. // Create HDR post-process
  78484. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  78485. var _this = this;
  78486. 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);
  78487. var outputLiminance = 1;
  78488. var time = 0;
  78489. var lastTime = 0;
  78490. this.hdrPostProcess.onApply = function (effect) {
  78491. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  78492. time += scene.getEngine().getDeltaTime();
  78493. if (outputLiminance < 0) {
  78494. outputLiminance = _this._hdrCurrentLuminance;
  78495. }
  78496. else {
  78497. var dt = (lastTime - time) / 1000.0;
  78498. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  78499. outputLiminance += _this.hdrDecreaseRate * dt;
  78500. }
  78501. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  78502. outputLiminance -= _this.hdrIncreaseRate * dt;
  78503. }
  78504. else {
  78505. outputLiminance = _this._hdrCurrentLuminance;
  78506. }
  78507. }
  78508. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  78509. effect.setFloat("averageLuminance", outputLiminance);
  78510. lastTime = time;
  78511. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  78512. };
  78513. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  78514. };
  78515. // Create lens flare post-process
  78516. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  78517. var _this = this;
  78518. 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);
  78519. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  78520. this._createBlurPostProcesses(scene, ratio / 4, 2);
  78521. 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);
  78522. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  78523. var resolution = new BABYLON.Vector2(0, 0);
  78524. // Lens flare
  78525. this.lensFlarePostProcess.onApply = function (effect) {
  78526. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  78527. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  78528. effect.setFloat("strength", _this.lensFlareStrength);
  78529. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  78530. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  78531. // Shift
  78532. resolution.x = _this.lensFlarePostProcess.width;
  78533. resolution.y = _this.lensFlarePostProcess.height;
  78534. effect.setVector2("resolution", resolution);
  78535. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  78536. };
  78537. // Compose
  78538. 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);
  78539. 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);
  78540. this.lensFlareComposePostProcess.onApply = function (effect) {
  78541. if (!_this._scene.activeCamera) {
  78542. return;
  78543. }
  78544. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  78545. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  78546. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  78547. // Lens start rotation matrix
  78548. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  78549. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  78550. 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));
  78551. camRot *= 4.0;
  78552. 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);
  78553. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  78554. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  78555. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  78556. };
  78557. };
  78558. // Create depth-of-field post-process
  78559. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  78560. var _this = this;
  78561. 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);
  78562. this.depthOfFieldPostProcess.onApply = function (effect) {
  78563. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  78564. effect.setTexture("depthSampler", _this._getDepthTexture());
  78565. effect.setFloat("distance", _this.depthOfFieldDistance);
  78566. };
  78567. // Add to pipeline
  78568. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  78569. };
  78570. // Create motion blur post-process
  78571. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  78572. var _this = this;
  78573. 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);
  78574. var motionScale = 0;
  78575. var prevViewProjection = BABYLON.Matrix.Identity();
  78576. var invViewProjection = BABYLON.Matrix.Identity();
  78577. var viewProjection = BABYLON.Matrix.Identity();
  78578. var screenSize = BABYLON.Vector2.Zero();
  78579. this.motionBlurPostProcess.onApply = function (effect) {
  78580. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  78581. viewProjection.invertToRef(invViewProjection);
  78582. effect.setMatrix("inverseViewProjection", invViewProjection);
  78583. effect.setMatrix("prevViewProjection", prevViewProjection);
  78584. prevViewProjection = viewProjection;
  78585. screenSize.x = _this.motionBlurPostProcess.width;
  78586. screenSize.y = _this.motionBlurPostProcess.height;
  78587. effect.setVector2("screenSize", screenSize);
  78588. motionScale = scene.getEngine().getFps() / 60.0;
  78589. effect.setFloat("motionScale", motionScale);
  78590. effect.setFloat("motionStrength", _this.motionStrength);
  78591. effect.setTexture("depthSampler", _this._getDepthTexture());
  78592. };
  78593. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  78594. };
  78595. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  78596. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  78597. var renderer = this._scene.enableGeometryBufferRenderer();
  78598. return renderer.getGBuffer().textures[0];
  78599. }
  78600. return this._scene.enableDepthRenderer().getDepthMap();
  78601. };
  78602. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  78603. for (var i = 0; i < this._cameras.length; i++) {
  78604. var camera = this._cameras[i];
  78605. if (this.originalPostProcess) {
  78606. this.originalPostProcess.dispose(camera);
  78607. }
  78608. if (this.downSampleX4PostProcess) {
  78609. this.downSampleX4PostProcess.dispose(camera);
  78610. }
  78611. if (this.brightPassPostProcess) {
  78612. this.brightPassPostProcess.dispose(camera);
  78613. }
  78614. if (this.textureAdderPostProcess) {
  78615. this.textureAdderPostProcess.dispose(camera);
  78616. }
  78617. if (this.textureAdderFinalPostProcess) {
  78618. this.textureAdderFinalPostProcess.dispose(camera);
  78619. }
  78620. if (this.volumetricLightPostProcess) {
  78621. this.volumetricLightPostProcess.dispose(camera);
  78622. }
  78623. if (this.volumetricLightSmoothXPostProcess) {
  78624. this.volumetricLightSmoothXPostProcess.dispose(camera);
  78625. }
  78626. if (this.volumetricLightSmoothYPostProcess) {
  78627. this.volumetricLightSmoothYPostProcess.dispose(camera);
  78628. }
  78629. if (this.volumetricLightMergePostProces) {
  78630. this.volumetricLightMergePostProces.dispose(camera);
  78631. }
  78632. if (this.volumetricLightFinalPostProcess) {
  78633. this.volumetricLightFinalPostProcess.dispose(camera);
  78634. }
  78635. if (this.lensFlarePostProcess) {
  78636. this.lensFlarePostProcess.dispose(camera);
  78637. }
  78638. if (this.lensFlareComposePostProcess) {
  78639. this.lensFlareComposePostProcess.dispose(camera);
  78640. }
  78641. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  78642. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  78643. }
  78644. if (this.luminancePostProcess) {
  78645. this.luminancePostProcess.dispose(camera);
  78646. }
  78647. if (this.hdrPostProcess) {
  78648. this.hdrPostProcess.dispose(camera);
  78649. }
  78650. if (this.hdrFinalPostProcess) {
  78651. this.hdrFinalPostProcess.dispose(camera);
  78652. }
  78653. if (this.depthOfFieldPostProcess) {
  78654. this.depthOfFieldPostProcess.dispose(camera);
  78655. }
  78656. if (this.motionBlurPostProcess) {
  78657. this.motionBlurPostProcess.dispose(camera);
  78658. }
  78659. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  78660. this.blurHPostProcesses[j].dispose(camera);
  78661. }
  78662. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  78663. this.blurVPostProcesses[j].dispose(camera);
  78664. }
  78665. }
  78666. this.originalPostProcess = null;
  78667. this.downSampleX4PostProcess = null;
  78668. this.brightPassPostProcess = null;
  78669. this.textureAdderPostProcess = null;
  78670. this.textureAdderFinalPostProcess = null;
  78671. this.volumetricLightPostProcess = null;
  78672. this.volumetricLightSmoothXPostProcess = null;
  78673. this.volumetricLightSmoothYPostProcess = null;
  78674. this.volumetricLightMergePostProces = null;
  78675. this.volumetricLightFinalPostProcess = null;
  78676. this.lensFlarePostProcess = null;
  78677. this.lensFlareComposePostProcess = null;
  78678. this.luminancePostProcess = null;
  78679. this.hdrPostProcess = null;
  78680. this.hdrFinalPostProcess = null;
  78681. this.depthOfFieldPostProcess = null;
  78682. this.motionBlurPostProcess = null;
  78683. this.luminanceDownSamplePostProcesses = [];
  78684. this.blurHPostProcesses = [];
  78685. this.blurVPostProcesses = [];
  78686. };
  78687. /**
  78688. * Dispose of the pipeline and stop all post processes
  78689. */
  78690. StandardRenderingPipeline.prototype.dispose = function () {
  78691. this._disposePostProcesses();
  78692. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  78693. _super.prototype.dispose.call(this);
  78694. };
  78695. /**
  78696. * Serialize the rendering pipeline (Used when exporting)
  78697. * @returns the serialized object
  78698. */
  78699. StandardRenderingPipeline.prototype.serialize = function () {
  78700. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  78701. if (this.sourceLight) {
  78702. serializationObject.sourceLightId = this.sourceLight.id;
  78703. }
  78704. serializationObject.customType = "StandardRenderingPipeline";
  78705. return serializationObject;
  78706. };
  78707. /**
  78708. * Parse the serialized pipeline
  78709. * @param source Source pipeline.
  78710. * @param scene The scene to load the pipeline to.
  78711. * @param rootUrl The URL of the serialized pipeline.
  78712. * @returns An instantiated pipeline from the serialized object.
  78713. */
  78714. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  78715. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  78716. if (source.sourceLightId) {
  78717. p.sourceLight = scene.getLightByID(source.sourceLightId);
  78718. }
  78719. return p;
  78720. };
  78721. // Luminance steps
  78722. StandardRenderingPipeline.LuminanceSteps = 6;
  78723. __decorate([
  78724. BABYLON.serialize()
  78725. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  78726. __decorate([
  78727. BABYLON.serialize()
  78728. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  78729. __decorate([
  78730. BABYLON.serialize()
  78731. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  78732. __decorate([
  78733. BABYLON.serialize()
  78734. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  78735. __decorate([
  78736. BABYLON.serializeAsTexture("lensTexture")
  78737. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  78738. __decorate([
  78739. BABYLON.serialize()
  78740. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  78741. __decorate([
  78742. BABYLON.serialize()
  78743. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  78744. __decorate([
  78745. BABYLON.serialize()
  78746. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  78747. __decorate([
  78748. BABYLON.serialize()
  78749. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  78750. __decorate([
  78751. BABYLON.serialize()
  78752. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  78753. __decorate([
  78754. BABYLON.serialize()
  78755. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  78756. __decorate([
  78757. BABYLON.serializeAsTexture("lensColorTexture")
  78758. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  78759. __decorate([
  78760. BABYLON.serialize()
  78761. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  78762. __decorate([
  78763. BABYLON.serialize()
  78764. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  78765. __decorate([
  78766. BABYLON.serialize()
  78767. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  78768. __decorate([
  78769. BABYLON.serialize()
  78770. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  78771. __decorate([
  78772. BABYLON.serializeAsTexture("lensStarTexture")
  78773. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  78774. __decorate([
  78775. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  78776. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  78777. __decorate([
  78778. BABYLON.serialize()
  78779. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  78780. __decorate([
  78781. BABYLON.serialize()
  78782. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  78783. __decorate([
  78784. BABYLON.serialize()
  78785. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  78786. __decorate([
  78787. BABYLON.serialize()
  78788. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  78789. __decorate([
  78790. BABYLON.serialize()
  78791. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  78792. __decorate([
  78793. BABYLON.serialize()
  78794. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  78795. __decorate([
  78796. BABYLON.serialize()
  78797. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  78798. __decorate([
  78799. BABYLON.serialize()
  78800. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  78801. __decorate([
  78802. BABYLON.serialize()
  78803. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  78804. __decorate([
  78805. BABYLON.serialize()
  78806. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  78807. __decorate([
  78808. BABYLON.serialize()
  78809. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  78810. __decorate([
  78811. BABYLON.serialize()
  78812. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  78813. return StandardRenderingPipeline;
  78814. }(BABYLON.PostProcessRenderPipeline));
  78815. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  78816. })(BABYLON || (BABYLON = {}));
  78817. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  78818. var BABYLON;
  78819. (function (BABYLON) {
  78820. var FxaaPostProcess = /** @class */ (function (_super) {
  78821. __extends(FxaaPostProcess, _super);
  78822. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  78823. if (camera === void 0) { camera = null; }
  78824. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78825. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  78826. var defines = _this._getDefines();
  78827. _this.updateEffect(defines);
  78828. _this.onApplyObservable.add(function (effect) {
  78829. var texelSize = _this.texelSize;
  78830. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  78831. });
  78832. return _this;
  78833. }
  78834. FxaaPostProcess.prototype._getDefines = function () {
  78835. var engine = this.getEngine();
  78836. if (!engine) {
  78837. return null;
  78838. }
  78839. var glInfo = engine.getGlInfo();
  78840. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  78841. return "#define MALI 1\n";
  78842. }
  78843. return null;
  78844. };
  78845. return FxaaPostProcess;
  78846. }(BABYLON.PostProcess));
  78847. BABYLON.FxaaPostProcess = FxaaPostProcess;
  78848. })(BABYLON || (BABYLON = {}));
  78849. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  78850. var BABYLON;
  78851. (function (BABYLON) {
  78852. /**
  78853. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  78854. */
  78855. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  78856. __extends(ChromaticAberrationPostProcess, _super);
  78857. /**
  78858. * Creates a new instance ChromaticAberrationPostProcess
  78859. * @param name The name of the effect.
  78860. * @param screenWidth The width of the screen to apply the effect on.
  78861. * @param screenHeight The height of the screen to apply the effect on.
  78862. * @param options The required width/height ratio to downsize to before computing the render pass.
  78863. * @param camera The camera to apply the render pass to.
  78864. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78865. * @param engine The engine which the post process will be applied. (default: current engine)
  78866. * @param reusable If the post process can be reused on the same frame. (default: false)
  78867. * @param textureType Type of textures used when performing the post process. (default: 0)
  78868. * @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)
  78869. */
  78870. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  78871. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78872. if (blockCompilation === void 0) { blockCompilation = false; }
  78873. 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;
  78874. /**
  78875. * The amount of seperation of rgb channels (default: 30)
  78876. */
  78877. _this.aberrationAmount = 30;
  78878. /**
  78879. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  78880. */
  78881. _this.radialIntensity = 0;
  78882. /**
  78883. * 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))
  78884. */
  78885. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  78886. /**
  78887. * 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))
  78888. */
  78889. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  78890. _this.onApplyObservable.add(function (effect) {
  78891. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  78892. effect.setFloat('screen_width', screenWidth);
  78893. effect.setFloat('screen_height', screenHeight);
  78894. effect.setFloat('radialIntensity', _this.radialIntensity);
  78895. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  78896. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  78897. });
  78898. return _this;
  78899. }
  78900. return ChromaticAberrationPostProcess;
  78901. }(BABYLON.PostProcess));
  78902. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  78903. })(BABYLON || (BABYLON = {}));
  78904. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  78905. var BABYLON;
  78906. (function (BABYLON) {
  78907. /**
  78908. * The GrainPostProcess adds noise to the image at mid luminance levels
  78909. */
  78910. var GrainPostProcess = /** @class */ (function (_super) {
  78911. __extends(GrainPostProcess, _super);
  78912. /**
  78913. * Creates a new instance of @see GrainPostProcess
  78914. * @param name The name of the effect.
  78915. * @param options The required width/height ratio to downsize to before computing the render pass.
  78916. * @param camera The camera to apply the render pass to.
  78917. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78918. * @param engine The engine which the post process will be applied. (default: current engine)
  78919. * @param reusable If the post process can be reused on the same frame. (default: false)
  78920. * @param textureType Type of textures used when performing the post process. (default: 0)
  78921. * @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)
  78922. */
  78923. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  78924. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78925. if (blockCompilation === void 0) { blockCompilation = false; }
  78926. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  78927. /**
  78928. * The intensity of the grain added (default: 30)
  78929. */
  78930. _this.intensity = 30;
  78931. /**
  78932. * If the grain should be randomized on every frame
  78933. */
  78934. _this.animated = false;
  78935. _this.onApplyObservable.add(function (effect) {
  78936. effect.setFloat('intensity', _this.intensity);
  78937. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  78938. });
  78939. return _this;
  78940. }
  78941. return GrainPostProcess;
  78942. }(BABYLON.PostProcess));
  78943. BABYLON.GrainPostProcess = GrainPostProcess;
  78944. })(BABYLON || (BABYLON = {}));
  78945. //# sourceMappingURL=babylon.grainPostProcess.js.map
  78946. var BABYLON;
  78947. (function (BABYLON) {
  78948. /**
  78949. * The SharpenPostProcess applies a sharpen kernel to every pixel
  78950. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  78951. */
  78952. var SharpenPostProcess = /** @class */ (function (_super) {
  78953. __extends(SharpenPostProcess, _super);
  78954. /**
  78955. * Creates a new instance ConvolutionPostProcess
  78956. * @param name The name of the effect.
  78957. * @param options The required width/height ratio to downsize to before computing the render pass.
  78958. * @param camera The camera to apply the render pass to.
  78959. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78960. * @param engine The engine which the post process will be applied. (default: current engine)
  78961. * @param reusable If the post process can be reused on the same frame. (default: false)
  78962. * @param textureType Type of textures used when performing the post process. (default: 0)
  78963. * @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)
  78964. */
  78965. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  78966. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78967. if (blockCompilation === void 0) { blockCompilation = false; }
  78968. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  78969. /**
  78970. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  78971. */
  78972. _this.colorAmount = 1.0;
  78973. /**
  78974. * How much sharpness should be applied (default: 0.3)
  78975. */
  78976. _this.edgeAmount = 0.3;
  78977. _this.onApply = function (effect) {
  78978. effect.setFloat2("screenSize", _this.width, _this.height);
  78979. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  78980. };
  78981. return _this;
  78982. }
  78983. return SharpenPostProcess;
  78984. }(BABYLON.PostProcess));
  78985. BABYLON.SharpenPostProcess = SharpenPostProcess;
  78986. })(BABYLON || (BABYLON = {}));
  78987. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  78988. var BABYLON;
  78989. (function (BABYLON) {
  78990. /**
  78991. * The Blur Post Process which blurs an image based on a kernel and direction.
  78992. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  78993. */
  78994. var BlurPostProcess = /** @class */ (function (_super) {
  78995. __extends(BlurPostProcess, _super);
  78996. /**
  78997. * Creates a new instance BlurPostProcess
  78998. * @param name The name of the effect.
  78999. * @param direction The direction in which to blur the image.
  79000. * @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.
  79001. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  79002. * @param camera The camera to apply the render pass to.
  79003. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  79004. * @param engine The engine which the post process will be applied. (default: current engine)
  79005. * @param reusable If the post process can be reused on the same frame. (default: false)
  79006. * @param textureType Type of textures used when performing the post process. (default: 0)
  79007. * @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)
  79008. */
  79009. function BlurPostProcess(name,
  79010. /** The direction in which to blur the image. */
  79011. direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  79012. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  79013. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79014. if (defines === void 0) { defines = ""; }
  79015. if (blockCompilation === void 0) { blockCompilation = false; }
  79016. 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;
  79017. _this.direction = direction;
  79018. _this.blockCompilation = blockCompilation;
  79019. _this._packedFloat = false;
  79020. _this._staticDefines = "";
  79021. _this._staticDefines = defines;
  79022. _this.onApplyObservable.add(function (effect) {
  79023. if (_this._outputTexture) {
  79024. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  79025. }
  79026. else {
  79027. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  79028. }
  79029. });
  79030. _this.kernel = kernel;
  79031. return _this;
  79032. }
  79033. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  79034. /**
  79035. * Gets the length in pixels of the blur sample region
  79036. */
  79037. get: function () {
  79038. return this._idealKernel;
  79039. },
  79040. /**
  79041. * Sets the length in pixels of the blur sample region
  79042. */
  79043. set: function (v) {
  79044. if (this._idealKernel === v) {
  79045. return;
  79046. }
  79047. v = Math.max(v, 1);
  79048. this._idealKernel = v;
  79049. this._kernel = this._nearestBestKernel(v);
  79050. if (!this.blockCompilation) {
  79051. this._updateParameters();
  79052. }
  79053. },
  79054. enumerable: true,
  79055. configurable: true
  79056. });
  79057. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  79058. /**
  79059. * Gets wether or not the blur is unpacking/repacking floats
  79060. */
  79061. get: function () {
  79062. return this._packedFloat;
  79063. },
  79064. /**
  79065. * Sets wether or not the blur needs to unpack/repack floats
  79066. */
  79067. set: function (v) {
  79068. if (this._packedFloat === v) {
  79069. return;
  79070. }
  79071. this._packedFloat = v;
  79072. if (!this.blockCompilation) {
  79073. this._updateParameters();
  79074. }
  79075. },
  79076. enumerable: true,
  79077. configurable: true
  79078. });
  79079. /**
  79080. * Updates the effect with the current post process compile time values and recompiles the shader.
  79081. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  79082. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  79083. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  79084. * @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
  79085. * @param onCompiled Called when the shader has been compiled.
  79086. * @param onError Called if there is an error when compiling a shader.
  79087. */
  79088. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  79089. if (defines === void 0) { defines = null; }
  79090. if (uniforms === void 0) { uniforms = null; }
  79091. if (samplers === void 0) { samplers = null; }
  79092. this._updateParameters(onCompiled, onError);
  79093. };
  79094. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  79095. // Generate sampling offsets and weights
  79096. var N = this._kernel;
  79097. var centerIndex = (N - 1) / 2;
  79098. // Generate Gaussian sampling weights over kernel
  79099. var offsets = [];
  79100. var weights = [];
  79101. var totalWeight = 0;
  79102. for (var i = 0; i < N; i++) {
  79103. var u = i / (N - 1);
  79104. var w = this._gaussianWeight(u * 2.0 - 1);
  79105. offsets[i] = (i - centerIndex);
  79106. weights[i] = w;
  79107. totalWeight += w;
  79108. }
  79109. // Normalize weights
  79110. for (var i = 0; i < weights.length; i++) {
  79111. weights[i] /= totalWeight;
  79112. }
  79113. // Optimize: combine samples to take advantage of hardware linear sampling
  79114. // Walk from left to center, combining pairs (symmetrically)
  79115. var linearSamplingWeights = [];
  79116. var linearSamplingOffsets = [];
  79117. var linearSamplingMap = [];
  79118. for (var i = 0; i <= centerIndex; i += 2) {
  79119. var j = Math.min(i + 1, Math.floor(centerIndex));
  79120. var singleCenterSample = i === j;
  79121. if (singleCenterSample) {
  79122. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  79123. }
  79124. else {
  79125. var sharedCell = j === centerIndex;
  79126. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  79127. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  79128. if (offsetLinear === 0) {
  79129. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  79130. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  79131. }
  79132. else {
  79133. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  79134. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  79135. }
  79136. }
  79137. }
  79138. for (var i = 0; i < linearSamplingMap.length; i++) {
  79139. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  79140. linearSamplingWeights[i] = linearSamplingMap[i].w;
  79141. }
  79142. // Replace with optimized
  79143. offsets = linearSamplingOffsets;
  79144. weights = linearSamplingWeights;
  79145. // Generate shaders
  79146. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  79147. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  79148. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  79149. var defines = "";
  79150. defines += this._staticDefines;
  79151. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  79152. if (this._staticDefines.indexOf("DOF") != -1) {
  79153. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  79154. varyingCount--;
  79155. }
  79156. for (var i = 0; i < varyingCount; i++) {
  79157. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  79158. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  79159. }
  79160. var depCount = 0;
  79161. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  79162. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  79163. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  79164. depCount++;
  79165. }
  79166. if (this.packedFloat) {
  79167. defines += "#define PACKEDFLOAT 1";
  79168. }
  79169. this.blockCompilation = false;
  79170. _super.prototype.updateEffect.call(this, defines, null, null, {
  79171. varyingCount: varyingCount,
  79172. depCount: depCount
  79173. }, onCompiled, onError);
  79174. };
  79175. /**
  79176. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  79177. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  79178. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  79179. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  79180. * The gaps between physical kernels are compensated for in the weighting of the samples
  79181. * @param idealKernel Ideal blur kernel.
  79182. * @return Nearest best kernel.
  79183. */
  79184. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  79185. var v = Math.round(idealKernel);
  79186. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  79187. var k = _a[_i];
  79188. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  79189. return Math.max(k, 3);
  79190. }
  79191. }
  79192. return Math.max(v, 3);
  79193. };
  79194. /**
  79195. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  79196. * @param x The point on the Gaussian distribution to sample.
  79197. * @return the value of the Gaussian function at x.
  79198. */
  79199. BlurPostProcess.prototype._gaussianWeight = function (x) {
  79200. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  79201. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  79202. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  79203. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  79204. // truncated at around 1.3% of peak strength.
  79205. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  79206. var sigma = (1 / 3);
  79207. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  79208. var exponent = -((x * x) / (2.0 * sigma * sigma));
  79209. var weight = (1.0 / denominator) * Math.exp(exponent);
  79210. return weight;
  79211. };
  79212. /**
  79213. * Generates a string that can be used as a floating point number in GLSL.
  79214. * @param x Value to print.
  79215. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  79216. * @return GLSL float string.
  79217. */
  79218. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  79219. if (decimalFigures === void 0) { decimalFigures = 8; }
  79220. return x.toFixed(decimalFigures).replace(/0+$/, '');
  79221. };
  79222. return BlurPostProcess;
  79223. }(BABYLON.PostProcess));
  79224. BABYLON.BlurPostProcess = BlurPostProcess;
  79225. })(BABYLON || (BABYLON = {}));
  79226. //# sourceMappingURL=babylon.blurPostProcess.js.map
  79227. var BABYLON;
  79228. (function (BABYLON) {
  79229. /**
  79230. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  79231. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  79232. * based on samples that have a large difference in distance than the center pixel.
  79233. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  79234. */
  79235. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  79236. __extends(DepthOfFieldBlurPostProcess, _super);
  79237. /**
  79238. * Creates a new instance CircleOfConfusionPostProcess
  79239. * @param name The name of the effect.
  79240. * @param scene The scene the effect belongs to.
  79241. * @param direction The direction the blur should be applied.
  79242. * @param kernel The size of the kernel used to blur.
  79243. * @param options The required width/height ratio to downsize to before computing the render pass.
  79244. * @param camera The camera to apply the render pass to.
  79245. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  79246. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  79247. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  79248. * @param engine The engine which the post process will be applied. (default: current engine)
  79249. * @param reusable If the post process can be reused on the same frame. (default: false)
  79250. * @param textureType Type of textures used when performing the post process. (default: 0)
  79251. * @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)
  79252. */
  79253. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  79254. if (imageToBlur === void 0) { imageToBlur = null; }
  79255. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  79256. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79257. if (blockCompilation === void 0) { blockCompilation = false; }
  79258. 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;
  79259. _this.direction = direction;
  79260. _this.onApplyObservable.add(function (effect) {
  79261. if (imageToBlur != null) {
  79262. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  79263. }
  79264. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  79265. if (scene.activeCamera) {
  79266. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  79267. }
  79268. });
  79269. return _this;
  79270. }
  79271. return DepthOfFieldBlurPostProcess;
  79272. }(BABYLON.BlurPostProcess));
  79273. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  79274. })(BABYLON || (BABYLON = {}));
  79275. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  79276. var BABYLON;
  79277. (function (BABYLON) {
  79278. /**
  79279. * Options to be set when merging outputs from the default pipeline.
  79280. */
  79281. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  79282. function DepthOfFieldMergePostProcessOptions() {
  79283. }
  79284. return DepthOfFieldMergePostProcessOptions;
  79285. }());
  79286. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  79287. /**
  79288. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  79289. */
  79290. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  79291. __extends(DepthOfFieldMergePostProcess, _super);
  79292. /**
  79293. * Creates a new instance of DepthOfFieldMergePostProcess
  79294. * @param name The name of the effect.
  79295. * @param originalFromInput Post process which's input will be used for the merge.
  79296. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  79297. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  79298. * @param options The required width/height ratio to downsize to before computing the render pass.
  79299. * @param camera The camera to apply the render pass to.
  79300. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  79301. * @param engine The engine which the post process will be applied. (default: current engine)
  79302. * @param reusable If the post process can be reused on the same frame. (default: false)
  79303. * @param textureType Type of textures used when performing the post process. (default: 0)
  79304. * @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)
  79305. */
  79306. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  79307. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79308. if (blockCompilation === void 0) { blockCompilation = false; }
  79309. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  79310. _this.blurSteps = blurSteps;
  79311. _this.onApplyObservable.add(function (effect) {
  79312. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  79313. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  79314. blurSteps.forEach(function (step, index) {
  79315. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  79316. });
  79317. });
  79318. if (!blockCompilation) {
  79319. _this.updateEffect();
  79320. }
  79321. return _this;
  79322. }
  79323. /**
  79324. * Updates the effect with the current post process compile time values and recompiles the shader.
  79325. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  79326. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  79327. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  79328. * @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
  79329. * @param onCompiled Called when the shader has been compiled.
  79330. * @param onError Called if there is an error when compiling a shader.
  79331. */
  79332. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  79333. if (defines === void 0) { defines = null; }
  79334. if (uniforms === void 0) { uniforms = null; }
  79335. if (samplers === void 0) { samplers = null; }
  79336. if (!defines) {
  79337. defines = "";
  79338. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  79339. }
  79340. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  79341. };
  79342. return DepthOfFieldMergePostProcess;
  79343. }(BABYLON.PostProcess));
  79344. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  79345. })(BABYLON || (BABYLON = {}));
  79346. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  79347. var BABYLON;
  79348. (function (BABYLON) {
  79349. /**
  79350. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  79351. */
  79352. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  79353. __extends(CircleOfConfusionPostProcess, _super);
  79354. /**
  79355. * Creates a new instance CircleOfConfusionPostProcess
  79356. * @param name The name of the effect.
  79357. * @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.
  79358. * @param options The required width/height ratio to downsize to before computing the render pass.
  79359. * @param camera The camera to apply the render pass to.
  79360. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  79361. * @param engine The engine which the post process will be applied. (default: current engine)
  79362. * @param reusable If the post process can be reused on the same frame. (default: false)
  79363. * @param textureType Type of textures used when performing the post process. (default: 0)
  79364. * @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)
  79365. */
  79366. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  79367. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79368. if (blockCompilation === void 0) { blockCompilation = false; }
  79369. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  79370. /**
  79371. * 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.
  79372. */
  79373. _this.lensSize = 50;
  79374. /**
  79375. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  79376. */
  79377. _this.fStop = 1.4;
  79378. /**
  79379. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  79380. */
  79381. _this.focusDistance = 2000;
  79382. /**
  79383. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  79384. */
  79385. _this.focalLength = 50;
  79386. _this._depthTexture = null;
  79387. _this._depthTexture = depthTexture;
  79388. _this.onApplyObservable.add(function (effect) {
  79389. if (!_this._depthTexture) {
  79390. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  79391. return;
  79392. }
  79393. effect.setTexture("depthSampler", _this._depthTexture);
  79394. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  79395. var aperture = _this.lensSize / _this.fStop;
  79396. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  79397. effect.setFloat('focusDistance', _this.focusDistance);
  79398. effect.setFloat('cocPrecalculation', cocPrecalculation);
  79399. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  79400. });
  79401. return _this;
  79402. }
  79403. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  79404. /**
  79405. * 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.
  79406. */
  79407. set: function (value) {
  79408. this._depthTexture = value;
  79409. },
  79410. enumerable: true,
  79411. configurable: true
  79412. });
  79413. return CircleOfConfusionPostProcess;
  79414. }(BABYLON.PostProcess));
  79415. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  79416. })(BABYLON || (BABYLON = {}));
  79417. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  79418. var BABYLON;
  79419. (function (BABYLON) {
  79420. /**
  79421. * Specifies the level of max blur that should be applied when using the depth of field effect
  79422. */
  79423. var DepthOfFieldEffectBlurLevel;
  79424. (function (DepthOfFieldEffectBlurLevel) {
  79425. /**
  79426. * Subtle blur
  79427. */
  79428. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  79429. /**
  79430. * Medium blur
  79431. */
  79432. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  79433. /**
  79434. * Large blur
  79435. */
  79436. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  79437. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  79438. ;
  79439. /**
  79440. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  79441. */
  79442. var DepthOfFieldEffect = /** @class */ (function (_super) {
  79443. __extends(DepthOfFieldEffect, _super);
  79444. /**
  79445. * Creates a new instance DepthOfFieldEffect
  79446. * @param scene The scene the effect belongs to.
  79447. * @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.
  79448. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  79449. * @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)
  79450. */
  79451. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  79452. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  79453. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  79454. if (blockCompilation === void 0) { blockCompilation = false; }
  79455. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  79456. return _this._effects;
  79457. }, true) || this;
  79458. /**
  79459. * @hidden Internal post processes in depth of field effect
  79460. */
  79461. _this._effects = [];
  79462. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  79463. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  79464. // 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)
  79465. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  79466. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  79467. _this._depthOfFieldBlurY = [];
  79468. _this._depthOfFieldBlurX = [];
  79469. var blurCount = 1;
  79470. var kernelSize = 15;
  79471. switch (blurLevel) {
  79472. case DepthOfFieldEffectBlurLevel.High: {
  79473. blurCount = 3;
  79474. kernelSize = 51;
  79475. break;
  79476. }
  79477. case DepthOfFieldEffectBlurLevel.Medium: {
  79478. blurCount = 2;
  79479. kernelSize = 31;
  79480. break;
  79481. }
  79482. default: {
  79483. kernelSize = 15;
  79484. blurCount = 1;
  79485. break;
  79486. }
  79487. }
  79488. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  79489. var ratio = 1.0;
  79490. for (var i = 0; i < blurCount; i++) {
  79491. 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);
  79492. blurY.autoClear = false;
  79493. ratio = 0.75 / Math.pow(2, i);
  79494. 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);
  79495. blurX.autoClear = false;
  79496. _this._depthOfFieldBlurY.push(blurY);
  79497. _this._depthOfFieldBlurX.push(blurX);
  79498. }
  79499. // Set all post processes on the effect.
  79500. _this._effects = [_this._circleOfConfusion];
  79501. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  79502. _this._effects.push(_this._depthOfFieldBlurY[i]);
  79503. _this._effects.push(_this._depthOfFieldBlurX[i]);
  79504. }
  79505. // Merge blurred images with original image based on circleOfConfusion
  79506. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  79507. _this._dofMerge.autoClear = false;
  79508. _this._effects.push(_this._dofMerge);
  79509. return _this;
  79510. }
  79511. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  79512. get: function () {
  79513. return this._circleOfConfusion.focalLength;
  79514. },
  79515. /**
  79516. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  79517. */
  79518. set: function (value) {
  79519. this._circleOfConfusion.focalLength = value;
  79520. },
  79521. enumerable: true,
  79522. configurable: true
  79523. });
  79524. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  79525. get: function () {
  79526. return this._circleOfConfusion.fStop;
  79527. },
  79528. /**
  79529. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  79530. */
  79531. set: function (value) {
  79532. this._circleOfConfusion.fStop = value;
  79533. },
  79534. enumerable: true,
  79535. configurable: true
  79536. });
  79537. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  79538. get: function () {
  79539. return this._circleOfConfusion.focusDistance;
  79540. },
  79541. /**
  79542. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  79543. */
  79544. set: function (value) {
  79545. this._circleOfConfusion.focusDistance = value;
  79546. },
  79547. enumerable: true,
  79548. configurable: true
  79549. });
  79550. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  79551. get: function () {
  79552. return this._circleOfConfusion.lensSize;
  79553. },
  79554. /**
  79555. * 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.
  79556. */
  79557. set: function (value) {
  79558. this._circleOfConfusion.lensSize = value;
  79559. },
  79560. enumerable: true,
  79561. configurable: true
  79562. });
  79563. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  79564. /**
  79565. * 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.
  79566. */
  79567. set: function (value) {
  79568. this._circleOfConfusion.depthTexture = value;
  79569. },
  79570. enumerable: true,
  79571. configurable: true
  79572. });
  79573. /**
  79574. * Disposes each of the internal effects for a given camera.
  79575. * @param camera The camera to dispose the effect on.
  79576. */
  79577. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  79578. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  79579. this._effects[effectIndex].dispose(camera);
  79580. }
  79581. };
  79582. /**
  79583. * @hidden Internal
  79584. */
  79585. DepthOfFieldEffect.prototype._updateEffects = function () {
  79586. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  79587. this._effects[effectIndex].updateEffect();
  79588. }
  79589. };
  79590. /**
  79591. * Internal
  79592. * @returns if all the contained post processes are ready.
  79593. * @hidden
  79594. */
  79595. DepthOfFieldEffect.prototype._isReady = function () {
  79596. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  79597. if (!this._effects[effectIndex].isReady()) {
  79598. return false;
  79599. }
  79600. }
  79601. return true;
  79602. };
  79603. return DepthOfFieldEffect;
  79604. }(BABYLON.PostProcessRenderEffect));
  79605. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  79606. })(BABYLON || (BABYLON = {}));
  79607. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  79608. var BABYLON;
  79609. (function (BABYLON) {
  79610. /**
  79611. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  79612. */
  79613. var BloomMergePostProcess = /** @class */ (function (_super) {
  79614. __extends(BloomMergePostProcess, _super);
  79615. /**
  79616. * Creates a new instance of @see BloomMergePostProcess
  79617. * @param name The name of the effect.
  79618. * @param originalFromInput Post process which's input will be used for the merge.
  79619. * @param blurred Blurred highlights post process which's output will be used.
  79620. * @param weight Weight of the bloom to be added to the original input.
  79621. * @param options The required width/height ratio to downsize to before computing the render pass.
  79622. * @param camera The camera to apply the render pass to.
  79623. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  79624. * @param engine The engine which the post process will be applied. (default: current engine)
  79625. * @param reusable If the post process can be reused on the same frame. (default: false)
  79626. * @param textureType Type of textures used when performing the post process. (default: 0)
  79627. * @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)
  79628. */
  79629. function BloomMergePostProcess(name, originalFromInput, blurred,
  79630. /** Weight of the bloom to be added to the original input. */
  79631. weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  79632. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79633. if (blockCompilation === void 0) { blockCompilation = false; }
  79634. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  79635. _this.weight = weight;
  79636. _this.onApplyObservable.add(function (effect) {
  79637. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  79638. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  79639. effect.setFloat("bloomWeight", _this.weight);
  79640. });
  79641. if (!blockCompilation) {
  79642. _this.updateEffect();
  79643. }
  79644. return _this;
  79645. }
  79646. return BloomMergePostProcess;
  79647. }(BABYLON.PostProcess));
  79648. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  79649. })(BABYLON || (BABYLON = {}));
  79650. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  79651. var BABYLON;
  79652. (function (BABYLON) {
  79653. /**
  79654. * 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.
  79655. */
  79656. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  79657. __extends(ExtractHighlightsPostProcess, _super);
  79658. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  79659. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79660. if (blockCompilation === void 0) { blockCompilation = false; }
  79661. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  79662. /**
  79663. * The luminance threshold, pixels below this value will be set to black.
  79664. */
  79665. _this.threshold = 0.9;
  79666. /** @hidden */
  79667. _this._exposure = 1;
  79668. /**
  79669. * Post process which has the input texture to be used when performing highlight extraction
  79670. * @hidden
  79671. */
  79672. _this._inputPostProcess = null;
  79673. _this.onApplyObservable.add(function (effect) {
  79674. if (_this._inputPostProcess) {
  79675. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  79676. }
  79677. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  79678. effect.setFloat('exposure', _this._exposure);
  79679. });
  79680. return _this;
  79681. }
  79682. return ExtractHighlightsPostProcess;
  79683. }(BABYLON.PostProcess));
  79684. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  79685. })(BABYLON || (BABYLON = {}));
  79686. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  79687. var BABYLON;
  79688. (function (BABYLON) {
  79689. /**
  79690. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  79691. */
  79692. var BloomEffect = /** @class */ (function (_super) {
  79693. __extends(BloomEffect, _super);
  79694. /**
  79695. * Creates a new instance of @see BloomEffect
  79696. * @param scene The scene the effect belongs to.
  79697. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  79698. * @param bloomKernel The size of the kernel to be used when applying the blur.
  79699. * @param bloomWeight The the strength of bloom.
  79700. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  79701. * @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)
  79702. */
  79703. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  79704. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  79705. if (blockCompilation === void 0) { blockCompilation = false; }
  79706. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  79707. return _this._effects;
  79708. }, true) || this;
  79709. _this.bloomScale = bloomScale;
  79710. /**
  79711. * @hidden Internal
  79712. */
  79713. _this._effects = [];
  79714. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  79715. _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);
  79716. _this._blurX.alwaysForcePOT = true;
  79717. _this._blurX.autoClear = false;
  79718. _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);
  79719. _this._blurY.alwaysForcePOT = true;
  79720. _this._blurY.autoClear = false;
  79721. _this.kernel = bloomKernel;
  79722. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  79723. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  79724. _this._merge.autoClear = false;
  79725. _this._effects.push(_this._merge);
  79726. return _this;
  79727. }
  79728. Object.defineProperty(BloomEffect.prototype, "threshold", {
  79729. /**
  79730. * The luminance threshold to find bright areas of the image to bloom.
  79731. */
  79732. get: function () {
  79733. return this._downscale.threshold;
  79734. },
  79735. set: function (value) {
  79736. this._downscale.threshold = value;
  79737. },
  79738. enumerable: true,
  79739. configurable: true
  79740. });
  79741. Object.defineProperty(BloomEffect.prototype, "weight", {
  79742. /**
  79743. * The strength of the bloom.
  79744. */
  79745. get: function () {
  79746. return this._merge.weight;
  79747. },
  79748. set: function (value) {
  79749. this._merge.weight = value;
  79750. },
  79751. enumerable: true,
  79752. configurable: true
  79753. });
  79754. Object.defineProperty(BloomEffect.prototype, "kernel", {
  79755. /**
  79756. * Specifies the size of the bloom blur kernel, relative to the final output size
  79757. */
  79758. get: function () {
  79759. return this._blurX.kernel / this.bloomScale;
  79760. },
  79761. set: function (value) {
  79762. this._blurX.kernel = value * this.bloomScale;
  79763. this._blurY.kernel = value * this.bloomScale;
  79764. },
  79765. enumerable: true,
  79766. configurable: true
  79767. });
  79768. /**
  79769. * Disposes each of the internal effects for a given camera.
  79770. * @param camera The camera to dispose the effect on.
  79771. */
  79772. BloomEffect.prototype.disposeEffects = function (camera) {
  79773. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  79774. this._effects[effectIndex].dispose(camera);
  79775. }
  79776. };
  79777. /**
  79778. * @hidden Internal
  79779. */
  79780. BloomEffect.prototype._updateEffects = function () {
  79781. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  79782. this._effects[effectIndex].updateEffect();
  79783. }
  79784. };
  79785. /**
  79786. * Internal
  79787. * @returns if all the contained post processes are ready.
  79788. * @hidden
  79789. */
  79790. BloomEffect.prototype._isReady = function () {
  79791. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  79792. if (!this._effects[effectIndex].isReady()) {
  79793. return false;
  79794. }
  79795. }
  79796. return true;
  79797. };
  79798. return BloomEffect;
  79799. }(BABYLON.PostProcessRenderEffect));
  79800. BABYLON.BloomEffect = BloomEffect;
  79801. })(BABYLON || (BABYLON = {}));
  79802. //# sourceMappingURL=babylon.bloomEffect.js.map
  79803. var BABYLON;
  79804. (function (BABYLON) {
  79805. /**
  79806. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  79807. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  79808. */
  79809. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  79810. __extends(DefaultRenderingPipeline, _super);
  79811. /**
  79812. * @constructor
  79813. * @param {string} name - The rendering pipeline name (default: "")
  79814. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  79815. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  79816. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  79817. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  79818. */
  79819. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  79820. if (name === void 0) { name = ""; }
  79821. if (hdr === void 0) { hdr = true; }
  79822. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  79823. if (automaticBuild === void 0) { automaticBuild = true; }
  79824. var _this = _super.call(this, scene.getEngine(), name) || this;
  79825. _this._camerasToBeAttached = [];
  79826. /**
  79827. * ID of the sharpen post process,
  79828. */
  79829. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  79830. /**
  79831. * ID of the image processing post process;
  79832. */
  79833. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  79834. /**
  79835. * ID of the Fast Approximate Anti-Aliasing post process;
  79836. */
  79837. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  79838. /**
  79839. * ID of the chromatic aberration post process,
  79840. */
  79841. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  79842. /**
  79843. * ID of the grain post process
  79844. */
  79845. _this.GrainPostProcessId = "GrainPostProcessEffect";
  79846. /**
  79847. * Glow post process which adds a glow to emmisive areas of the image
  79848. */
  79849. _this._glowLayer = null;
  79850. /**
  79851. * Animations which can be used to tweak settings over a period of time
  79852. */
  79853. _this.animations = [];
  79854. _this._imageProcessingConfigurationObserver = null;
  79855. // Values
  79856. _this._sharpenEnabled = false;
  79857. _this._bloomEnabled = false;
  79858. _this._depthOfFieldEnabled = false;
  79859. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  79860. _this._fxaaEnabled = false;
  79861. _this._imageProcessingEnabled = true;
  79862. _this._bloomScale = 0.5;
  79863. _this._chromaticAberrationEnabled = false;
  79864. _this._grainEnabled = false;
  79865. _this._buildAllowed = true;
  79866. _this._resizeObserver = null;
  79867. _this._hardwareScaleLevel = 1.0;
  79868. _this._bloomKernel = 64;
  79869. /**
  79870. * Specifies the weight of the bloom in the final rendering
  79871. */
  79872. _this._bloomWeight = 0.15;
  79873. /**
  79874. * Specifies the luma threshold for the area that will be blurred by the bloom
  79875. */
  79876. _this._bloomThreshold = 0.9;
  79877. _this._samples = 1;
  79878. _this._hasCleared = false;
  79879. _this._prevPostProcess = null;
  79880. _this._prevPrevPostProcess = null;
  79881. _this._cameras = cameras || scene.cameras;
  79882. _this._cameras = _this._cameras.slice();
  79883. _this._camerasToBeAttached = _this._cameras.slice();
  79884. _this._buildAllowed = automaticBuild;
  79885. // Initialize
  79886. _this._scene = scene;
  79887. var caps = _this._scene.getEngine().getCaps();
  79888. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  79889. // Misc
  79890. if (_this._hdr) {
  79891. if (caps.textureHalfFloatRender) {
  79892. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  79893. }
  79894. else if (caps.textureFloatRender) {
  79895. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79896. }
  79897. }
  79898. else {
  79899. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79900. }
  79901. // Attach
  79902. scene.postProcessRenderPipelineManager.addPipeline(_this);
  79903. var engine = _this._scene.getEngine();
  79904. // Create post processes before hand so they can be modified before enabled.
  79905. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  79906. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  79907. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  79908. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  79909. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  79910. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  79911. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  79912. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  79913. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  79914. _this._resizeObserver = engine.onResizeObservable.add(function () {
  79915. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  79916. _this.bloomKernel = _this.bloomKernel;
  79917. });
  79918. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  79919. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  79920. });
  79921. _this._buildPipeline();
  79922. return _this;
  79923. }
  79924. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  79925. get: function () {
  79926. return this._sharpenEnabled;
  79927. },
  79928. /**
  79929. * Enable or disable the sharpen process from the pipeline
  79930. */
  79931. set: function (enabled) {
  79932. if (this._sharpenEnabled === enabled) {
  79933. return;
  79934. }
  79935. this._sharpenEnabled = enabled;
  79936. this._buildPipeline();
  79937. },
  79938. enumerable: true,
  79939. configurable: true
  79940. });
  79941. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  79942. /**
  79943. * Specifies the size of the bloom blur kernel, relative to the final output size
  79944. */
  79945. get: function () {
  79946. return this._bloomKernel;
  79947. },
  79948. set: function (value) {
  79949. this._bloomKernel = value;
  79950. this.bloom.kernel = value / this._hardwareScaleLevel;
  79951. },
  79952. enumerable: true,
  79953. configurable: true
  79954. });
  79955. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  79956. get: function () {
  79957. return this._bloomWeight;
  79958. },
  79959. /**
  79960. * The strength of the bloom.
  79961. */
  79962. set: function (value) {
  79963. if (this._bloomWeight === value) {
  79964. return;
  79965. }
  79966. this.bloom.weight = value;
  79967. this._bloomWeight = value;
  79968. },
  79969. enumerable: true,
  79970. configurable: true
  79971. });
  79972. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  79973. get: function () {
  79974. return this._bloomThreshold;
  79975. },
  79976. /**
  79977. * The strength of the bloom.
  79978. */
  79979. set: function (value) {
  79980. if (this._bloomThreshold === value) {
  79981. return;
  79982. }
  79983. this.bloom.threshold = value;
  79984. this._bloomThreshold = value;
  79985. },
  79986. enumerable: true,
  79987. configurable: true
  79988. });
  79989. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  79990. get: function () {
  79991. return this._bloomScale;
  79992. },
  79993. /**
  79994. * The scale of the bloom, lower value will provide better performance.
  79995. */
  79996. set: function (value) {
  79997. if (this._bloomScale === value) {
  79998. return;
  79999. }
  80000. this._bloomScale = value;
  80001. // recreate bloom and dispose old as this setting is not dynamic
  80002. this._rebuildBloom();
  80003. this._buildPipeline();
  80004. },
  80005. enumerable: true,
  80006. configurable: true
  80007. });
  80008. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  80009. get: function () {
  80010. return this._bloomEnabled;
  80011. },
  80012. /**
  80013. * Enable or disable the bloom from the pipeline
  80014. */
  80015. set: function (enabled) {
  80016. if (this._bloomEnabled === enabled) {
  80017. return;
  80018. }
  80019. this._bloomEnabled = enabled;
  80020. this._buildPipeline();
  80021. },
  80022. enumerable: true,
  80023. configurable: true
  80024. });
  80025. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  80026. // recreate bloom and dispose old as this setting is not dynamic
  80027. var oldBloom = this.bloom;
  80028. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  80029. this.bloom.threshold = oldBloom.threshold;
  80030. for (var i = 0; i < this._cameras.length; i++) {
  80031. oldBloom.disposeEffects(this._cameras[i]);
  80032. }
  80033. };
  80034. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  80035. /**
  80036. * If the depth of field is enabled.
  80037. */
  80038. get: function () {
  80039. return this._depthOfFieldEnabled;
  80040. },
  80041. set: function (enabled) {
  80042. if (this._depthOfFieldEnabled === enabled) {
  80043. return;
  80044. }
  80045. this._depthOfFieldEnabled = enabled;
  80046. this._buildPipeline();
  80047. },
  80048. enumerable: true,
  80049. configurable: true
  80050. });
  80051. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  80052. /**
  80053. * Blur level of the depth of field effect. (Higher blur will effect performance)
  80054. */
  80055. get: function () {
  80056. return this._depthOfFieldBlurLevel;
  80057. },
  80058. set: function (value) {
  80059. if (this._depthOfFieldBlurLevel === value) {
  80060. return;
  80061. }
  80062. this._depthOfFieldBlurLevel = value;
  80063. // recreate dof and dispose old as this setting is not dynamic
  80064. var oldDof = this.depthOfField;
  80065. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  80066. this.depthOfField.focalLength = oldDof.focalLength;
  80067. this.depthOfField.focusDistance = oldDof.focusDistance;
  80068. this.depthOfField.fStop = oldDof.fStop;
  80069. this.depthOfField.lensSize = oldDof.lensSize;
  80070. for (var i = 0; i < this._cameras.length; i++) {
  80071. oldDof.disposeEffects(this._cameras[i]);
  80072. }
  80073. this._buildPipeline();
  80074. },
  80075. enumerable: true,
  80076. configurable: true
  80077. });
  80078. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  80079. get: function () {
  80080. return this._fxaaEnabled;
  80081. },
  80082. /**
  80083. * If the anti aliasing is enabled.
  80084. */
  80085. set: function (enabled) {
  80086. if (this._fxaaEnabled === enabled) {
  80087. return;
  80088. }
  80089. this._fxaaEnabled = enabled;
  80090. this._buildPipeline();
  80091. },
  80092. enumerable: true,
  80093. configurable: true
  80094. });
  80095. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  80096. get: function () {
  80097. return this._samples;
  80098. },
  80099. /**
  80100. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  80101. */
  80102. set: function (sampleCount) {
  80103. if (this._samples === sampleCount) {
  80104. return;
  80105. }
  80106. this._samples = sampleCount;
  80107. this._buildPipeline();
  80108. },
  80109. enumerable: true,
  80110. configurable: true
  80111. });
  80112. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  80113. get: function () {
  80114. return this._imageProcessingEnabled;
  80115. },
  80116. /**
  80117. * If image processing is enabled.
  80118. */
  80119. set: function (enabled) {
  80120. if (this._imageProcessingEnabled === enabled) {
  80121. return;
  80122. }
  80123. this._imageProcessingEnabled = enabled;
  80124. this._buildPipeline();
  80125. },
  80126. enumerable: true,
  80127. configurable: true
  80128. });
  80129. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  80130. get: function () {
  80131. return this._glowLayer == null;
  80132. },
  80133. /**
  80134. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  80135. */
  80136. set: function (enabled) {
  80137. if (enabled && !this._glowLayer) {
  80138. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  80139. }
  80140. else if (!enabled && this._glowLayer) {
  80141. this._glowLayer.dispose();
  80142. this._glowLayer = null;
  80143. }
  80144. },
  80145. enumerable: true,
  80146. configurable: true
  80147. });
  80148. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  80149. get: function () {
  80150. return this._chromaticAberrationEnabled;
  80151. },
  80152. /**
  80153. * Enable or disable the chromaticAberration process from the pipeline
  80154. */
  80155. set: function (enabled) {
  80156. if (this._chromaticAberrationEnabled === enabled) {
  80157. return;
  80158. }
  80159. this._chromaticAberrationEnabled = enabled;
  80160. this._buildPipeline();
  80161. },
  80162. enumerable: true,
  80163. configurable: true
  80164. });
  80165. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  80166. get: function () {
  80167. return this._grainEnabled;
  80168. },
  80169. /**
  80170. * Enable or disable the grain process from the pipeline
  80171. */
  80172. set: function (enabled) {
  80173. if (this._grainEnabled === enabled) {
  80174. return;
  80175. }
  80176. this._grainEnabled = enabled;
  80177. this._buildPipeline();
  80178. },
  80179. enumerable: true,
  80180. configurable: true
  80181. });
  80182. /**
  80183. * Force the compilation of the entire pipeline.
  80184. */
  80185. DefaultRenderingPipeline.prototype.prepare = function () {
  80186. var previousState = this._buildAllowed;
  80187. this._buildAllowed = true;
  80188. this._buildPipeline();
  80189. this._buildAllowed = previousState;
  80190. };
  80191. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  80192. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  80193. if (this._hasCleared) {
  80194. postProcess.autoClear = false;
  80195. }
  80196. else {
  80197. postProcess.autoClear = true;
  80198. this._scene.autoClear = false;
  80199. this._hasCleared = true;
  80200. }
  80201. if (!skipTextureSharing) {
  80202. if (this._prevPrevPostProcess) {
  80203. postProcess.shareOutputWith(this._prevPrevPostProcess);
  80204. }
  80205. else {
  80206. postProcess.useOwnOutput();
  80207. }
  80208. if (this._prevPostProcess) {
  80209. this._prevPrevPostProcess = this._prevPostProcess;
  80210. }
  80211. this._prevPostProcess = postProcess;
  80212. }
  80213. };
  80214. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  80215. var _this = this;
  80216. if (!this._buildAllowed) {
  80217. return;
  80218. }
  80219. this._scene.autoClear = true;
  80220. var engine = this._scene.getEngine();
  80221. this._disposePostProcesses();
  80222. if (this._cameras !== null) {
  80223. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  80224. // get back cameras to be used to reattach pipeline
  80225. this._cameras = this._camerasToBeAttached.slice();
  80226. }
  80227. this._reset();
  80228. this._prevPostProcess = null;
  80229. this._prevPrevPostProcess = null;
  80230. this._hasCleared = false;
  80231. if (this.depthOfFieldEnabled) {
  80232. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  80233. this.depthOfField.depthTexture = depthTexture;
  80234. if (!this.depthOfField._isReady()) {
  80235. this.depthOfField._updateEffects();
  80236. }
  80237. this.addEffect(this.depthOfField);
  80238. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  80239. }
  80240. if (this.bloomEnabled) {
  80241. if (!this.bloom._isReady()) {
  80242. this.bloom._updateEffects();
  80243. }
  80244. this.addEffect(this.bloom);
  80245. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  80246. }
  80247. if (this._imageProcessingEnabled) {
  80248. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  80249. if (this._hdr) {
  80250. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  80251. this._setAutoClearAndTextureSharing(this.imageProcessing);
  80252. }
  80253. else {
  80254. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  80255. }
  80256. }
  80257. if (this.sharpenEnabled) {
  80258. if (!this.sharpen.isReady()) {
  80259. this.sharpen.updateEffect();
  80260. }
  80261. this.addEffect(this._sharpenEffect);
  80262. this._setAutoClearAndTextureSharing(this.sharpen);
  80263. }
  80264. if (this.grainEnabled) {
  80265. if (!this.grain.isReady()) {
  80266. this.grain.updateEffect();
  80267. }
  80268. this.addEffect(this._grainEffect);
  80269. this._setAutoClearAndTextureSharing(this.grain);
  80270. }
  80271. if (this.chromaticAberrationEnabled) {
  80272. if (!this.chromaticAberration.isReady()) {
  80273. this.chromaticAberration.updateEffect();
  80274. }
  80275. this.addEffect(this._chromaticAberrationEffect);
  80276. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  80277. }
  80278. if (this.fxaaEnabled) {
  80279. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  80280. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  80281. this._setAutoClearAndTextureSharing(this.fxaa, true);
  80282. }
  80283. if (this._cameras !== null) {
  80284. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  80285. }
  80286. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  80287. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  80288. }
  80289. };
  80290. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  80291. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  80292. for (var i = 0; i < this._cameras.length; i++) {
  80293. var camera = this._cameras[i];
  80294. if (this.imageProcessing) {
  80295. this.imageProcessing.dispose(camera);
  80296. }
  80297. if (this.fxaa) {
  80298. this.fxaa.dispose(camera);
  80299. }
  80300. // These are created in the constructor and should not be disposed on every pipeline change
  80301. if (disposeNonRecreated) {
  80302. if (this.sharpen) {
  80303. this.sharpen.dispose(camera);
  80304. }
  80305. if (this.depthOfField) {
  80306. this.depthOfField.disposeEffects(camera);
  80307. }
  80308. if (this.bloom) {
  80309. this.bloom.disposeEffects(camera);
  80310. }
  80311. if (this.chromaticAberration) {
  80312. this.chromaticAberration.dispose(camera);
  80313. }
  80314. if (this.grain) {
  80315. this.grain.dispose(camera);
  80316. }
  80317. if (this._glowLayer) {
  80318. this._glowLayer.dispose();
  80319. }
  80320. }
  80321. }
  80322. this.imageProcessing = null;
  80323. this.fxaa = null;
  80324. if (disposeNonRecreated) {
  80325. this.sharpen = null;
  80326. this._sharpenEffect = null;
  80327. this.depthOfField = null;
  80328. this.bloom = null;
  80329. this.chromaticAberration = null;
  80330. this._chromaticAberrationEffect = null;
  80331. this.grain = null;
  80332. this._grainEffect = null;
  80333. this._glowLayer = null;
  80334. }
  80335. };
  80336. /**
  80337. * Adds a camera to the pipeline
  80338. * @param camera the camera to be added
  80339. */
  80340. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  80341. this._camerasToBeAttached.push(camera);
  80342. this._buildPipeline();
  80343. };
  80344. /**
  80345. * Removes a camera from the pipeline
  80346. * @param camera the camera to remove
  80347. */
  80348. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  80349. var index = this._camerasToBeAttached.indexOf(camera);
  80350. this._camerasToBeAttached.splice(index, 1);
  80351. this._buildPipeline();
  80352. };
  80353. /**
  80354. * Dispose of the pipeline and stop all post processes
  80355. */
  80356. DefaultRenderingPipeline.prototype.dispose = function () {
  80357. this._disposePostProcesses(true);
  80358. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  80359. this._scene.autoClear = true;
  80360. if (this._resizeObserver) {
  80361. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  80362. this._resizeObserver = null;
  80363. }
  80364. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  80365. _super.prototype.dispose.call(this);
  80366. };
  80367. /**
  80368. * Serialize the rendering pipeline (Used when exporting)
  80369. * @returns the serialized object
  80370. */
  80371. DefaultRenderingPipeline.prototype.serialize = function () {
  80372. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  80373. serializationObject.customType = "DefaultRenderingPipeline";
  80374. return serializationObject;
  80375. };
  80376. /**
  80377. * Parse the serialized pipeline
  80378. * @param source Source pipeline.
  80379. * @param scene The scene to load the pipeline to.
  80380. * @param rootUrl The URL of the serialized pipeline.
  80381. * @returns An instantiated pipeline from the serialized object.
  80382. */
  80383. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  80384. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  80385. };
  80386. __decorate([
  80387. BABYLON.serialize()
  80388. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  80389. __decorate([
  80390. BABYLON.serialize()
  80391. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  80392. __decorate([
  80393. BABYLON.serialize()
  80394. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  80395. __decorate([
  80396. BABYLON.serialize()
  80397. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  80398. __decorate([
  80399. BABYLON.serialize()
  80400. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  80401. __decorate([
  80402. BABYLON.serialize()
  80403. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  80404. __decorate([
  80405. BABYLON.serialize()
  80406. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  80407. __decorate([
  80408. BABYLON.serialize()
  80409. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  80410. __decorate([
  80411. BABYLON.serialize()
  80412. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  80413. __decorate([
  80414. BABYLON.serialize()
  80415. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  80416. __decorate([
  80417. BABYLON.serialize()
  80418. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  80419. __decorate([
  80420. BABYLON.serialize()
  80421. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  80422. __decorate([
  80423. BABYLON.serialize()
  80424. ], DefaultRenderingPipeline.prototype, "samples", null);
  80425. __decorate([
  80426. BABYLON.serialize()
  80427. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  80428. __decorate([
  80429. BABYLON.serialize()
  80430. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  80431. __decorate([
  80432. BABYLON.serialize()
  80433. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  80434. __decorate([
  80435. BABYLON.serialize()
  80436. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  80437. return DefaultRenderingPipeline;
  80438. }(BABYLON.PostProcessRenderPipeline));
  80439. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  80440. })(BABYLON || (BABYLON = {}));
  80441. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  80442. var BABYLON;
  80443. (function (BABYLON) {
  80444. /**
  80445. * @hidden
  80446. */
  80447. var ImageProcessingConfigurationDefines = /** @class */ (function (_super) {
  80448. __extends(ImageProcessingConfigurationDefines, _super);
  80449. function ImageProcessingConfigurationDefines() {
  80450. var _this = _super.call(this) || this;
  80451. _this.IMAGEPROCESSING = false;
  80452. _this.VIGNETTE = false;
  80453. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  80454. _this.VIGNETTEBLENDMODEOPAQUE = false;
  80455. _this.TONEMAPPING = false;
  80456. _this.TONEMAPPING_ACES = false;
  80457. _this.CONTRAST = false;
  80458. _this.COLORCURVES = false;
  80459. _this.COLORGRADING = false;
  80460. _this.COLORGRADING3D = false;
  80461. _this.SAMPLER3DGREENDEPTH = false;
  80462. _this.SAMPLER3DBGRMAP = false;
  80463. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  80464. _this.EXPOSURE = false;
  80465. _this.rebuild();
  80466. return _this;
  80467. }
  80468. return ImageProcessingConfigurationDefines;
  80469. }(BABYLON.MaterialDefines));
  80470. BABYLON.ImageProcessingConfigurationDefines = ImageProcessingConfigurationDefines;
  80471. /**
  80472. * This groups together the common properties used for image processing either in direct forward pass
  80473. * or through post processing effect depending on the use of the image processing pipeline in your scene
  80474. * or not.
  80475. */
  80476. var ImageProcessingConfiguration = /** @class */ (function () {
  80477. function ImageProcessingConfiguration() {
  80478. /**
  80479. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  80480. */
  80481. this.colorCurves = new BABYLON.ColorCurves();
  80482. this._colorCurvesEnabled = false;
  80483. this._colorGradingEnabled = false;
  80484. this._colorGradingWithGreenDepth = true;
  80485. this._colorGradingBGR = true;
  80486. /** @hidden */
  80487. this._exposure = 1.0;
  80488. this._toneMappingEnabled = false;
  80489. this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;
  80490. this._contrast = 1.0;
  80491. /**
  80492. * Vignette stretch size.
  80493. */
  80494. this.vignetteStretch = 0;
  80495. /**
  80496. * Vignette centre X Offset.
  80497. */
  80498. this.vignetteCentreX = 0;
  80499. /**
  80500. * Vignette centre Y Offset.
  80501. */
  80502. this.vignetteCentreY = 0;
  80503. /**
  80504. * Vignette weight or intensity of the vignette effect.
  80505. */
  80506. this.vignetteWeight = 1.5;
  80507. /**
  80508. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  80509. * if vignetteEnabled is set to true.
  80510. */
  80511. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  80512. /**
  80513. * Camera field of view used by the Vignette effect.
  80514. */
  80515. this.vignetteCameraFov = 0.5;
  80516. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  80517. this._vignetteEnabled = false;
  80518. this._applyByPostProcess = false;
  80519. this._isEnabled = true;
  80520. /**
  80521. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  80522. */
  80523. this.onUpdateParameters = new BABYLON.Observable();
  80524. }
  80525. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  80526. /**
  80527. * Gets wether the color curves effect is enabled.
  80528. */
  80529. get: function () {
  80530. return this._colorCurvesEnabled;
  80531. },
  80532. /**
  80533. * Sets wether the color curves effect is enabled.
  80534. */
  80535. set: function (value) {
  80536. if (this._colorCurvesEnabled === value) {
  80537. return;
  80538. }
  80539. this._colorCurvesEnabled = value;
  80540. this._updateParameters();
  80541. },
  80542. enumerable: true,
  80543. configurable: true
  80544. });
  80545. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  80546. /**
  80547. * Gets wether the color grading effect is enabled.
  80548. */
  80549. get: function () {
  80550. return this._colorGradingEnabled;
  80551. },
  80552. /**
  80553. * Sets wether the color grading effect is enabled.
  80554. */
  80555. set: function (value) {
  80556. if (this._colorGradingEnabled === value) {
  80557. return;
  80558. }
  80559. this._colorGradingEnabled = value;
  80560. this._updateParameters();
  80561. },
  80562. enumerable: true,
  80563. configurable: true
  80564. });
  80565. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  80566. /**
  80567. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  80568. */
  80569. get: function () {
  80570. return this._colorGradingWithGreenDepth;
  80571. },
  80572. /**
  80573. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  80574. */
  80575. set: function (value) {
  80576. if (this._colorGradingWithGreenDepth === value) {
  80577. return;
  80578. }
  80579. this._colorGradingWithGreenDepth = value;
  80580. this._updateParameters();
  80581. },
  80582. enumerable: true,
  80583. configurable: true
  80584. });
  80585. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  80586. /**
  80587. * Gets wether the color grading texture contains BGR values.
  80588. */
  80589. get: function () {
  80590. return this._colorGradingBGR;
  80591. },
  80592. /**
  80593. * Sets wether the color grading texture contains BGR values.
  80594. */
  80595. set: function (value) {
  80596. if (this._colorGradingBGR === value) {
  80597. return;
  80598. }
  80599. this._colorGradingBGR = value;
  80600. this._updateParameters();
  80601. },
  80602. enumerable: true,
  80603. configurable: true
  80604. });
  80605. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  80606. /**
  80607. * Gets the Exposure used in the effect.
  80608. */
  80609. get: function () {
  80610. return this._exposure;
  80611. },
  80612. /**
  80613. * Sets the Exposure used in the effect.
  80614. */
  80615. set: function (value) {
  80616. if (this._exposure === value) {
  80617. return;
  80618. }
  80619. this._exposure = value;
  80620. this._updateParameters();
  80621. },
  80622. enumerable: true,
  80623. configurable: true
  80624. });
  80625. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  80626. /**
  80627. * Gets wether the tone mapping effect is enabled.
  80628. */
  80629. get: function () {
  80630. return this._toneMappingEnabled;
  80631. },
  80632. /**
  80633. * Sets wether the tone mapping effect is enabled.
  80634. */
  80635. set: function (value) {
  80636. if (this._toneMappingEnabled === value) {
  80637. return;
  80638. }
  80639. this._toneMappingEnabled = value;
  80640. this._updateParameters();
  80641. },
  80642. enumerable: true,
  80643. configurable: true
  80644. });
  80645. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingType", {
  80646. /**
  80647. * Gets the type of tone mapping effect.
  80648. */
  80649. get: function () {
  80650. return this._toneMappingType;
  80651. },
  80652. /**
  80653. * Sets the type of tone mapping effect used in BabylonJS.
  80654. */
  80655. set: function (value) {
  80656. if (this._toneMappingType === value) {
  80657. return;
  80658. }
  80659. this._toneMappingType = value;
  80660. this._updateParameters();
  80661. },
  80662. enumerable: true,
  80663. configurable: true
  80664. });
  80665. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  80666. /**
  80667. * Gets the contrast used in the effect.
  80668. */
  80669. get: function () {
  80670. return this._contrast;
  80671. },
  80672. /**
  80673. * Sets the contrast used in the effect.
  80674. */
  80675. set: function (value) {
  80676. if (this._contrast === value) {
  80677. return;
  80678. }
  80679. this._contrast = value;
  80680. this._updateParameters();
  80681. },
  80682. enumerable: true,
  80683. configurable: true
  80684. });
  80685. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  80686. /**
  80687. * Gets the vignette blend mode allowing different kind of effect.
  80688. */
  80689. get: function () {
  80690. return this._vignetteBlendMode;
  80691. },
  80692. /**
  80693. * Sets the vignette blend mode allowing different kind of effect.
  80694. */
  80695. set: function (value) {
  80696. if (this._vignetteBlendMode === value) {
  80697. return;
  80698. }
  80699. this._vignetteBlendMode = value;
  80700. this._updateParameters();
  80701. },
  80702. enumerable: true,
  80703. configurable: true
  80704. });
  80705. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  80706. /**
  80707. * Gets wether the vignette effect is enabled.
  80708. */
  80709. get: function () {
  80710. return this._vignetteEnabled;
  80711. },
  80712. /**
  80713. * Sets wether the vignette effect is enabled.
  80714. */
  80715. set: function (value) {
  80716. if (this._vignetteEnabled === value) {
  80717. return;
  80718. }
  80719. this._vignetteEnabled = value;
  80720. this._updateParameters();
  80721. },
  80722. enumerable: true,
  80723. configurable: true
  80724. });
  80725. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  80726. /**
  80727. * Gets wether the image processing is applied through a post process or not.
  80728. */
  80729. get: function () {
  80730. return this._applyByPostProcess;
  80731. },
  80732. /**
  80733. * Sets wether the image processing is applied through a post process or not.
  80734. */
  80735. set: function (value) {
  80736. if (this._applyByPostProcess === value) {
  80737. return;
  80738. }
  80739. this._applyByPostProcess = value;
  80740. this._updateParameters();
  80741. },
  80742. enumerable: true,
  80743. configurable: true
  80744. });
  80745. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  80746. /**
  80747. * Gets wether the image processing is enabled or not.
  80748. */
  80749. get: function () {
  80750. return this._isEnabled;
  80751. },
  80752. /**
  80753. * Sets wether the image processing is enabled or not.
  80754. */
  80755. set: function (value) {
  80756. if (this._isEnabled === value) {
  80757. return;
  80758. }
  80759. this._isEnabled = value;
  80760. this._updateParameters();
  80761. },
  80762. enumerable: true,
  80763. configurable: true
  80764. });
  80765. /**
  80766. * Method called each time the image processing information changes requires to recompile the effect.
  80767. */
  80768. ImageProcessingConfiguration.prototype._updateParameters = function () {
  80769. this.onUpdateParameters.notifyObservers(this);
  80770. };
  80771. ImageProcessingConfiguration.prototype.getClassName = function () {
  80772. return "ImageProcessingConfiguration";
  80773. };
  80774. /**
  80775. * Prepare the list of uniforms associated with the Image Processing effects.
  80776. * @param uniformsList The list of uniforms used in the effect
  80777. * @param defines the list of defines currently in use
  80778. */
  80779. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  80780. if (defines.EXPOSURE) {
  80781. uniforms.push("exposureLinear");
  80782. }
  80783. if (defines.CONTRAST) {
  80784. uniforms.push("contrast");
  80785. }
  80786. if (defines.COLORGRADING) {
  80787. uniforms.push("colorTransformSettings");
  80788. }
  80789. if (defines.VIGNETTE) {
  80790. uniforms.push("vInverseScreenSize");
  80791. uniforms.push("vignetteSettings1");
  80792. uniforms.push("vignetteSettings2");
  80793. }
  80794. if (defines.COLORCURVES) {
  80795. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  80796. }
  80797. };
  80798. /**
  80799. * Prepare the list of samplers associated with the Image Processing effects.
  80800. * @param uniformsList The list of uniforms used in the effect
  80801. * @param defines the list of defines currently in use
  80802. */
  80803. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  80804. if (defines.COLORGRADING) {
  80805. samplersList.push("txColorTransform");
  80806. }
  80807. };
  80808. /**
  80809. * Prepare the list of defines associated to the shader.
  80810. * @param defines the list of defines to complete
  80811. */
  80812. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  80813. if (forPostProcess === void 0) { forPostProcess = false; }
  80814. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  80815. defines.VIGNETTE = false;
  80816. defines.TONEMAPPING = false;
  80817. defines.TONEMAPPING_ACES = false;
  80818. defines.CONTRAST = false;
  80819. defines.EXPOSURE = false;
  80820. defines.COLORCURVES = false;
  80821. defines.COLORGRADING = false;
  80822. defines.COLORGRADING3D = false;
  80823. defines.IMAGEPROCESSING = false;
  80824. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  80825. return;
  80826. }
  80827. defines.VIGNETTE = this.vignetteEnabled;
  80828. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  80829. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  80830. defines.TONEMAPPING = this.toneMappingEnabled;
  80831. switch (this._toneMappingType) {
  80832. case ImageProcessingConfiguration.TONEMAPPING_ACES:
  80833. defines.TONEMAPPING_ACES = true;
  80834. break;
  80835. }
  80836. defines.CONTRAST = (this.contrast !== 1.0);
  80837. defines.EXPOSURE = (this.exposure !== 1.0);
  80838. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  80839. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  80840. if (defines.COLORGRADING) {
  80841. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  80842. }
  80843. else {
  80844. defines.COLORGRADING3D = false;
  80845. }
  80846. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  80847. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  80848. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  80849. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  80850. };
  80851. /**
  80852. * Returns true if all the image processing information are ready.
  80853. */
  80854. ImageProcessingConfiguration.prototype.isReady = function () {
  80855. // Color Grading texure can not be none blocking.
  80856. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  80857. };
  80858. /**
  80859. * Binds the image processing to the shader.
  80860. * @param effect The effect to bind to
  80861. */
  80862. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  80863. if (aspectRatio === void 0) { aspectRatio = 1; }
  80864. // Color Curves
  80865. if (this._colorCurvesEnabled && this.colorCurves) {
  80866. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  80867. }
  80868. // Vignette
  80869. if (this._vignetteEnabled) {
  80870. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  80871. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  80872. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  80873. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  80874. var vignetteScaleX = vignetteScaleY * aspectRatio;
  80875. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  80876. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  80877. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  80878. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  80879. var vignettePower = -2.0 * this.vignetteWeight;
  80880. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  80881. }
  80882. // Exposure
  80883. effect.setFloat("exposureLinear", this.exposure);
  80884. // Contrast
  80885. effect.setFloat("contrast", this.contrast);
  80886. // Color transform settings
  80887. if (this.colorGradingTexture) {
  80888. effect.setTexture("txColorTransform", this.colorGradingTexture);
  80889. var textureSize = this.colorGradingTexture.getSize().height;
  80890. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  80891. 0.5 / textureSize, // textureOffset
  80892. textureSize, // textureSize
  80893. this.colorGradingTexture.level // weight
  80894. );
  80895. }
  80896. };
  80897. /**
  80898. * Clones the current image processing instance.
  80899. * @return The cloned image processing
  80900. */
  80901. ImageProcessingConfiguration.prototype.clone = function () {
  80902. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  80903. };
  80904. /**
  80905. * Serializes the current image processing instance to a json representation.
  80906. * @return a JSON representation
  80907. */
  80908. ImageProcessingConfiguration.prototype.serialize = function () {
  80909. return BABYLON.SerializationHelper.Serialize(this);
  80910. };
  80911. /**
  80912. * Parses the image processing from a json representation.
  80913. * @param source the JSON source to parse
  80914. * @return The parsed image processing
  80915. */
  80916. ImageProcessingConfiguration.Parse = function (source) {
  80917. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  80918. };
  80919. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  80920. /**
  80921. * Used to apply the vignette as a mix with the pixel color.
  80922. */
  80923. get: function () {
  80924. return this._VIGNETTEMODE_MULTIPLY;
  80925. },
  80926. enumerable: true,
  80927. configurable: true
  80928. });
  80929. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  80930. /**
  80931. * Used to apply the vignette as a replacement of the pixel color.
  80932. */
  80933. get: function () {
  80934. return this._VIGNETTEMODE_OPAQUE;
  80935. },
  80936. enumerable: true,
  80937. configurable: true
  80938. });
  80939. /**
  80940. * Default tone mapping applied in BabylonJS.
  80941. */
  80942. ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
  80943. /**
  80944. * ACES Tone mapping (used by default in unreal and unity). This can help getting closer
  80945. * to other engines rendering to increase portability.
  80946. */
  80947. ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
  80948. // Static constants associated to the image processing.
  80949. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  80950. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  80951. __decorate([
  80952. BABYLON.serializeAsColorCurves()
  80953. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  80954. __decorate([
  80955. BABYLON.serialize()
  80956. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  80957. __decorate([
  80958. BABYLON.serializeAsTexture()
  80959. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  80960. __decorate([
  80961. BABYLON.serialize()
  80962. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  80963. __decorate([
  80964. BABYLON.serialize()
  80965. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  80966. __decorate([
  80967. BABYLON.serialize()
  80968. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  80969. __decorate([
  80970. BABYLON.serialize()
  80971. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  80972. __decorate([
  80973. BABYLON.serialize()
  80974. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  80975. __decorate([
  80976. BABYLON.serialize()
  80977. ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0);
  80978. __decorate([
  80979. BABYLON.serialize()
  80980. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  80981. __decorate([
  80982. BABYLON.serialize()
  80983. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  80984. __decorate([
  80985. BABYLON.serialize()
  80986. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  80987. __decorate([
  80988. BABYLON.serialize()
  80989. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  80990. __decorate([
  80991. BABYLON.serialize()
  80992. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  80993. __decorate([
  80994. BABYLON.serializeAsColor4()
  80995. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  80996. __decorate([
  80997. BABYLON.serialize()
  80998. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  80999. __decorate([
  81000. BABYLON.serialize()
  81001. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  81002. __decorate([
  81003. BABYLON.serialize()
  81004. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  81005. __decorate([
  81006. BABYLON.serialize()
  81007. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  81008. __decorate([
  81009. BABYLON.serialize()
  81010. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  81011. return ImageProcessingConfiguration;
  81012. }());
  81013. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  81014. })(BABYLON || (BABYLON = {}));
  81015. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  81016. var BABYLON;
  81017. (function (BABYLON) {
  81018. /**
  81019. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  81020. * It can help converting any input color in a desired output one. This can then be used to create effects
  81021. * from sepia, black and white to sixties or futuristic rendering...
  81022. *
  81023. * The only supported format is currently 3dl.
  81024. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  81025. */
  81026. var ColorGradingTexture = /** @class */ (function (_super) {
  81027. __extends(ColorGradingTexture, _super);
  81028. /**
  81029. * Instantiates a ColorGradingTexture from the following parameters.
  81030. *
  81031. * @param url The location of the color gradind data (currently only supporting 3dl)
  81032. * @param scene The scene the texture will be used in
  81033. */
  81034. function ColorGradingTexture(url, scene) {
  81035. var _this = _super.call(this, scene) || this;
  81036. if (!url) {
  81037. return _this;
  81038. }
  81039. _this._engine = scene.getEngine();
  81040. _this._textureMatrix = BABYLON.Matrix.Identity();
  81041. _this.name = url;
  81042. _this.url = url;
  81043. _this.hasAlpha = false;
  81044. _this.isCube = false;
  81045. _this.is3D = _this._engine.webGLVersion > 1;
  81046. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81047. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81048. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81049. _this.anisotropicFilteringLevel = 1;
  81050. _this._texture = _this._getFromCache(url, true);
  81051. if (!_this._texture) {
  81052. if (!scene.useDelayedTextureLoading) {
  81053. _this.loadTexture();
  81054. }
  81055. else {
  81056. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  81057. }
  81058. }
  81059. return _this;
  81060. }
  81061. /**
  81062. * Returns the texture matrix used in most of the material.
  81063. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  81064. */
  81065. ColorGradingTexture.prototype.getTextureMatrix = function () {
  81066. return this._textureMatrix;
  81067. };
  81068. /**
  81069. * Occurs when the file being loaded is a .3dl LUT file.
  81070. */
  81071. ColorGradingTexture.prototype.load3dlTexture = function () {
  81072. var engine = this._engine;
  81073. var texture;
  81074. if (engine.webGLVersion === 1) {
  81075. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  81076. }
  81077. else {
  81078. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  81079. }
  81080. this._texture = texture;
  81081. var callback = function (text) {
  81082. if (typeof text !== "string") {
  81083. return;
  81084. }
  81085. var data = null;
  81086. var tempData = null;
  81087. var line;
  81088. var lines = text.split('\n');
  81089. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  81090. var maxColor = 0;
  81091. for (var i = 0; i < lines.length; i++) {
  81092. line = lines[i];
  81093. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  81094. continue;
  81095. if (line.indexOf('#') === 0)
  81096. continue;
  81097. var words = line.split(" ");
  81098. if (size === 0) {
  81099. // Number of space + one
  81100. size = words.length;
  81101. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  81102. tempData = new Float32Array(size * size * size * 4);
  81103. continue;
  81104. }
  81105. if (size != 0) {
  81106. var r = Math.max(parseInt(words[0]), 0);
  81107. var g = Math.max(parseInt(words[1]), 0);
  81108. var b = Math.max(parseInt(words[2]), 0);
  81109. maxColor = Math.max(r, maxColor);
  81110. maxColor = Math.max(g, maxColor);
  81111. maxColor = Math.max(b, maxColor);
  81112. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  81113. if (tempData) {
  81114. tempData[pixelStorageIndex + 0] = r;
  81115. tempData[pixelStorageIndex + 1] = g;
  81116. tempData[pixelStorageIndex + 2] = b;
  81117. }
  81118. pixelIndexSlice++;
  81119. if (pixelIndexSlice % size == 0) {
  81120. pixelIndexH++;
  81121. pixelIndexSlice = 0;
  81122. if (pixelIndexH % size == 0) {
  81123. pixelIndexW++;
  81124. pixelIndexH = 0;
  81125. }
  81126. }
  81127. }
  81128. }
  81129. if (tempData && data) {
  81130. for (var i = 0; i < tempData.length; i++) {
  81131. if (i > 0 && (i + 1) % 4 === 0) {
  81132. data[i] = 255;
  81133. }
  81134. else {
  81135. var value = tempData[i];
  81136. data[i] = (value / maxColor * 255);
  81137. }
  81138. }
  81139. }
  81140. if (texture.is3D) {
  81141. texture.updateSize(size, size, size);
  81142. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  81143. }
  81144. else {
  81145. texture.updateSize(size * size, size);
  81146. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  81147. }
  81148. };
  81149. var scene = this.getScene();
  81150. if (scene) {
  81151. scene._loadFile(this.url, callback);
  81152. }
  81153. else {
  81154. this._engine._loadFile(this.url, callback);
  81155. }
  81156. return this._texture;
  81157. };
  81158. /**
  81159. * Starts the loading process of the texture.
  81160. */
  81161. ColorGradingTexture.prototype.loadTexture = function () {
  81162. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  81163. this.load3dlTexture();
  81164. }
  81165. };
  81166. /**
  81167. * Clones the color gradind texture.
  81168. */
  81169. ColorGradingTexture.prototype.clone = function () {
  81170. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  81171. // Base texture
  81172. newTexture.level = this.level;
  81173. return newTexture;
  81174. };
  81175. /**
  81176. * Called during delayed load for textures.
  81177. */
  81178. ColorGradingTexture.prototype.delayLoad = function () {
  81179. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  81180. return;
  81181. }
  81182. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  81183. this._texture = this._getFromCache(this.url, true);
  81184. if (!this._texture) {
  81185. this.loadTexture();
  81186. }
  81187. };
  81188. /**
  81189. * Parses a color grading texture serialized by Babylon.
  81190. * @param parsedTexture The texture information being parsedTexture
  81191. * @param scene The scene to load the texture in
  81192. * @param rootUrl The root url of the data assets to load
  81193. * @return A color gradind texture
  81194. */
  81195. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  81196. var texture = null;
  81197. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  81198. texture = new ColorGradingTexture(parsedTexture.name, scene);
  81199. texture.name = parsedTexture.name;
  81200. texture.level = parsedTexture.level;
  81201. }
  81202. return texture;
  81203. };
  81204. /**
  81205. * Serializes the LUT texture to json format.
  81206. */
  81207. ColorGradingTexture.prototype.serialize = function () {
  81208. if (!this.name) {
  81209. return null;
  81210. }
  81211. var serializationObject = {};
  81212. serializationObject.name = this.name;
  81213. serializationObject.level = this.level;
  81214. serializationObject.customType = "BABYLON.ColorGradingTexture";
  81215. return serializationObject;
  81216. };
  81217. /**
  81218. * Empty line regex stored for GC.
  81219. */
  81220. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  81221. return ColorGradingTexture;
  81222. }(BABYLON.BaseTexture));
  81223. BABYLON.ColorGradingTexture = ColorGradingTexture;
  81224. })(BABYLON || (BABYLON = {}));
  81225. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  81226. var BABYLON;
  81227. (function (BABYLON) {
  81228. /**
  81229. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  81230. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  81231. * 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;
  81232. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  81233. */
  81234. var ColorCurves = /** @class */ (function () {
  81235. function ColorCurves() {
  81236. this._dirty = true;
  81237. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  81238. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  81239. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  81240. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  81241. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  81242. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  81243. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  81244. this._globalHue = 30;
  81245. this._globalDensity = 0;
  81246. this._globalSaturation = 0;
  81247. this._globalExposure = 0;
  81248. this._highlightsHue = 30;
  81249. this._highlightsDensity = 0;
  81250. this._highlightsSaturation = 0;
  81251. this._highlightsExposure = 0;
  81252. this._midtonesHue = 30;
  81253. this._midtonesDensity = 0;
  81254. this._midtonesSaturation = 0;
  81255. this._midtonesExposure = 0;
  81256. this._shadowsHue = 30;
  81257. this._shadowsDensity = 0;
  81258. this._shadowsSaturation = 0;
  81259. this._shadowsExposure = 0;
  81260. }
  81261. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  81262. /**
  81263. * Gets the global Hue value.
  81264. * 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).
  81265. */
  81266. get: function () {
  81267. return this._globalHue;
  81268. },
  81269. /**
  81270. * Sets the global Hue value.
  81271. * 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).
  81272. */
  81273. set: function (value) {
  81274. this._globalHue = value;
  81275. this._dirty = true;
  81276. },
  81277. enumerable: true,
  81278. configurable: true
  81279. });
  81280. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  81281. /**
  81282. * Gets the global Density value.
  81283. * 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.
  81284. * Values less than zero provide a filter of opposite hue.
  81285. */
  81286. get: function () {
  81287. return this._globalDensity;
  81288. },
  81289. /**
  81290. * Sets the global Density value.
  81291. * 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.
  81292. * Values less than zero provide a filter of opposite hue.
  81293. */
  81294. set: function (value) {
  81295. this._globalDensity = value;
  81296. this._dirty = true;
  81297. },
  81298. enumerable: true,
  81299. configurable: true
  81300. });
  81301. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  81302. /**
  81303. * Gets the global Saturation value.
  81304. * 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.
  81305. */
  81306. get: function () {
  81307. return this._globalSaturation;
  81308. },
  81309. /**
  81310. * Sets the global Saturation value.
  81311. * 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.
  81312. */
  81313. set: function (value) {
  81314. this._globalSaturation = value;
  81315. this._dirty = true;
  81316. },
  81317. enumerable: true,
  81318. configurable: true
  81319. });
  81320. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  81321. /**
  81322. * Gets the global Exposure value.
  81323. * 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.
  81324. */
  81325. get: function () {
  81326. return this._globalExposure;
  81327. },
  81328. /**
  81329. * Sets the global Exposure value.
  81330. * 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.
  81331. */
  81332. set: function (value) {
  81333. this._globalExposure = value;
  81334. this._dirty = true;
  81335. },
  81336. enumerable: true,
  81337. configurable: true
  81338. });
  81339. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  81340. /**
  81341. * Gets the highlights Hue value.
  81342. * 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).
  81343. */
  81344. get: function () {
  81345. return this._highlightsHue;
  81346. },
  81347. /**
  81348. * Sets the highlights Hue value.
  81349. * 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).
  81350. */
  81351. set: function (value) {
  81352. this._highlightsHue = value;
  81353. this._dirty = true;
  81354. },
  81355. enumerable: true,
  81356. configurable: true
  81357. });
  81358. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  81359. /**
  81360. * Gets the highlights Density value.
  81361. * 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.
  81362. * Values less than zero provide a filter of opposite hue.
  81363. */
  81364. get: function () {
  81365. return this._highlightsDensity;
  81366. },
  81367. /**
  81368. * Sets the highlights Density value.
  81369. * 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.
  81370. * Values less than zero provide a filter of opposite hue.
  81371. */
  81372. set: function (value) {
  81373. this._highlightsDensity = value;
  81374. this._dirty = true;
  81375. },
  81376. enumerable: true,
  81377. configurable: true
  81378. });
  81379. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  81380. /**
  81381. * Gets the highlights Saturation value.
  81382. * 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.
  81383. */
  81384. get: function () {
  81385. return this._highlightsSaturation;
  81386. },
  81387. /**
  81388. * Sets the highlights Saturation value.
  81389. * 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.
  81390. */
  81391. set: function (value) {
  81392. this._highlightsSaturation = value;
  81393. this._dirty = true;
  81394. },
  81395. enumerable: true,
  81396. configurable: true
  81397. });
  81398. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  81399. /**
  81400. * Gets the highlights Exposure value.
  81401. * 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.
  81402. */
  81403. get: function () {
  81404. return this._highlightsExposure;
  81405. },
  81406. /**
  81407. * Sets the highlights Exposure value.
  81408. * 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.
  81409. */
  81410. set: function (value) {
  81411. this._highlightsExposure = value;
  81412. this._dirty = true;
  81413. },
  81414. enumerable: true,
  81415. configurable: true
  81416. });
  81417. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  81418. /**
  81419. * Gets the midtones Hue value.
  81420. * 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).
  81421. */
  81422. get: function () {
  81423. return this._midtonesHue;
  81424. },
  81425. /**
  81426. * Sets the midtones Hue value.
  81427. * 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).
  81428. */
  81429. set: function (value) {
  81430. this._midtonesHue = value;
  81431. this._dirty = true;
  81432. },
  81433. enumerable: true,
  81434. configurable: true
  81435. });
  81436. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  81437. /**
  81438. * Gets the midtones Density value.
  81439. * 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.
  81440. * Values less than zero provide a filter of opposite hue.
  81441. */
  81442. get: function () {
  81443. return this._midtonesDensity;
  81444. },
  81445. /**
  81446. * Sets the midtones Density value.
  81447. * 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.
  81448. * Values less than zero provide a filter of opposite hue.
  81449. */
  81450. set: function (value) {
  81451. this._midtonesDensity = value;
  81452. this._dirty = true;
  81453. },
  81454. enumerable: true,
  81455. configurable: true
  81456. });
  81457. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  81458. /**
  81459. * Gets the midtones Saturation value.
  81460. * 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.
  81461. */
  81462. get: function () {
  81463. return this._midtonesSaturation;
  81464. },
  81465. /**
  81466. * Sets the midtones Saturation value.
  81467. * 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.
  81468. */
  81469. set: function (value) {
  81470. this._midtonesSaturation = value;
  81471. this._dirty = true;
  81472. },
  81473. enumerable: true,
  81474. configurable: true
  81475. });
  81476. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  81477. /**
  81478. * Gets the midtones Exposure value.
  81479. * 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.
  81480. */
  81481. get: function () {
  81482. return this._midtonesExposure;
  81483. },
  81484. /**
  81485. * Sets the midtones Exposure value.
  81486. * 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.
  81487. */
  81488. set: function (value) {
  81489. this._midtonesExposure = value;
  81490. this._dirty = true;
  81491. },
  81492. enumerable: true,
  81493. configurable: true
  81494. });
  81495. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  81496. /**
  81497. * Gets the shadows Hue value.
  81498. * 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).
  81499. */
  81500. get: function () {
  81501. return this._shadowsHue;
  81502. },
  81503. /**
  81504. * Sets the shadows Hue value.
  81505. * 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).
  81506. */
  81507. set: function (value) {
  81508. this._shadowsHue = value;
  81509. this._dirty = true;
  81510. },
  81511. enumerable: true,
  81512. configurable: true
  81513. });
  81514. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  81515. /**
  81516. * Gets the shadows Density value.
  81517. * 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.
  81518. * Values less than zero provide a filter of opposite hue.
  81519. */
  81520. get: function () {
  81521. return this._shadowsDensity;
  81522. },
  81523. /**
  81524. * Sets the shadows Density value.
  81525. * 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.
  81526. * Values less than zero provide a filter of opposite hue.
  81527. */
  81528. set: function (value) {
  81529. this._shadowsDensity = value;
  81530. this._dirty = true;
  81531. },
  81532. enumerable: true,
  81533. configurable: true
  81534. });
  81535. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  81536. /**
  81537. * Gets the shadows Saturation value.
  81538. * 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.
  81539. */
  81540. get: function () {
  81541. return this._shadowsSaturation;
  81542. },
  81543. /**
  81544. * Sets the shadows Saturation value.
  81545. * 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.
  81546. */
  81547. set: function (value) {
  81548. this._shadowsSaturation = value;
  81549. this._dirty = true;
  81550. },
  81551. enumerable: true,
  81552. configurable: true
  81553. });
  81554. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  81555. /**
  81556. * Gets the shadows Exposure value.
  81557. * 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.
  81558. */
  81559. get: function () {
  81560. return this._shadowsExposure;
  81561. },
  81562. /**
  81563. * Sets the shadows Exposure value.
  81564. * 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.
  81565. */
  81566. set: function (value) {
  81567. this._shadowsExposure = value;
  81568. this._dirty = true;
  81569. },
  81570. enumerable: true,
  81571. configurable: true
  81572. });
  81573. ColorCurves.prototype.getClassName = function () {
  81574. return "ColorCurves";
  81575. };
  81576. /**
  81577. * Binds the color curves to the shader.
  81578. * @param colorCurves The color curve to bind
  81579. * @param effect The effect to bind to
  81580. */
  81581. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  81582. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  81583. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  81584. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  81585. if (colorCurves._dirty) {
  81586. colorCurves._dirty = false;
  81587. // Fill in global info.
  81588. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  81589. // Compute highlights info.
  81590. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  81591. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  81592. // Compute midtones info.
  81593. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  81594. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  81595. // Compute shadows info.
  81596. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  81597. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  81598. // Compute deltas (neutral is midtones).
  81599. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  81600. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  81601. }
  81602. if (effect) {
  81603. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  81604. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  81605. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  81606. }
  81607. };
  81608. /**
  81609. * Prepare the list of uniforms associated with the ColorCurves effects.
  81610. * @param uniformsList The list of uniforms used in the effect
  81611. */
  81612. ColorCurves.PrepareUniforms = function (uniformsList) {
  81613. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  81614. };
  81615. /**
  81616. * Returns color grading data based on a hue, density, saturation and exposure value.
  81617. * @param filterHue The hue of the color filter.
  81618. * @param filterDensity The density of the color filter.
  81619. * @param saturation The saturation.
  81620. * @param exposure The exposure.
  81621. * @param result The result data container.
  81622. */
  81623. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  81624. if (hue == null) {
  81625. return;
  81626. }
  81627. hue = ColorCurves.clamp(hue, 0, 360);
  81628. density = ColorCurves.clamp(density, -100, 100);
  81629. saturation = ColorCurves.clamp(saturation, -100, 100);
  81630. exposure = ColorCurves.clamp(exposure, -100, 100);
  81631. // Remap the slider/config filter density with non-linear mapping and also scale by half
  81632. // so that the maximum filter density is only 50% control. This provides fine control
  81633. // for small values and reasonable range.
  81634. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  81635. density *= 0.5;
  81636. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  81637. if (density < 0) {
  81638. density *= -1;
  81639. hue = (hue + 180) % 360;
  81640. }
  81641. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  81642. result.scaleToRef(2, result);
  81643. result.a = 1 + 0.01 * saturation;
  81644. };
  81645. /**
  81646. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  81647. * @param value The input slider value in range [-100,100].
  81648. * @returns Adjusted value.
  81649. */
  81650. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  81651. value /= 100;
  81652. var x = Math.abs(value);
  81653. x = Math.pow(x, 2);
  81654. if (value < 0) {
  81655. x *= -1;
  81656. }
  81657. x *= 100;
  81658. return x;
  81659. };
  81660. /**
  81661. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  81662. * @param hue The hue (H) input.
  81663. * @param saturation The saturation (S) input.
  81664. * @param brightness The brightness (B) input.
  81665. * @result An RGBA color represented as Vector4.
  81666. */
  81667. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  81668. var h = ColorCurves.clamp(hue, 0, 360);
  81669. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  81670. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  81671. if (s === 0) {
  81672. result.r = v;
  81673. result.g = v;
  81674. result.b = v;
  81675. }
  81676. else {
  81677. // sector 0 to 5
  81678. h /= 60;
  81679. var i = Math.floor(h);
  81680. // fractional part of h
  81681. var f = h - i;
  81682. var p = v * (1 - s);
  81683. var q = v * (1 - s * f);
  81684. var t = v * (1 - s * (1 - f));
  81685. switch (i) {
  81686. case 0:
  81687. result.r = v;
  81688. result.g = t;
  81689. result.b = p;
  81690. break;
  81691. case 1:
  81692. result.r = q;
  81693. result.g = v;
  81694. result.b = p;
  81695. break;
  81696. case 2:
  81697. result.r = p;
  81698. result.g = v;
  81699. result.b = t;
  81700. break;
  81701. case 3:
  81702. result.r = p;
  81703. result.g = q;
  81704. result.b = v;
  81705. break;
  81706. case 4:
  81707. result.r = t;
  81708. result.g = p;
  81709. result.b = v;
  81710. break;
  81711. default: // case 5:
  81712. result.r = v;
  81713. result.g = p;
  81714. result.b = q;
  81715. break;
  81716. }
  81717. }
  81718. result.a = 1;
  81719. };
  81720. /**
  81721. * Returns a value clamped between min and max
  81722. * @param value The value to clamp
  81723. * @param min The minimum of value
  81724. * @param max The maximum of value
  81725. * @returns The clamped value.
  81726. */
  81727. ColorCurves.clamp = function (value, min, max) {
  81728. return Math.min(Math.max(value, min), max);
  81729. };
  81730. /**
  81731. * Clones the current color curve instance.
  81732. * @return The cloned curves
  81733. */
  81734. ColorCurves.prototype.clone = function () {
  81735. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  81736. };
  81737. /**
  81738. * Serializes the current color curve instance to a json representation.
  81739. * @return a JSON representation
  81740. */
  81741. ColorCurves.prototype.serialize = function () {
  81742. return BABYLON.SerializationHelper.Serialize(this);
  81743. };
  81744. /**
  81745. * Parses the color curve from a json representation.
  81746. * @param source the JSON source to parse
  81747. * @return The parsed curves
  81748. */
  81749. ColorCurves.Parse = function (source) {
  81750. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  81751. };
  81752. __decorate([
  81753. BABYLON.serialize()
  81754. ], ColorCurves.prototype, "_globalHue", void 0);
  81755. __decorate([
  81756. BABYLON.serialize()
  81757. ], ColorCurves.prototype, "_globalDensity", void 0);
  81758. __decorate([
  81759. BABYLON.serialize()
  81760. ], ColorCurves.prototype, "_globalSaturation", void 0);
  81761. __decorate([
  81762. BABYLON.serialize()
  81763. ], ColorCurves.prototype, "_globalExposure", void 0);
  81764. __decorate([
  81765. BABYLON.serialize()
  81766. ], ColorCurves.prototype, "_highlightsHue", void 0);
  81767. __decorate([
  81768. BABYLON.serialize()
  81769. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  81770. __decorate([
  81771. BABYLON.serialize()
  81772. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  81773. __decorate([
  81774. BABYLON.serialize()
  81775. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  81776. __decorate([
  81777. BABYLON.serialize()
  81778. ], ColorCurves.prototype, "_midtonesHue", void 0);
  81779. __decorate([
  81780. BABYLON.serialize()
  81781. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  81782. __decorate([
  81783. BABYLON.serialize()
  81784. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  81785. __decorate([
  81786. BABYLON.serialize()
  81787. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  81788. return ColorCurves;
  81789. }());
  81790. BABYLON.ColorCurves = ColorCurves;
  81791. })(BABYLON || (BABYLON = {}));
  81792. //# sourceMappingURL=babylon.colorCurves.js.map
  81793. var BABYLON;
  81794. (function (BABYLON) {
  81795. var RefractionPostProcess = /** @class */ (function (_super) {
  81796. __extends(RefractionPostProcess, _super);
  81797. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  81798. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  81799. _this.color = color;
  81800. _this.depth = depth;
  81801. _this.colorLevel = colorLevel;
  81802. _this._ownRefractionTexture = true;
  81803. _this.onActivateObservable.add(function (cam) {
  81804. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  81805. });
  81806. _this.onApplyObservable.add(function (effect) {
  81807. effect.setColor3("baseColor", _this.color);
  81808. effect.setFloat("depth", _this.depth);
  81809. effect.setFloat("colorLevel", _this.colorLevel);
  81810. effect.setTexture("refractionSampler", _this._refTexture);
  81811. });
  81812. return _this;
  81813. }
  81814. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  81815. /**
  81816. * Gets or sets the refraction texture
  81817. * Please note that you are responsible for disposing the texture if you set it manually
  81818. */
  81819. get: function () {
  81820. return this._refTexture;
  81821. },
  81822. set: function (value) {
  81823. if (this._refTexture && this._ownRefractionTexture) {
  81824. this._refTexture.dispose();
  81825. }
  81826. this._refTexture = value;
  81827. this._ownRefractionTexture = false;
  81828. },
  81829. enumerable: true,
  81830. configurable: true
  81831. });
  81832. // Methods
  81833. RefractionPostProcess.prototype.dispose = function (camera) {
  81834. if (this._refTexture && this._ownRefractionTexture) {
  81835. this._refTexture.dispose();
  81836. this._refTexture = null;
  81837. }
  81838. _super.prototype.dispose.call(this, camera);
  81839. };
  81840. return RefractionPostProcess;
  81841. }(BABYLON.PostProcess));
  81842. BABYLON.RefractionPostProcess = RefractionPostProcess;
  81843. })(BABYLON || (BABYLON = {}));
  81844. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  81845. var BABYLON;
  81846. (function (BABYLON) {
  81847. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  81848. __extends(BlackAndWhitePostProcess, _super);
  81849. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  81850. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  81851. _this.degree = 1;
  81852. _this.onApplyObservable.add(function (effect) {
  81853. effect.setFloat("degree", _this.degree);
  81854. });
  81855. return _this;
  81856. }
  81857. return BlackAndWhitePostProcess;
  81858. }(BABYLON.PostProcess));
  81859. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  81860. })(BABYLON || (BABYLON = {}));
  81861. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  81862. var BABYLON;
  81863. (function (BABYLON) {
  81864. /**
  81865. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  81866. * input texture to perform effects such as edge detection or sharpening
  81867. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  81868. */
  81869. var ConvolutionPostProcess = /** @class */ (function (_super) {
  81870. __extends(ConvolutionPostProcess, _super);
  81871. /**
  81872. * Creates a new instance ConvolutionPostProcess
  81873. * @param name The name of the effect.
  81874. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  81875. * @param options The required width/height ratio to downsize to before computing the render pass.
  81876. * @param camera The camera to apply the render pass to.
  81877. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  81878. * @param engine The engine which the post process will be applied. (default: current engine)
  81879. * @param reusable If the post process can be reused on the same frame. (default: false)
  81880. * @param textureType Type of textures used when performing the post process. (default: 0)
  81881. */
  81882. function ConvolutionPostProcess(name,
  81883. /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
  81884. kernel, options, camera, samplingMode, engine, reusable, textureType) {
  81885. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  81886. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  81887. _this.kernel = kernel;
  81888. _this.onApply = function (effect) {
  81889. effect.setFloat2("screenSize", _this.width, _this.height);
  81890. effect.setArray("kernel", _this.kernel);
  81891. };
  81892. return _this;
  81893. }
  81894. // Statics
  81895. /**
  81896. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  81897. */
  81898. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  81899. /**
  81900. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  81901. */
  81902. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  81903. /**
  81904. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  81905. */
  81906. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  81907. /**
  81908. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  81909. */
  81910. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  81911. /**
  81912. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  81913. */
  81914. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  81915. /**
  81916. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  81917. */
  81918. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  81919. return ConvolutionPostProcess;
  81920. }(BABYLON.PostProcess));
  81921. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  81922. })(BABYLON || (BABYLON = {}));
  81923. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  81924. var BABYLON;
  81925. (function (BABYLON) {
  81926. var FilterPostProcess = /** @class */ (function (_super) {
  81927. __extends(FilterPostProcess, _super);
  81928. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  81929. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  81930. _this.kernelMatrix = kernelMatrix;
  81931. _this.onApply = function (effect) {
  81932. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  81933. };
  81934. return _this;
  81935. }
  81936. return FilterPostProcess;
  81937. }(BABYLON.PostProcess));
  81938. BABYLON.FilterPostProcess = FilterPostProcess;
  81939. })(BABYLON || (BABYLON = {}));
  81940. //# sourceMappingURL=babylon.filterPostProcess.js.map
  81941. var BABYLON;
  81942. (function (BABYLON) {
  81943. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  81944. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  81945. __extends(VolumetricLightScatteringPostProcess, _super);
  81946. /**
  81947. * @constructor
  81948. * @param {string} name - The post-process name
  81949. * @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)
  81950. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  81951. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  81952. * @param {number} samples - The post-process quality, default 100
  81953. * @param {number} samplingMode - The post-process filtering mode
  81954. * @param {BABYLON.Engine} engine - The babylon engine
  81955. * @param {boolean} reusable - If the post-process is reusable
  81956. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided
  81957. */
  81958. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  81959. if (samples === void 0) { samples = 100; }
  81960. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  81961. 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;
  81962. _this._screenCoordinates = BABYLON.Vector2.Zero();
  81963. /**
  81964. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  81965. */
  81966. _this.customMeshPosition = BABYLON.Vector3.Zero();
  81967. /**
  81968. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  81969. */
  81970. _this.useCustomMeshPosition = false;
  81971. /**
  81972. * If the post-process should inverse the light scattering direction
  81973. */
  81974. _this.invert = true;
  81975. /**
  81976. * Array containing the excluded meshes not rendered in the internal pass
  81977. */
  81978. _this.excludedMeshes = new Array();
  81979. /**
  81980. * Controls the overall intensity of the post-process
  81981. */
  81982. _this.exposure = 0.3;
  81983. /**
  81984. * Dissipates each sample's contribution in range [0, 1]
  81985. */
  81986. _this.decay = 0.96815;
  81987. /**
  81988. * Controls the overall intensity of each sample
  81989. */
  81990. _this.weight = 0.58767;
  81991. /**
  81992. * Controls the density of each sample
  81993. */
  81994. _this.density = 0.926;
  81995. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  81996. engine = scene.getEngine();
  81997. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  81998. // Configure mesh
  81999. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  82000. // Configure
  82001. _this._createPass(scene, ratio.passRatio || ratio);
  82002. _this.onActivate = function (camera) {
  82003. if (!_this.isSupported) {
  82004. _this.dispose(camera);
  82005. }
  82006. _this.onActivate = null;
  82007. };
  82008. _this.onApplyObservable.add(function (effect) {
  82009. _this._updateMeshScreenCoordinates(scene);
  82010. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  82011. effect.setFloat("exposure", _this.exposure);
  82012. effect.setFloat("decay", _this.decay);
  82013. effect.setFloat("weight", _this.weight);
  82014. effect.setFloat("density", _this.density);
  82015. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  82016. });
  82017. return _this;
  82018. }
  82019. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  82020. get: function () {
  82021. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  82022. return false;
  82023. },
  82024. set: function (useDiffuseColor) {
  82025. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  82026. },
  82027. enumerable: true,
  82028. configurable: true
  82029. });
  82030. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  82031. return "VolumetricLightScatteringPostProcess";
  82032. };
  82033. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  82034. var mesh = subMesh.getMesh();
  82035. // Render this.mesh as default
  82036. if (mesh === this.mesh && mesh.material) {
  82037. return mesh.material.isReady(mesh);
  82038. }
  82039. var defines = [];
  82040. var attribs = [BABYLON.VertexBuffer.PositionKind];
  82041. var material = subMesh.getMaterial();
  82042. // Alpha test
  82043. if (material) {
  82044. if (material.needAlphaTesting()) {
  82045. defines.push("#define ALPHATEST");
  82046. }
  82047. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  82048. attribs.push(BABYLON.VertexBuffer.UVKind);
  82049. defines.push("#define UV1");
  82050. }
  82051. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  82052. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  82053. defines.push("#define UV2");
  82054. }
  82055. }
  82056. // Bones
  82057. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  82058. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  82059. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  82060. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  82061. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  82062. }
  82063. else {
  82064. defines.push("#define NUM_BONE_INFLUENCERS 0");
  82065. }
  82066. // Instances
  82067. if (useInstances) {
  82068. defines.push("#define INSTANCES");
  82069. attribs.push("world0");
  82070. attribs.push("world1");
  82071. attribs.push("world2");
  82072. attribs.push("world3");
  82073. }
  82074. // Get correct effect
  82075. var join = defines.join("\n");
  82076. if (this._cachedDefines !== join) {
  82077. this._cachedDefines = join;
  82078. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  82079. }
  82080. return this._volumetricLightScatteringPass.isReady();
  82081. };
  82082. /**
  82083. * Sets the new light position for light scattering effect
  82084. * @param {BABYLON.Vector3} The new custom light position
  82085. */
  82086. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  82087. this.customMeshPosition = position;
  82088. };
  82089. /**
  82090. * Returns the light position for light scattering effect
  82091. * @return {BABYLON.Vector3} The custom light position
  82092. */
  82093. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  82094. return this.customMeshPosition;
  82095. };
  82096. /**
  82097. * Disposes the internal assets and detaches the post-process from the camera
  82098. */
  82099. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  82100. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  82101. if (rttIndex !== -1) {
  82102. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  82103. }
  82104. this._volumetricLightScatteringRTT.dispose();
  82105. _super.prototype.dispose.call(this, camera);
  82106. };
  82107. /**
  82108. * Returns the render target texture used by the post-process
  82109. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  82110. */
  82111. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  82112. return this._volumetricLightScatteringRTT;
  82113. };
  82114. // Private methods
  82115. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  82116. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  82117. return true;
  82118. }
  82119. return false;
  82120. };
  82121. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  82122. var _this = this;
  82123. var engine = scene.getEngine();
  82124. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  82125. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82126. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82127. this._volumetricLightScatteringRTT.renderList = null;
  82128. this._volumetricLightScatteringRTT.renderParticles = false;
  82129. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  82130. var camera = this.getCamera();
  82131. if (camera) {
  82132. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  82133. }
  82134. else {
  82135. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  82136. }
  82137. // Custom render function for submeshes
  82138. var renderSubMesh = function (subMesh) {
  82139. var mesh = subMesh.getRenderingMesh();
  82140. if (_this._meshExcluded(mesh)) {
  82141. return;
  82142. }
  82143. var material = subMesh.getMaterial();
  82144. if (!material) {
  82145. return;
  82146. }
  82147. var scene = mesh.getScene();
  82148. var engine = scene.getEngine();
  82149. // Culling
  82150. engine.setState(material.backFaceCulling);
  82151. // Managing instances
  82152. var batch = mesh._getInstancesRenderList(subMesh._id);
  82153. if (batch.mustReturn) {
  82154. return;
  82155. }
  82156. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  82157. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  82158. var effect = _this._volumetricLightScatteringPass;
  82159. if (mesh === _this.mesh) {
  82160. if (subMesh.effect) {
  82161. effect = subMesh.effect;
  82162. }
  82163. else {
  82164. effect = material.getEffect();
  82165. }
  82166. }
  82167. engine.enableEffect(effect);
  82168. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  82169. if (mesh === _this.mesh) {
  82170. material.bind(mesh.getWorldMatrix(), mesh);
  82171. }
  82172. else {
  82173. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  82174. // Alpha test
  82175. if (material && material.needAlphaTesting()) {
  82176. var alphaTexture = material.getAlphaTestTexture();
  82177. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  82178. if (alphaTexture) {
  82179. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  82180. }
  82181. }
  82182. // Bones
  82183. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  82184. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  82185. }
  82186. }
  82187. // Draw
  82188. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  82189. }
  82190. };
  82191. // Render target texture callbacks
  82192. var savedSceneClearColor;
  82193. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  82194. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  82195. savedSceneClearColor = scene.clearColor;
  82196. scene.clearColor = sceneClearColor;
  82197. });
  82198. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  82199. scene.clearColor = savedSceneClearColor;
  82200. });
  82201. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  82202. var engine = scene.getEngine();
  82203. var index;
  82204. if (depthOnlySubMeshes.length) {
  82205. engine.setColorWrite(false);
  82206. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  82207. renderSubMesh(depthOnlySubMeshes.data[index]);
  82208. }
  82209. engine.setColorWrite(true);
  82210. }
  82211. for (index = 0; index < opaqueSubMeshes.length; index++) {
  82212. renderSubMesh(opaqueSubMeshes.data[index]);
  82213. }
  82214. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  82215. renderSubMesh(alphaTestSubMeshes.data[index]);
  82216. }
  82217. if (transparentSubMeshes.length) {
  82218. // Sort sub meshes
  82219. for (index = 0; index < transparentSubMeshes.length; index++) {
  82220. var submesh = transparentSubMeshes.data[index];
  82221. var boundingInfo = submesh.getBoundingInfo();
  82222. if (boundingInfo && scene.activeCamera) {
  82223. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  82224. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  82225. }
  82226. }
  82227. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  82228. sortedArray.sort(function (a, b) {
  82229. // Alpha index first
  82230. if (a._alphaIndex > b._alphaIndex) {
  82231. return 1;
  82232. }
  82233. if (a._alphaIndex < b._alphaIndex) {
  82234. return -1;
  82235. }
  82236. // Then distance to camera
  82237. if (a._distanceToCamera < b._distanceToCamera) {
  82238. return 1;
  82239. }
  82240. if (a._distanceToCamera > b._distanceToCamera) {
  82241. return -1;
  82242. }
  82243. return 0;
  82244. });
  82245. // Render sub meshes
  82246. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  82247. for (index = 0; index < sortedArray.length; index++) {
  82248. renderSubMesh(sortedArray[index]);
  82249. }
  82250. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  82251. }
  82252. };
  82253. };
  82254. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  82255. var transform = scene.getTransformMatrix();
  82256. var meshPosition;
  82257. if (this.useCustomMeshPosition) {
  82258. meshPosition = this.customMeshPosition;
  82259. }
  82260. else if (this.attachedNode) {
  82261. meshPosition = this.attachedNode.position;
  82262. }
  82263. else {
  82264. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  82265. }
  82266. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  82267. this._screenCoordinates.x = pos.x / this._viewPort.width;
  82268. this._screenCoordinates.y = pos.y / this._viewPort.height;
  82269. if (this.invert)
  82270. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  82271. };
  82272. // Static methods
  82273. /**
  82274. * Creates a default mesh for the Volumeric Light Scattering post-process
  82275. * @param {string} The mesh name
  82276. * @param {BABYLON.Scene} The scene where to create the mesh
  82277. * @return {BABYLON.Mesh} the default mesh
  82278. */
  82279. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  82280. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  82281. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  82282. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  82283. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  82284. mesh.material = material;
  82285. return mesh;
  82286. };
  82287. __decorate([
  82288. BABYLON.serializeAsVector3()
  82289. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  82290. __decorate([
  82291. BABYLON.serialize()
  82292. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  82293. __decorate([
  82294. BABYLON.serialize()
  82295. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  82296. __decorate([
  82297. BABYLON.serializeAsMeshReference()
  82298. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  82299. __decorate([
  82300. BABYLON.serialize()
  82301. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  82302. __decorate([
  82303. BABYLON.serialize()
  82304. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  82305. __decorate([
  82306. BABYLON.serialize()
  82307. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  82308. __decorate([
  82309. BABYLON.serialize()
  82310. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  82311. __decorate([
  82312. BABYLON.serialize()
  82313. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  82314. return VolumetricLightScatteringPostProcess;
  82315. }(BABYLON.PostProcess));
  82316. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  82317. })(BABYLON || (BABYLON = {}));
  82318. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  82319. //
  82320. // This post-process allows the modification of rendered colors by using
  82321. // a 'look-up table' (LUT). This effect is also called Color Grading.
  82322. //
  82323. // The object needs to be provided an url to a texture containing the color
  82324. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  82325. // Use an image editing software to tweak the LUT to match your needs.
  82326. //
  82327. // For an example of a color LUT, see here:
  82328. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  82329. // For explanations on color grading, see here:
  82330. // http://udn.epicgames.com/Three/ColorGrading.html
  82331. //
  82332. var BABYLON;
  82333. (function (BABYLON) {
  82334. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  82335. __extends(ColorCorrectionPostProcess, _super);
  82336. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  82337. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  82338. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  82339. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  82340. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82341. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82342. _this.onApply = function (effect) {
  82343. effect.setTexture("colorTable", _this._colorTableTexture);
  82344. };
  82345. return _this;
  82346. }
  82347. return ColorCorrectionPostProcess;
  82348. }(BABYLON.PostProcess));
  82349. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  82350. })(BABYLON || (BABYLON = {}));
  82351. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  82352. var BABYLON;
  82353. (function (BABYLON) {
  82354. /** Defines operator used for tonemapping */
  82355. var TonemappingOperator;
  82356. (function (TonemappingOperator) {
  82357. /** Hable */
  82358. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  82359. /** Reinhard */
  82360. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  82361. /** HejiDawson */
  82362. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  82363. /** Photographic */
  82364. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  82365. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  82366. ;
  82367. /**
  82368. * Defines a post process to apply tone mapping
  82369. */
  82370. var TonemapPostProcess = /** @class */ (function (_super) {
  82371. __extends(TonemapPostProcess, _super);
  82372. /**
  82373. * Creates a new TonemapPostProcess
  82374. * @param name defines the name of the postprocess
  82375. * @param _operator defines the operator to use
  82376. * @param exposureAdjustment defines the required exposure adjustement
  82377. * @param camera defines the camera to use (can be null)
  82378. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  82379. * @param engine defines the hosting engine (can be ignore if camera is set)
  82380. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  82381. */
  82382. function TonemapPostProcess(name, _operator,
  82383. /** Defines the required exposure adjustement */
  82384. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  82385. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  82386. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82387. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  82388. _this._operator = _operator;
  82389. _this.exposureAdjustment = exposureAdjustment;
  82390. var defines = "#define ";
  82391. if (_this._operator === TonemappingOperator.Hable)
  82392. defines += "HABLE_TONEMAPPING";
  82393. else if (_this._operator === TonemappingOperator.Reinhard)
  82394. defines += "REINHARD_TONEMAPPING";
  82395. else if (_this._operator === TonemappingOperator.HejiDawson)
  82396. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  82397. else if (_this._operator === TonemappingOperator.Photographic)
  82398. defines += "PHOTOGRAPHIC_TONEMAPPING";
  82399. //sadly a second call to create the effect.
  82400. _this.updateEffect(defines);
  82401. _this.onApply = function (effect) {
  82402. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  82403. };
  82404. return _this;
  82405. }
  82406. return TonemapPostProcess;
  82407. }(BABYLON.PostProcess));
  82408. BABYLON.TonemapPostProcess = TonemapPostProcess;
  82409. })(BABYLON || (BABYLON = {}));
  82410. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  82411. var BABYLON;
  82412. (function (BABYLON) {
  82413. var DisplayPassPostProcess = /** @class */ (function (_super) {
  82414. __extends(DisplayPassPostProcess, _super);
  82415. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  82416. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  82417. }
  82418. return DisplayPassPostProcess;
  82419. }(BABYLON.PostProcess));
  82420. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  82421. })(BABYLON || (BABYLON = {}));
  82422. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  82423. var BABYLON;
  82424. (function (BABYLON) {
  82425. var HighlightsPostProcess = /** @class */ (function (_super) {
  82426. __extends(HighlightsPostProcess, _super);
  82427. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  82428. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82429. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  82430. }
  82431. return HighlightsPostProcess;
  82432. }(BABYLON.PostProcess));
  82433. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  82434. })(BABYLON || (BABYLON = {}));
  82435. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  82436. var BABYLON;
  82437. (function (BABYLON) {
  82438. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  82439. __extends(ImageProcessingPostProcess, _super);
  82440. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  82441. if (camera === void 0) { camera = null; }
  82442. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82443. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  82444. _this._fromLinearSpace = true;
  82445. /**
  82446. * Defines cache preventing GC.
  82447. */
  82448. _this._defines = {
  82449. IMAGEPROCESSING: false,
  82450. VIGNETTE: false,
  82451. VIGNETTEBLENDMODEMULTIPLY: false,
  82452. VIGNETTEBLENDMODEOPAQUE: false,
  82453. TONEMAPPING: false,
  82454. TONEMAPPING_ACES: false,
  82455. CONTRAST: false,
  82456. COLORCURVES: false,
  82457. COLORGRADING: false,
  82458. COLORGRADING3D: false,
  82459. FROMLINEARSPACE: false,
  82460. SAMPLER3DGREENDEPTH: false,
  82461. SAMPLER3DBGRMAP: false,
  82462. IMAGEPROCESSINGPOSTPROCESS: false,
  82463. EXPOSURE: false,
  82464. };
  82465. // Setup the configuration as forced by the constructor. This would then not force the
  82466. // scene materials output in linear space and let untouched the default forward pass.
  82467. if (imageProcessingConfiguration) {
  82468. imageProcessingConfiguration.applyByPostProcess = true;
  82469. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  82470. // This will cause the shader to be compiled
  82471. _this.fromLinearSpace = false;
  82472. }
  82473. // Setup the default processing configuration to the scene.
  82474. else {
  82475. _this._attachImageProcessingConfiguration(null, true);
  82476. _this.imageProcessingConfiguration.applyByPostProcess = true;
  82477. }
  82478. _this.onApply = function (effect) {
  82479. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  82480. };
  82481. return _this;
  82482. }
  82483. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  82484. /**
  82485. * Gets the image processing configuration used either in this material.
  82486. */
  82487. get: function () {
  82488. return this._imageProcessingConfiguration;
  82489. },
  82490. /**
  82491. * Sets the Default image processing configuration used either in the this material.
  82492. *
  82493. * If sets to null, the scene one is in use.
  82494. */
  82495. set: function (value) {
  82496. this._attachImageProcessingConfiguration(value);
  82497. },
  82498. enumerable: true,
  82499. configurable: true
  82500. });
  82501. /**
  82502. * Attaches a new image processing configuration to the PBR Material.
  82503. * @param configuration
  82504. */
  82505. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  82506. var _this = this;
  82507. if (doNotBuild === void 0) { doNotBuild = false; }
  82508. if (configuration === this._imageProcessingConfiguration) {
  82509. return;
  82510. }
  82511. // Detaches observer.
  82512. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  82513. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  82514. }
  82515. // Pick the scene configuration if needed.
  82516. if (!configuration) {
  82517. var scene = null;
  82518. var engine = this.getEngine();
  82519. var camera = this.getCamera();
  82520. if (camera) {
  82521. scene = camera.getScene();
  82522. }
  82523. else if (engine && engine.scenes) {
  82524. var scenes = engine.scenes;
  82525. scene = scenes[scenes.length - 1];
  82526. }
  82527. else {
  82528. scene = BABYLON.Engine.LastCreatedScene;
  82529. }
  82530. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  82531. }
  82532. else {
  82533. this._imageProcessingConfiguration = configuration;
  82534. }
  82535. // Attaches observer.
  82536. if (this._imageProcessingConfiguration) {
  82537. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  82538. _this._updateParameters();
  82539. });
  82540. }
  82541. // Ensure the effect will be rebuilt.
  82542. if (!doNotBuild) {
  82543. this._updateParameters();
  82544. }
  82545. };
  82546. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  82547. /**
  82548. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  82549. */
  82550. get: function () {
  82551. return this.imageProcessingConfiguration.colorCurves;
  82552. },
  82553. /**
  82554. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  82555. */
  82556. set: function (value) {
  82557. this.imageProcessingConfiguration.colorCurves = value;
  82558. },
  82559. enumerable: true,
  82560. configurable: true
  82561. });
  82562. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  82563. /**
  82564. * Gets wether the color curves effect is enabled.
  82565. */
  82566. get: function () {
  82567. return this.imageProcessingConfiguration.colorCurvesEnabled;
  82568. },
  82569. /**
  82570. * Sets wether the color curves effect is enabled.
  82571. */
  82572. set: function (value) {
  82573. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  82574. },
  82575. enumerable: true,
  82576. configurable: true
  82577. });
  82578. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  82579. /**
  82580. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  82581. */
  82582. get: function () {
  82583. return this.imageProcessingConfiguration.colorGradingTexture;
  82584. },
  82585. /**
  82586. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  82587. */
  82588. set: function (value) {
  82589. this.imageProcessingConfiguration.colorGradingTexture = value;
  82590. },
  82591. enumerable: true,
  82592. configurable: true
  82593. });
  82594. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  82595. /**
  82596. * Gets wether the color grading effect is enabled.
  82597. */
  82598. get: function () {
  82599. return this.imageProcessingConfiguration.colorGradingEnabled;
  82600. },
  82601. /**
  82602. * Gets wether the color grading effect is enabled.
  82603. */
  82604. set: function (value) {
  82605. this.imageProcessingConfiguration.colorGradingEnabled = value;
  82606. },
  82607. enumerable: true,
  82608. configurable: true
  82609. });
  82610. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  82611. /**
  82612. * Gets exposure used in the effect.
  82613. */
  82614. get: function () {
  82615. return this.imageProcessingConfiguration.exposure;
  82616. },
  82617. /**
  82618. * Sets exposure used in the effect.
  82619. */
  82620. set: function (value) {
  82621. this.imageProcessingConfiguration.exposure = value;
  82622. },
  82623. enumerable: true,
  82624. configurable: true
  82625. });
  82626. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  82627. /**
  82628. * Gets wether tonemapping is enabled or not.
  82629. */
  82630. get: function () {
  82631. return this._imageProcessingConfiguration.toneMappingEnabled;
  82632. },
  82633. /**
  82634. * Sets wether tonemapping is enabled or not
  82635. */
  82636. set: function (value) {
  82637. this._imageProcessingConfiguration.toneMappingEnabled = value;
  82638. },
  82639. enumerable: true,
  82640. configurable: true
  82641. });
  82642. ;
  82643. ;
  82644. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  82645. /**
  82646. * Gets contrast used in the effect.
  82647. */
  82648. get: function () {
  82649. return this.imageProcessingConfiguration.contrast;
  82650. },
  82651. /**
  82652. * Sets contrast used in the effect.
  82653. */
  82654. set: function (value) {
  82655. this.imageProcessingConfiguration.contrast = value;
  82656. },
  82657. enumerable: true,
  82658. configurable: true
  82659. });
  82660. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  82661. /**
  82662. * Gets Vignette stretch size.
  82663. */
  82664. get: function () {
  82665. return this.imageProcessingConfiguration.vignetteStretch;
  82666. },
  82667. /**
  82668. * Sets Vignette stretch size.
  82669. */
  82670. set: function (value) {
  82671. this.imageProcessingConfiguration.vignetteStretch = value;
  82672. },
  82673. enumerable: true,
  82674. configurable: true
  82675. });
  82676. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  82677. /**
  82678. * Gets Vignette centre X Offset.
  82679. */
  82680. get: function () {
  82681. return this.imageProcessingConfiguration.vignetteCentreX;
  82682. },
  82683. /**
  82684. * Sets Vignette centre X Offset.
  82685. */
  82686. set: function (value) {
  82687. this.imageProcessingConfiguration.vignetteCentreX = value;
  82688. },
  82689. enumerable: true,
  82690. configurable: true
  82691. });
  82692. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  82693. /**
  82694. * Gets Vignette centre Y Offset.
  82695. */
  82696. get: function () {
  82697. return this.imageProcessingConfiguration.vignetteCentreY;
  82698. },
  82699. /**
  82700. * Sets Vignette centre Y Offset.
  82701. */
  82702. set: function (value) {
  82703. this.imageProcessingConfiguration.vignetteCentreY = value;
  82704. },
  82705. enumerable: true,
  82706. configurable: true
  82707. });
  82708. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  82709. /**
  82710. * Gets Vignette weight or intensity of the vignette effect.
  82711. */
  82712. get: function () {
  82713. return this.imageProcessingConfiguration.vignetteWeight;
  82714. },
  82715. /**
  82716. * Sets Vignette weight or intensity of the vignette effect.
  82717. */
  82718. set: function (value) {
  82719. this.imageProcessingConfiguration.vignetteWeight = value;
  82720. },
  82721. enumerable: true,
  82722. configurable: true
  82723. });
  82724. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  82725. /**
  82726. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  82727. * if vignetteEnabled is set to true.
  82728. */
  82729. get: function () {
  82730. return this.imageProcessingConfiguration.vignetteColor;
  82731. },
  82732. /**
  82733. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  82734. * if vignetteEnabled is set to true.
  82735. */
  82736. set: function (value) {
  82737. this.imageProcessingConfiguration.vignetteColor = value;
  82738. },
  82739. enumerable: true,
  82740. configurable: true
  82741. });
  82742. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  82743. /**
  82744. * Gets Camera field of view used by the Vignette effect.
  82745. */
  82746. get: function () {
  82747. return this.imageProcessingConfiguration.vignetteCameraFov;
  82748. },
  82749. /**
  82750. * Sets Camera field of view used by the Vignette effect.
  82751. */
  82752. set: function (value) {
  82753. this.imageProcessingConfiguration.vignetteCameraFov = value;
  82754. },
  82755. enumerable: true,
  82756. configurable: true
  82757. });
  82758. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  82759. /**
  82760. * Gets the vignette blend mode allowing different kind of effect.
  82761. */
  82762. get: function () {
  82763. return this.imageProcessingConfiguration.vignetteBlendMode;
  82764. },
  82765. /**
  82766. * Sets the vignette blend mode allowing different kind of effect.
  82767. */
  82768. set: function (value) {
  82769. this.imageProcessingConfiguration.vignetteBlendMode = value;
  82770. },
  82771. enumerable: true,
  82772. configurable: true
  82773. });
  82774. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  82775. /**
  82776. * Gets wether the vignette effect is enabled.
  82777. */
  82778. get: function () {
  82779. return this.imageProcessingConfiguration.vignetteEnabled;
  82780. },
  82781. /**
  82782. * Sets wether the vignette effect is enabled.
  82783. */
  82784. set: function (value) {
  82785. this.imageProcessingConfiguration.vignetteEnabled = value;
  82786. },
  82787. enumerable: true,
  82788. configurable: true
  82789. });
  82790. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  82791. /**
  82792. * Gets wether the input of the processing is in Gamma or Linear Space.
  82793. */
  82794. get: function () {
  82795. return this._fromLinearSpace;
  82796. },
  82797. /**
  82798. * Sets wether the input of the processing is in Gamma or Linear Space.
  82799. */
  82800. set: function (value) {
  82801. if (this._fromLinearSpace === value) {
  82802. return;
  82803. }
  82804. this._fromLinearSpace = value;
  82805. this._updateParameters();
  82806. },
  82807. enumerable: true,
  82808. configurable: true
  82809. });
  82810. ImageProcessingPostProcess.prototype.getClassName = function () {
  82811. return "ImageProcessingPostProcess";
  82812. };
  82813. ImageProcessingPostProcess.prototype._updateParameters = function () {
  82814. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  82815. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  82816. var defines = "";
  82817. for (var define in this._defines) {
  82818. if (this._defines[define]) {
  82819. defines += "#define " + define + ";\r\n";
  82820. }
  82821. }
  82822. var samplers = ["textureSampler"];
  82823. var uniforms = ["scale"];
  82824. if (BABYLON.ImageProcessingConfiguration) {
  82825. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  82826. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  82827. }
  82828. this.updateEffect(defines, uniforms, samplers);
  82829. };
  82830. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  82831. _super.prototype.dispose.call(this, camera);
  82832. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  82833. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  82834. }
  82835. if (this._imageProcessingConfiguration) {
  82836. this.imageProcessingConfiguration.applyByPostProcess = false;
  82837. }
  82838. };
  82839. __decorate([
  82840. BABYLON.serialize()
  82841. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  82842. return ImageProcessingPostProcess;
  82843. }(BABYLON.PostProcess));
  82844. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  82845. })(BABYLON || (BABYLON = {}));
  82846. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  82847. var BABYLON;
  82848. (function (BABYLON) {
  82849. /**
  82850. * Class used to store bone information
  82851. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  82852. */
  82853. var Bone = /** @class */ (function (_super) {
  82854. __extends(Bone, _super);
  82855. /**
  82856. * Create a new bone
  82857. * @param name defines the bone name
  82858. * @param skeleton defines the parent skeleton
  82859. * @param parentBone defines the parent (can be null if the bone is the root)
  82860. * @param localMatrix defines the local matrix
  82861. * @param restPose defines the rest pose matrix
  82862. * @param baseMatrix defines the base matrix
  82863. * @param index defines index of the bone in the hiearchy
  82864. */
  82865. function Bone(
  82866. /**
  82867. * defines the bone name
  82868. */
  82869. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  82870. if (parentBone === void 0) { parentBone = null; }
  82871. if (localMatrix === void 0) { localMatrix = null; }
  82872. if (restPose === void 0) { restPose = null; }
  82873. if (baseMatrix === void 0) { baseMatrix = null; }
  82874. if (index === void 0) { index = null; }
  82875. var _this = _super.call(this, name, skeleton.getScene()) || this;
  82876. _this.name = name;
  82877. /**
  82878. * Gets the list of child bones
  82879. */
  82880. _this.children = new Array();
  82881. /** Gets the animations associated with this bone */
  82882. _this.animations = new Array();
  82883. /**
  82884. * @hidden Internal only
  82885. * Set this value to map this bone to a different index in the transform matrices
  82886. * Set this value to -1 to exclude the bone from the transform matrices
  82887. */
  82888. _this._index = null;
  82889. _this._absoluteTransform = new BABYLON.Matrix();
  82890. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  82891. _this._scalingDeterminant = 1;
  82892. _this._worldTransform = new BABYLON.Matrix();
  82893. _this._needToDecompose = true;
  82894. _this._needToCompose = false;
  82895. _this._skeleton = skeleton;
  82896. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  82897. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  82898. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  82899. _this._index = index;
  82900. skeleton.bones.push(_this);
  82901. _this.setParent(parentBone, false);
  82902. if (baseMatrix || localMatrix) {
  82903. _this._updateDifferenceMatrix();
  82904. }
  82905. return _this;
  82906. }
  82907. Object.defineProperty(Bone.prototype, "_matrix", {
  82908. /** @hidden */
  82909. get: function () {
  82910. this._compose();
  82911. return this._localMatrix;
  82912. },
  82913. /** @hidden */
  82914. set: function (value) {
  82915. this._localMatrix.copyFrom(value);
  82916. this._needToDecompose = true;
  82917. },
  82918. enumerable: true,
  82919. configurable: true
  82920. });
  82921. // Members
  82922. /**
  82923. * Gets the parent skeleton
  82924. * @returns a skeleton
  82925. */
  82926. Bone.prototype.getSkeleton = function () {
  82927. return this._skeleton;
  82928. };
  82929. /**
  82930. * Gets parent bone
  82931. * @returns a bone or null if the bone is the root of the bone hierarchy
  82932. */
  82933. Bone.prototype.getParent = function () {
  82934. return this._parent;
  82935. };
  82936. /**
  82937. * Sets the parent bone
  82938. * @param parent defines the parent (can be null if the bone is the root)
  82939. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  82940. */
  82941. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  82942. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  82943. if (this._parent === parent) {
  82944. return;
  82945. }
  82946. if (this._parent) {
  82947. var index = this._parent.children.indexOf(this);
  82948. if (index !== -1) {
  82949. this._parent.children.splice(index, 1);
  82950. }
  82951. }
  82952. this._parent = parent;
  82953. if (this._parent) {
  82954. this._parent.children.push(this);
  82955. }
  82956. if (updateDifferenceMatrix) {
  82957. this._updateDifferenceMatrix();
  82958. }
  82959. this.markAsDirty();
  82960. };
  82961. /**
  82962. * Gets the local matrix
  82963. * @returns a matrix
  82964. */
  82965. Bone.prototype.getLocalMatrix = function () {
  82966. this._compose();
  82967. return this._localMatrix;
  82968. };
  82969. /**
  82970. * Gets the base matrix (initial matrix which remains unchanged)
  82971. * @returns a matrix
  82972. */
  82973. Bone.prototype.getBaseMatrix = function () {
  82974. return this._baseMatrix;
  82975. };
  82976. /**
  82977. * Gets the rest pose matrix
  82978. * @returns a matrix
  82979. */
  82980. Bone.prototype.getRestPose = function () {
  82981. return this._restPose;
  82982. };
  82983. /**
  82984. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  82985. */
  82986. Bone.prototype.getWorldMatrix = function () {
  82987. return this._worldTransform;
  82988. };
  82989. /**
  82990. * Sets the local matrix to rest pose matrix
  82991. */
  82992. Bone.prototype.returnToRest = function () {
  82993. this.updateMatrix(this._restPose.clone());
  82994. };
  82995. /**
  82996. * Gets the inverse of the absolute transform matrix.
  82997. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  82998. * @returns a matrix
  82999. */
  83000. Bone.prototype.getInvertedAbsoluteTransform = function () {
  83001. return this._invertedAbsoluteTransform;
  83002. };
  83003. /**
  83004. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  83005. * @returns a matrix
  83006. */
  83007. Bone.prototype.getAbsoluteTransform = function () {
  83008. return this._absoluteTransform;
  83009. };
  83010. Object.defineProperty(Bone.prototype, "position", {
  83011. // Properties (matches AbstractMesh properties)
  83012. /** Gets or sets current position (in local space) */
  83013. get: function () {
  83014. this._decompose();
  83015. return this._localPosition;
  83016. },
  83017. set: function (newPosition) {
  83018. this._decompose();
  83019. this._localPosition.copyFrom(newPosition);
  83020. this._markAsDirtyAndCompose();
  83021. },
  83022. enumerable: true,
  83023. configurable: true
  83024. });
  83025. Object.defineProperty(Bone.prototype, "rotation", {
  83026. /** Gets or sets current rotation (in local space) */
  83027. get: function () {
  83028. return this.getRotation();
  83029. },
  83030. set: function (newRotation) {
  83031. this.setRotation(newRotation);
  83032. },
  83033. enumerable: true,
  83034. configurable: true
  83035. });
  83036. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  83037. /** Gets or sets current rotation quaternion (in local space) */
  83038. get: function () {
  83039. this._decompose();
  83040. return this._localRotation;
  83041. },
  83042. set: function (newRotation) {
  83043. this.setRotationQuaternion(newRotation);
  83044. },
  83045. enumerable: true,
  83046. configurable: true
  83047. });
  83048. Object.defineProperty(Bone.prototype, "scaling", {
  83049. /** Gets or sets current scaling (in local space) */
  83050. get: function () {
  83051. return this.getScale();
  83052. },
  83053. set: function (newScaling) {
  83054. this.setScale(newScaling);
  83055. },
  83056. enumerable: true,
  83057. configurable: true
  83058. });
  83059. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  83060. /**
  83061. * Gets the animation properties override
  83062. */
  83063. get: function () {
  83064. return this._skeleton.animationPropertiesOverride;
  83065. },
  83066. enumerable: true,
  83067. configurable: true
  83068. });
  83069. // Methods
  83070. Bone.prototype._decompose = function () {
  83071. if (!this._needToDecompose) {
  83072. return;
  83073. }
  83074. this._needToDecompose = false;
  83075. if (!this._localScaling) {
  83076. this._localScaling = BABYLON.Vector3.Zero();
  83077. this._localRotation = BABYLON.Quaternion.Zero();
  83078. this._localPosition = BABYLON.Vector3.Zero();
  83079. }
  83080. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  83081. };
  83082. Bone.prototype._compose = function () {
  83083. if (!this._needToCompose) {
  83084. return;
  83085. }
  83086. this._needToCompose = false;
  83087. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  83088. };
  83089. /**
  83090. * Update the base and local matrices
  83091. * @param matrix defines the new base or local matrix
  83092. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  83093. * @param updateLocalMatrix defines if the local matrix should be updated
  83094. */
  83095. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  83096. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  83097. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  83098. this._baseMatrix.copyFrom(matrix);
  83099. if (updateDifferenceMatrix) {
  83100. this._updateDifferenceMatrix();
  83101. }
  83102. if (updateLocalMatrix) {
  83103. this._localMatrix.copyFrom(matrix);
  83104. this._markAsDirtyAndDecompose();
  83105. }
  83106. else {
  83107. this.markAsDirty();
  83108. }
  83109. };
  83110. /** @hidden */
  83111. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  83112. if (updateChildren === void 0) { updateChildren = true; }
  83113. if (!rootMatrix) {
  83114. rootMatrix = this._baseMatrix;
  83115. }
  83116. if (this._parent) {
  83117. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  83118. }
  83119. else {
  83120. this._absoluteTransform.copyFrom(rootMatrix);
  83121. }
  83122. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  83123. if (updateChildren) {
  83124. for (var index = 0; index < this.children.length; index++) {
  83125. this.children[index]._updateDifferenceMatrix();
  83126. }
  83127. }
  83128. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  83129. };
  83130. /**
  83131. * Flag the bone as dirty (Forcing it to update everything)
  83132. */
  83133. Bone.prototype.markAsDirty = function () {
  83134. this._currentRenderId++;
  83135. this._childRenderId++;
  83136. this._skeleton._markAsDirty();
  83137. };
  83138. Bone.prototype._markAsDirtyAndCompose = function () {
  83139. this.markAsDirty();
  83140. this._needToCompose = true;
  83141. };
  83142. Bone.prototype._markAsDirtyAndDecompose = function () {
  83143. this.markAsDirty();
  83144. this._needToDecompose = true;
  83145. };
  83146. /**
  83147. * Copy an animation range from another bone
  83148. * @param source defines the source bone
  83149. * @param rangeName defines the range name to copy
  83150. * @param frameOffset defines the frame offset
  83151. * @param rescaleAsRequired defines if rescaling must be applied if required
  83152. * @param skelDimensionsRatio defines the scaling ratio
  83153. * @returns true if operation was successful
  83154. */
  83155. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  83156. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  83157. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  83158. // all animation may be coming from a library skeleton, so may need to create animation
  83159. if (this.animations.length === 0) {
  83160. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  83161. this.animations[0].setKeys([]);
  83162. }
  83163. // get animation info / verify there is such a range from the source bone
  83164. var sourceRange = source.animations[0].getRange(rangeName);
  83165. if (!sourceRange) {
  83166. return false;
  83167. }
  83168. var from = sourceRange.from;
  83169. var to = sourceRange.to;
  83170. var sourceKeys = source.animations[0].getKeys();
  83171. // rescaling prep
  83172. var sourceBoneLength = source.length;
  83173. var sourceParent = source.getParent();
  83174. var parent = this.getParent();
  83175. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  83176. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  83177. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  83178. var destKeys = this.animations[0].getKeys();
  83179. // loop vars declaration
  83180. var orig;
  83181. var origTranslation;
  83182. var mat;
  83183. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  83184. orig = sourceKeys[key];
  83185. if (orig.frame >= from && orig.frame <= to) {
  83186. if (rescaleAsRequired) {
  83187. mat = orig.value.clone();
  83188. // scale based on parent ratio, when bone has parent
  83189. if (parentScalingReqd) {
  83190. origTranslation = mat.getTranslation();
  83191. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  83192. // scale based on skeleton dimension ratio when root bone, and value is passed
  83193. }
  83194. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  83195. origTranslation = mat.getTranslation();
  83196. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  83197. // use original when root bone, and no data for skelDimensionsRatio
  83198. }
  83199. else {
  83200. mat = orig.value;
  83201. }
  83202. }
  83203. else {
  83204. mat = orig.value;
  83205. }
  83206. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  83207. }
  83208. }
  83209. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  83210. return true;
  83211. };
  83212. /**
  83213. * Translate the bone in local or world space
  83214. * @param vec The amount to translate the bone
  83215. * @param space The space that the translation is in
  83216. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83217. */
  83218. Bone.prototype.translate = function (vec, space, mesh) {
  83219. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83220. var lm = this.getLocalMatrix();
  83221. if (space == BABYLON.Space.LOCAL) {
  83222. lm.m[12] += vec.x;
  83223. lm.m[13] += vec.y;
  83224. lm.m[14] += vec.z;
  83225. }
  83226. else {
  83227. var wm = null;
  83228. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  83229. if (mesh) {
  83230. wm = mesh.getWorldMatrix();
  83231. }
  83232. this._skeleton.computeAbsoluteTransforms();
  83233. var tmat = Bone._tmpMats[0];
  83234. var tvec = Bone._tmpVecs[0];
  83235. if (this._parent) {
  83236. if (mesh && wm) {
  83237. tmat.copyFrom(this._parent.getAbsoluteTransform());
  83238. tmat.multiplyToRef(wm, tmat);
  83239. }
  83240. else {
  83241. tmat.copyFrom(this._parent.getAbsoluteTransform());
  83242. }
  83243. }
  83244. tmat.m[12] = 0;
  83245. tmat.m[13] = 0;
  83246. tmat.m[14] = 0;
  83247. tmat.invert();
  83248. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  83249. lm.m[12] += tvec.x;
  83250. lm.m[13] += tvec.y;
  83251. lm.m[14] += tvec.z;
  83252. }
  83253. this._markAsDirtyAndDecompose();
  83254. };
  83255. /**
  83256. * Set the postion of the bone in local or world space
  83257. * @param position The position to set the bone
  83258. * @param space The space that the position is in
  83259. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83260. */
  83261. Bone.prototype.setPosition = function (position, space, mesh) {
  83262. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83263. var lm = this.getLocalMatrix();
  83264. if (space == BABYLON.Space.LOCAL) {
  83265. lm.m[12] = position.x;
  83266. lm.m[13] = position.y;
  83267. lm.m[14] = position.z;
  83268. }
  83269. else {
  83270. var wm = null;
  83271. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  83272. if (mesh) {
  83273. wm = mesh.getWorldMatrix();
  83274. }
  83275. this._skeleton.computeAbsoluteTransforms();
  83276. var tmat = Bone._tmpMats[0];
  83277. var vec = Bone._tmpVecs[0];
  83278. if (this._parent) {
  83279. if (mesh && wm) {
  83280. tmat.copyFrom(this._parent.getAbsoluteTransform());
  83281. tmat.multiplyToRef(wm, tmat);
  83282. }
  83283. else {
  83284. tmat.copyFrom(this._parent.getAbsoluteTransform());
  83285. }
  83286. }
  83287. tmat.invert();
  83288. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  83289. lm.m[12] = vec.x;
  83290. lm.m[13] = vec.y;
  83291. lm.m[14] = vec.z;
  83292. }
  83293. this._markAsDirtyAndDecompose();
  83294. };
  83295. /**
  83296. * Set the absolute position of the bone (world space)
  83297. * @param position The position to set the bone
  83298. * @param mesh The mesh that this bone is attached to
  83299. */
  83300. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  83301. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  83302. };
  83303. /**
  83304. * Scale the bone on the x, y and z axes (in local space)
  83305. * @param x The amount to scale the bone on the x axis
  83306. * @param y The amount to scale the bone on the y axis
  83307. * @param z The amount to scale the bone on the z axis
  83308. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  83309. */
  83310. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  83311. if (scaleChildren === void 0) { scaleChildren = false; }
  83312. var locMat = this.getLocalMatrix();
  83313. // Apply new scaling on top of current local matrix
  83314. var scaleMat = Bone._tmpMats[0];
  83315. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  83316. scaleMat.multiplyToRef(locMat, locMat);
  83317. // Invert scaling matrix and apply the inverse to all children
  83318. scaleMat.invert();
  83319. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  83320. var child = _a[_i];
  83321. var cm = child.getLocalMatrix();
  83322. cm.multiplyToRef(scaleMat, cm);
  83323. cm.m[12] *= x;
  83324. cm.m[13] *= y;
  83325. cm.m[14] *= z;
  83326. child._markAsDirtyAndDecompose();
  83327. }
  83328. this._markAsDirtyAndDecompose();
  83329. if (scaleChildren) {
  83330. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  83331. var child = _c[_b];
  83332. child.scale(x, y, z, scaleChildren);
  83333. }
  83334. }
  83335. };
  83336. /**
  83337. * Set the bone scaling in local space
  83338. * @param scale defines the scaling vector
  83339. */
  83340. Bone.prototype.setScale = function (scale) {
  83341. this._decompose();
  83342. this._localScaling.copyFrom(scale);
  83343. this._markAsDirtyAndCompose();
  83344. };
  83345. /**
  83346. * Gets the current scaling in local space
  83347. * @returns the current scaling vector
  83348. */
  83349. Bone.prototype.getScale = function () {
  83350. this._decompose();
  83351. return this._localScaling;
  83352. };
  83353. /**
  83354. * Gets the current scaling in local space and stores it in a target vector
  83355. * @param result defines the target vector
  83356. */
  83357. Bone.prototype.getScaleToRef = function (result) {
  83358. this._decompose();
  83359. result.copyFrom(this._localScaling);
  83360. };
  83361. /**
  83362. * Set the yaw, pitch, and roll of the bone in local or world space
  83363. * @param yaw The rotation of the bone on the y axis
  83364. * @param pitch The rotation of the bone on the x axis
  83365. * @param roll The rotation of the bone on the z axis
  83366. * @param space The space that the axes of rotation are in
  83367. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83368. */
  83369. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  83370. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83371. if (space === BABYLON.Space.LOCAL) {
  83372. var quat = Bone._tmpQuat;
  83373. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  83374. this.setRotationQuaternion(quat, space, mesh);
  83375. return;
  83376. }
  83377. var rotMatInv = Bone._tmpMats[0];
  83378. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  83379. return;
  83380. }
  83381. var rotMat = Bone._tmpMats[1];
  83382. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  83383. rotMatInv.multiplyToRef(rotMat, rotMat);
  83384. this._rotateWithMatrix(rotMat, space, mesh);
  83385. };
  83386. /**
  83387. * Add a rotation to the bone on an axis in local or world space
  83388. * @param axis The axis to rotate the bone on
  83389. * @param amount The amount to rotate the bone
  83390. * @param space The space that the axis is in
  83391. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83392. */
  83393. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  83394. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83395. var rmat = Bone._tmpMats[0];
  83396. rmat.m[12] = 0;
  83397. rmat.m[13] = 0;
  83398. rmat.m[14] = 0;
  83399. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  83400. this._rotateWithMatrix(rmat, space, mesh);
  83401. };
  83402. /**
  83403. * Set the rotation of the bone to a particular axis angle in local or world space
  83404. * @param axis The axis to rotate the bone on
  83405. * @param angle The angle that the bone should be rotated to
  83406. * @param space The space that the axis is in
  83407. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83408. */
  83409. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  83410. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83411. if (space === BABYLON.Space.LOCAL) {
  83412. var quat = Bone._tmpQuat;
  83413. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  83414. this.setRotationQuaternion(quat, space, mesh);
  83415. return;
  83416. }
  83417. var rotMatInv = Bone._tmpMats[0];
  83418. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  83419. return;
  83420. }
  83421. var rotMat = Bone._tmpMats[1];
  83422. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  83423. rotMatInv.multiplyToRef(rotMat, rotMat);
  83424. this._rotateWithMatrix(rotMat, space, mesh);
  83425. };
  83426. /**
  83427. * Set the euler rotation of the bone in local of world space
  83428. * @param rotation The euler rotation that the bone should be set to
  83429. * @param space The space that the rotation is in
  83430. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83431. */
  83432. Bone.prototype.setRotation = function (rotation, space, mesh) {
  83433. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83434. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  83435. };
  83436. /**
  83437. * Set the quaternion rotation of the bone in local of world space
  83438. * @param quat The quaternion rotation that the bone should be set to
  83439. * @param space The space that the rotation is in
  83440. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83441. */
  83442. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  83443. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83444. if (space === BABYLON.Space.LOCAL) {
  83445. this._decompose();
  83446. this._localRotation.copyFrom(quat);
  83447. this._markAsDirtyAndCompose();
  83448. return;
  83449. }
  83450. var rotMatInv = Bone._tmpMats[0];
  83451. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  83452. return;
  83453. }
  83454. var rotMat = Bone._tmpMats[1];
  83455. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  83456. rotMatInv.multiplyToRef(rotMat, rotMat);
  83457. this._rotateWithMatrix(rotMat, space, mesh);
  83458. };
  83459. /**
  83460. * Set the rotation matrix of the bone in local of world space
  83461. * @param rotMat The rotation matrix that the bone should be set to
  83462. * @param space The space that the rotation is in
  83463. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83464. */
  83465. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  83466. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83467. if (space === BABYLON.Space.LOCAL) {
  83468. var quat = Bone._tmpQuat;
  83469. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  83470. this.setRotationQuaternion(quat, space, mesh);
  83471. return;
  83472. }
  83473. var rotMatInv = Bone._tmpMats[0];
  83474. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  83475. return;
  83476. }
  83477. var rotMat2 = Bone._tmpMats[1];
  83478. rotMat2.copyFrom(rotMat);
  83479. rotMatInv.multiplyToRef(rotMat, rotMat2);
  83480. this._rotateWithMatrix(rotMat2, space, mesh);
  83481. };
  83482. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  83483. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83484. var lmat = this.getLocalMatrix();
  83485. var lx = lmat.m[12];
  83486. var ly = lmat.m[13];
  83487. var lz = lmat.m[14];
  83488. var parent = this.getParent();
  83489. var parentScale = Bone._tmpMats[3];
  83490. var parentScaleInv = Bone._tmpMats[4];
  83491. if (parent && space == BABYLON.Space.WORLD) {
  83492. if (mesh) {
  83493. parentScale.copyFrom(mesh.getWorldMatrix());
  83494. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  83495. }
  83496. else {
  83497. parentScale.copyFrom(parent.getAbsoluteTransform());
  83498. }
  83499. parentScaleInv.copyFrom(parentScale);
  83500. parentScaleInv.invert();
  83501. lmat.multiplyToRef(parentScale, lmat);
  83502. lmat.multiplyToRef(rmat, lmat);
  83503. lmat.multiplyToRef(parentScaleInv, lmat);
  83504. }
  83505. else {
  83506. if (space == BABYLON.Space.WORLD && mesh) {
  83507. parentScale.copyFrom(mesh.getWorldMatrix());
  83508. parentScaleInv.copyFrom(parentScale);
  83509. parentScaleInv.invert();
  83510. lmat.multiplyToRef(parentScale, lmat);
  83511. lmat.multiplyToRef(rmat, lmat);
  83512. lmat.multiplyToRef(parentScaleInv, lmat);
  83513. }
  83514. else {
  83515. lmat.multiplyToRef(rmat, lmat);
  83516. }
  83517. }
  83518. lmat.m[12] = lx;
  83519. lmat.m[13] = ly;
  83520. lmat.m[14] = lz;
  83521. this.computeAbsoluteTransforms();
  83522. this._markAsDirtyAndDecompose();
  83523. };
  83524. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  83525. var scaleMatrix = Bone._tmpMats[2];
  83526. rotMatInv.copyFrom(this.getAbsoluteTransform());
  83527. if (mesh) {
  83528. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  83529. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  83530. }
  83531. rotMatInv.invert();
  83532. if (isNaN(rotMatInv.m[0])) {
  83533. // Matrix failed to invert.
  83534. // This can happen if scale is zero for example.
  83535. return false;
  83536. }
  83537. scaleMatrix.m[0] *= this._scalingDeterminant;
  83538. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  83539. return true;
  83540. };
  83541. /**
  83542. * Get the position of the bone in local or world space
  83543. * @param space The space that the returned position is in
  83544. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83545. * @returns The position of the bone
  83546. */
  83547. Bone.prototype.getPosition = function (space, mesh) {
  83548. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83549. if (mesh === void 0) { mesh = null; }
  83550. var pos = BABYLON.Vector3.Zero();
  83551. this.getPositionToRef(space, mesh, pos);
  83552. return pos;
  83553. };
  83554. /**
  83555. * Copy the position of the bone to a vector3 in local or world space
  83556. * @param space The space that the returned position is in
  83557. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83558. * @param result The vector3 to copy the position to
  83559. */
  83560. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  83561. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83562. if (space == BABYLON.Space.LOCAL) {
  83563. var lm = this.getLocalMatrix();
  83564. result.x = lm.m[12];
  83565. result.y = lm.m[13];
  83566. result.z = lm.m[14];
  83567. }
  83568. else {
  83569. var wm = null;
  83570. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  83571. if (mesh) {
  83572. wm = mesh.getWorldMatrix();
  83573. }
  83574. this._skeleton.computeAbsoluteTransforms();
  83575. var tmat = Bone._tmpMats[0];
  83576. if (mesh && wm) {
  83577. tmat.copyFrom(this.getAbsoluteTransform());
  83578. tmat.multiplyToRef(wm, tmat);
  83579. }
  83580. else {
  83581. tmat = this.getAbsoluteTransform();
  83582. }
  83583. result.x = tmat.m[12];
  83584. result.y = tmat.m[13];
  83585. result.z = tmat.m[14];
  83586. }
  83587. };
  83588. /**
  83589. * Get the absolute position of the bone (world space)
  83590. * @param mesh The mesh that this bone is attached to
  83591. * @returns The absolute position of the bone
  83592. */
  83593. Bone.prototype.getAbsolutePosition = function (mesh) {
  83594. if (mesh === void 0) { mesh = null; }
  83595. var pos = BABYLON.Vector3.Zero();
  83596. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  83597. return pos;
  83598. };
  83599. /**
  83600. * Copy the absolute position of the bone (world space) to the result param
  83601. * @param mesh The mesh that this bone is attached to
  83602. * @param result The vector3 to copy the absolute position to
  83603. */
  83604. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  83605. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  83606. };
  83607. /**
  83608. * Compute the absolute transforms of this bone and its children
  83609. */
  83610. Bone.prototype.computeAbsoluteTransforms = function () {
  83611. this._compose();
  83612. if (this._parent) {
  83613. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  83614. }
  83615. else {
  83616. this._absoluteTransform.copyFrom(this._localMatrix);
  83617. var poseMatrix = this._skeleton.getPoseMatrix();
  83618. if (poseMatrix) {
  83619. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  83620. }
  83621. }
  83622. var children = this.children;
  83623. var len = children.length;
  83624. for (var i = 0; i < len; i++) {
  83625. children[i].computeAbsoluteTransforms();
  83626. }
  83627. };
  83628. /**
  83629. * Get the world direction from an axis that is in the local space of the bone
  83630. * @param localAxis The local direction that is used to compute the world direction
  83631. * @param mesh The mesh that this bone is attached to
  83632. * @returns The world direction
  83633. */
  83634. Bone.prototype.getDirection = function (localAxis, mesh) {
  83635. if (mesh === void 0) { mesh = null; }
  83636. var result = BABYLON.Vector3.Zero();
  83637. this.getDirectionToRef(localAxis, mesh, result);
  83638. return result;
  83639. };
  83640. /**
  83641. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  83642. * @param localAxis The local direction that is used to compute the world direction
  83643. * @param mesh The mesh that this bone is attached to
  83644. * @param result The vector3 that the world direction will be copied to
  83645. */
  83646. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  83647. if (mesh === void 0) { mesh = null; }
  83648. var wm = null;
  83649. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  83650. if (mesh) {
  83651. wm = mesh.getWorldMatrix();
  83652. }
  83653. this._skeleton.computeAbsoluteTransforms();
  83654. var mat = Bone._tmpMats[0];
  83655. mat.copyFrom(this.getAbsoluteTransform());
  83656. if (mesh && wm) {
  83657. mat.multiplyToRef(wm, mat);
  83658. }
  83659. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  83660. result.normalize();
  83661. };
  83662. /**
  83663. * Get the euler rotation of the bone in local or world space
  83664. * @param space The space that the rotation should be in
  83665. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83666. * @returns The euler rotation
  83667. */
  83668. Bone.prototype.getRotation = function (space, mesh) {
  83669. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83670. if (mesh === void 0) { mesh = null; }
  83671. var result = BABYLON.Vector3.Zero();
  83672. this.getRotationToRef(space, mesh, result);
  83673. return result;
  83674. };
  83675. /**
  83676. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  83677. * @param space The space that the rotation should be in
  83678. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83679. * @param result The vector3 that the rotation should be copied to
  83680. */
  83681. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  83682. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83683. if (mesh === void 0) { mesh = null; }
  83684. var quat = Bone._tmpQuat;
  83685. this.getRotationQuaternionToRef(space, mesh, quat);
  83686. quat.toEulerAnglesToRef(result);
  83687. };
  83688. /**
  83689. * Get the quaternion rotation of the bone in either local or world space
  83690. * @param space The space that the rotation should be in
  83691. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83692. * @returns The quaternion rotation
  83693. */
  83694. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  83695. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83696. if (mesh === void 0) { mesh = null; }
  83697. var result = BABYLON.Quaternion.Identity();
  83698. this.getRotationQuaternionToRef(space, mesh, result);
  83699. return result;
  83700. };
  83701. /**
  83702. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  83703. * @param space The space that the rotation should be in
  83704. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83705. * @param result The quaternion that the rotation should be copied to
  83706. */
  83707. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  83708. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83709. if (mesh === void 0) { mesh = null; }
  83710. if (space == BABYLON.Space.LOCAL) {
  83711. this._decompose();
  83712. result.copyFrom(this._localRotation);
  83713. }
  83714. else {
  83715. var mat = Bone._tmpMats[0];
  83716. var amat = this.getAbsoluteTransform();
  83717. if (mesh) {
  83718. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  83719. }
  83720. else {
  83721. mat.copyFrom(amat);
  83722. }
  83723. mat.m[0] *= this._scalingDeterminant;
  83724. mat.m[1] *= this._scalingDeterminant;
  83725. mat.m[2] *= this._scalingDeterminant;
  83726. mat.decompose(undefined, result, undefined);
  83727. }
  83728. };
  83729. /**
  83730. * Get the rotation matrix of the bone in local or world space
  83731. * @param space The space that the rotation should be in
  83732. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83733. * @returns The rotation matrix
  83734. */
  83735. Bone.prototype.getRotationMatrix = function (space, mesh) {
  83736. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83737. var result = BABYLON.Matrix.Identity();
  83738. this.getRotationMatrixToRef(space, mesh, result);
  83739. return result;
  83740. };
  83741. /**
  83742. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  83743. * @param space The space that the rotation should be in
  83744. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83745. * @param result The quaternion that the rotation should be copied to
  83746. */
  83747. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  83748. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83749. if (space == BABYLON.Space.LOCAL) {
  83750. this.getLocalMatrix().getRotationMatrixToRef(result);
  83751. }
  83752. else {
  83753. var mat = Bone._tmpMats[0];
  83754. var amat = this.getAbsoluteTransform();
  83755. if (mesh) {
  83756. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  83757. }
  83758. else {
  83759. mat.copyFrom(amat);
  83760. }
  83761. mat.m[0] *= this._scalingDeterminant;
  83762. mat.m[1] *= this._scalingDeterminant;
  83763. mat.m[2] *= this._scalingDeterminant;
  83764. mat.getRotationMatrixToRef(result);
  83765. }
  83766. };
  83767. /**
  83768. * Get the world position of a point that is in the local space of the bone
  83769. * @param position The local position
  83770. * @param mesh The mesh that this bone is attached to
  83771. * @returns The world position
  83772. */
  83773. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  83774. if (mesh === void 0) { mesh = null; }
  83775. var result = BABYLON.Vector3.Zero();
  83776. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  83777. return result;
  83778. };
  83779. /**
  83780. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  83781. * @param position The local position
  83782. * @param mesh The mesh that this bone is attached to
  83783. * @param result The vector3 that the world position should be copied to
  83784. */
  83785. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  83786. if (mesh === void 0) { mesh = null; }
  83787. var wm = null;
  83788. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  83789. if (mesh) {
  83790. wm = mesh.getWorldMatrix();
  83791. }
  83792. this._skeleton.computeAbsoluteTransforms();
  83793. var tmat = Bone._tmpMats[0];
  83794. if (mesh && wm) {
  83795. tmat.copyFrom(this.getAbsoluteTransform());
  83796. tmat.multiplyToRef(wm, tmat);
  83797. }
  83798. else {
  83799. tmat = this.getAbsoluteTransform();
  83800. }
  83801. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  83802. };
  83803. /**
  83804. * Get the local position of a point that is in world space
  83805. * @param position The world position
  83806. * @param mesh The mesh that this bone is attached to
  83807. * @returns The local position
  83808. */
  83809. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  83810. if (mesh === void 0) { mesh = null; }
  83811. var result = BABYLON.Vector3.Zero();
  83812. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  83813. return result;
  83814. };
  83815. /**
  83816. * Get the local position of a point that is in world space and copy it to the result param
  83817. * @param position The world position
  83818. * @param mesh The mesh that this bone is attached to
  83819. * @param result The vector3 that the local position should be copied to
  83820. */
  83821. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  83822. if (mesh === void 0) { mesh = null; }
  83823. var wm = null;
  83824. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  83825. if (mesh) {
  83826. wm = mesh.getWorldMatrix();
  83827. }
  83828. this._skeleton.computeAbsoluteTransforms();
  83829. var tmat = Bone._tmpMats[0];
  83830. tmat.copyFrom(this.getAbsoluteTransform());
  83831. if (mesh && wm) {
  83832. tmat.multiplyToRef(wm, tmat);
  83833. }
  83834. tmat.invert();
  83835. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  83836. };
  83837. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83838. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  83839. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  83840. return Bone;
  83841. }(BABYLON.Node));
  83842. BABYLON.Bone = Bone;
  83843. })(BABYLON || (BABYLON = {}));
  83844. //# sourceMappingURL=babylon.bone.js.map
  83845. var BABYLON;
  83846. (function (BABYLON) {
  83847. /**
  83848. * Class used to apply inverse kinematics to bones
  83849. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  83850. */
  83851. var BoneIKController = /** @class */ (function () {
  83852. /**
  83853. * Creates a new BoneIKController
  83854. * @param mesh defines the mesh to control
  83855. * @param bone defines the bone to control
  83856. * @param options defines options to set up the controller
  83857. */
  83858. function BoneIKController(mesh, bone, options) {
  83859. /**
  83860. * Gets or sets the target position
  83861. */
  83862. this.targetPosition = BABYLON.Vector3.Zero();
  83863. /**
  83864. * Gets or sets the pole target position
  83865. */
  83866. this.poleTargetPosition = BABYLON.Vector3.Zero();
  83867. /**
  83868. * Gets or sets the pole target local offset
  83869. */
  83870. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  83871. /**
  83872. * Gets or sets the pole angle
  83873. */
  83874. this.poleAngle = 0;
  83875. /**
  83876. * 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)
  83877. */
  83878. this.slerpAmount = 1;
  83879. this._bone1Quat = BABYLON.Quaternion.Identity();
  83880. this._bone1Mat = BABYLON.Matrix.Identity();
  83881. this._bone2Ang = Math.PI;
  83882. this._maxAngle = Math.PI;
  83883. this._rightHandedSystem = false;
  83884. this._bendAxis = BABYLON.Vector3.Right();
  83885. this._slerping = false;
  83886. this._adjustRoll = 0;
  83887. this._bone2 = bone;
  83888. this._bone1 = bone.getParent();
  83889. if (!this._bone1) {
  83890. return;
  83891. }
  83892. this.mesh = mesh;
  83893. var bonePos = bone.getPosition();
  83894. if (bone.getAbsoluteTransform().determinant() > 0) {
  83895. this._rightHandedSystem = true;
  83896. this._bendAxis.x = 0;
  83897. this._bendAxis.y = 0;
  83898. this._bendAxis.z = -1;
  83899. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  83900. this._adjustRoll = Math.PI * .5;
  83901. this._bendAxis.z = 1;
  83902. }
  83903. }
  83904. if (this._bone1.length) {
  83905. var boneScale1 = this._bone1.getScale();
  83906. var boneScale2 = this._bone2.getScale();
  83907. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  83908. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  83909. }
  83910. else if (this._bone1.children[0]) {
  83911. mesh.computeWorldMatrix(true);
  83912. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  83913. var pos2 = this._bone2.getAbsolutePosition(mesh);
  83914. var pos3 = this._bone1.getAbsolutePosition(mesh);
  83915. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  83916. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  83917. }
  83918. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  83919. this.maxAngle = Math.PI;
  83920. if (options) {
  83921. if (options.targetMesh) {
  83922. this.targetMesh = options.targetMesh;
  83923. this.targetMesh.computeWorldMatrix(true);
  83924. }
  83925. if (options.poleTargetMesh) {
  83926. this.poleTargetMesh = options.poleTargetMesh;
  83927. this.poleTargetMesh.computeWorldMatrix(true);
  83928. }
  83929. else if (options.poleTargetBone) {
  83930. this.poleTargetBone = options.poleTargetBone;
  83931. }
  83932. else if (this._bone1.getParent()) {
  83933. this.poleTargetBone = this._bone1.getParent();
  83934. }
  83935. if (options.poleTargetLocalOffset) {
  83936. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  83937. }
  83938. if (options.poleAngle) {
  83939. this.poleAngle = options.poleAngle;
  83940. }
  83941. if (options.bendAxis) {
  83942. this._bendAxis.copyFrom(options.bendAxis);
  83943. }
  83944. if (options.maxAngle) {
  83945. this.maxAngle = options.maxAngle;
  83946. }
  83947. if (options.slerpAmount) {
  83948. this.slerpAmount = options.slerpAmount;
  83949. }
  83950. }
  83951. }
  83952. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  83953. /**
  83954. * Gets or sets maximum allowed angle
  83955. */
  83956. get: function () {
  83957. return this._maxAngle;
  83958. },
  83959. set: function (value) {
  83960. this._setMaxAngle(value);
  83961. },
  83962. enumerable: true,
  83963. configurable: true
  83964. });
  83965. BoneIKController.prototype._setMaxAngle = function (ang) {
  83966. if (ang < 0) {
  83967. ang = 0;
  83968. }
  83969. if (ang > Math.PI || ang == undefined) {
  83970. ang = Math.PI;
  83971. }
  83972. this._maxAngle = ang;
  83973. var a = this._bone1Length;
  83974. var b = this._bone2Length;
  83975. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  83976. };
  83977. /**
  83978. * Force the controller to update the bones
  83979. */
  83980. BoneIKController.prototype.update = function () {
  83981. var bone1 = this._bone1;
  83982. if (!bone1) {
  83983. return;
  83984. }
  83985. var target = this.targetPosition;
  83986. var poleTarget = this.poleTargetPosition;
  83987. var mat1 = BoneIKController._tmpMats[0];
  83988. var mat2 = BoneIKController._tmpMats[1];
  83989. if (this.targetMesh) {
  83990. target.copyFrom(this.targetMesh.getAbsolutePosition());
  83991. }
  83992. if (this.poleTargetBone) {
  83993. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  83994. }
  83995. else if (this.poleTargetMesh) {
  83996. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  83997. }
  83998. var bonePos = BoneIKController._tmpVecs[0];
  83999. var zaxis = BoneIKController._tmpVecs[1];
  84000. var xaxis = BoneIKController._tmpVecs[2];
  84001. var yaxis = BoneIKController._tmpVecs[3];
  84002. var upAxis = BoneIKController._tmpVecs[4];
  84003. var _tmpQuat = BoneIKController._tmpQuat;
  84004. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  84005. poleTarget.subtractToRef(bonePos, upAxis);
  84006. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  84007. upAxis.y = 1;
  84008. }
  84009. else {
  84010. upAxis.normalize();
  84011. }
  84012. target.subtractToRef(bonePos, yaxis);
  84013. yaxis.normalize();
  84014. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  84015. zaxis.normalize();
  84016. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  84017. xaxis.normalize();
  84018. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  84019. var a = this._bone1Length;
  84020. var b = this._bone2Length;
  84021. var c = BABYLON.Vector3.Distance(bonePos, target);
  84022. if (this._maxReach > 0) {
  84023. c = Math.min(this._maxReach, c);
  84024. }
  84025. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  84026. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  84027. if (acosa > 1) {
  84028. acosa = 1;
  84029. }
  84030. if (acosb > 1) {
  84031. acosb = 1;
  84032. }
  84033. if (acosa < -1) {
  84034. acosa = -1;
  84035. }
  84036. if (acosb < -1) {
  84037. acosb = -1;
  84038. }
  84039. var angA = Math.acos(acosa);
  84040. var angB = Math.acos(acosb);
  84041. var angC = -angA - angB;
  84042. if (this._rightHandedSystem) {
  84043. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  84044. mat2.multiplyToRef(mat1, mat1);
  84045. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  84046. mat2.multiplyToRef(mat1, mat1);
  84047. }
  84048. else {
  84049. var _tmpVec = BoneIKController._tmpVecs[5];
  84050. _tmpVec.copyFrom(this._bendAxis);
  84051. _tmpVec.x *= -1;
  84052. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  84053. mat2.multiplyToRef(mat1, mat1);
  84054. }
  84055. if (this.poleAngle) {
  84056. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  84057. mat1.multiplyToRef(mat2, mat1);
  84058. }
  84059. if (this._bone1) {
  84060. if (this.slerpAmount < 1) {
  84061. if (!this._slerping) {
  84062. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  84063. }
  84064. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  84065. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  84066. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  84067. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  84068. this._slerping = true;
  84069. }
  84070. else {
  84071. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  84072. this._bone1Mat.copyFrom(mat1);
  84073. this._slerping = false;
  84074. }
  84075. }
  84076. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  84077. this._bone2Ang = angC;
  84078. };
  84079. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84080. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  84081. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  84082. return BoneIKController;
  84083. }());
  84084. BABYLON.BoneIKController = BoneIKController;
  84085. })(BABYLON || (BABYLON = {}));
  84086. //# sourceMappingURL=babylon.boneIKController.js.map
  84087. var BABYLON;
  84088. (function (BABYLON) {
  84089. /**
  84090. * Class used to make a bone look toward a point in space
  84091. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  84092. */
  84093. var BoneLookController = /** @class */ (function () {
  84094. /**
  84095. * Create a BoneLookController
  84096. * @param mesh the mesh that the bone belongs to
  84097. * @param bone the bone that will be looking to the target
  84098. * @param target the target Vector3 to look at
  84099. * @param settings optional settings:
  84100. * * maxYaw: the maximum angle the bone will yaw to
  84101. * * minYaw: the minimum angle the bone will yaw to
  84102. * * maxPitch: the maximum angle the bone will pitch to
  84103. * * minPitch: the minimum angle the bone will yaw to
  84104. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  84105. * * upAxis: the up axis of the coordinate system
  84106. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  84107. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  84108. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  84109. * * adjustYaw: used to make an adjustment to the yaw of the bone
  84110. * * adjustPitch: used to make an adjustment to the pitch of the bone
  84111. * * adjustRoll: used to make an adjustment to the roll of the bone
  84112. **/
  84113. function BoneLookController(mesh, bone, target, options) {
  84114. /**
  84115. * The up axis of the coordinate system that is used when the bone is rotated
  84116. */
  84117. this.upAxis = BABYLON.Vector3.Up();
  84118. /**
  84119. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  84120. */
  84121. this.upAxisSpace = BABYLON.Space.LOCAL;
  84122. /**
  84123. * Used to make an adjustment to the yaw of the bone
  84124. */
  84125. this.adjustYaw = 0;
  84126. /**
  84127. * Used to make an adjustment to the pitch of the bone
  84128. */
  84129. this.adjustPitch = 0;
  84130. /**
  84131. * Used to make an adjustment to the roll of the bone
  84132. */
  84133. this.adjustRoll = 0;
  84134. /**
  84135. * 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)
  84136. */
  84137. this.slerpAmount = 1;
  84138. this._boneQuat = BABYLON.Quaternion.Identity();
  84139. this._slerping = false;
  84140. this._firstFrameSkipped = false;
  84141. this._fowardAxis = BABYLON.Vector3.Forward();
  84142. this.mesh = mesh;
  84143. this.bone = bone;
  84144. this.target = target;
  84145. if (options) {
  84146. if (options.adjustYaw) {
  84147. this.adjustYaw = options.adjustYaw;
  84148. }
  84149. if (options.adjustPitch) {
  84150. this.adjustPitch = options.adjustPitch;
  84151. }
  84152. if (options.adjustRoll) {
  84153. this.adjustRoll = options.adjustRoll;
  84154. }
  84155. if (options.maxYaw != null) {
  84156. this.maxYaw = options.maxYaw;
  84157. }
  84158. else {
  84159. this.maxYaw = Math.PI;
  84160. }
  84161. if (options.minYaw != null) {
  84162. this.minYaw = options.minYaw;
  84163. }
  84164. else {
  84165. this.minYaw = -Math.PI;
  84166. }
  84167. if (options.maxPitch != null) {
  84168. this.maxPitch = options.maxPitch;
  84169. }
  84170. else {
  84171. this.maxPitch = Math.PI;
  84172. }
  84173. if (options.minPitch != null) {
  84174. this.minPitch = options.minPitch;
  84175. }
  84176. else {
  84177. this.minPitch = -Math.PI;
  84178. }
  84179. if (options.slerpAmount != null) {
  84180. this.slerpAmount = options.slerpAmount;
  84181. }
  84182. if (options.upAxis != null) {
  84183. this.upAxis = options.upAxis;
  84184. }
  84185. if (options.upAxisSpace != null) {
  84186. this.upAxisSpace = options.upAxisSpace;
  84187. }
  84188. if (options.yawAxis != null || options.pitchAxis != null) {
  84189. var newYawAxis = BABYLON.Axis.Y;
  84190. var newPitchAxis = BABYLON.Axis.X;
  84191. if (options.yawAxis != null) {
  84192. newYawAxis = options.yawAxis.clone();
  84193. newYawAxis.normalize();
  84194. }
  84195. if (options.pitchAxis != null) {
  84196. newPitchAxis = options.pitchAxis.clone();
  84197. newPitchAxis.normalize();
  84198. }
  84199. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  84200. this._transformYawPitch = BABYLON.Matrix.Identity();
  84201. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  84202. this._transformYawPitchInv = this._transformYawPitch.clone();
  84203. this._transformYawPitch.invert();
  84204. }
  84205. }
  84206. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  84207. this.upAxisSpace = BABYLON.Space.LOCAL;
  84208. }
  84209. }
  84210. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  84211. /**
  84212. * Gets or sets the minimum yaw angle that the bone can look to
  84213. */
  84214. get: function () {
  84215. return this._minYaw;
  84216. },
  84217. set: function (value) {
  84218. this._minYaw = value;
  84219. this._minYawSin = Math.sin(value);
  84220. this._minYawCos = Math.cos(value);
  84221. if (this._maxYaw != null) {
  84222. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  84223. this._yawRange = this._maxYaw - this._minYaw;
  84224. }
  84225. },
  84226. enumerable: true,
  84227. configurable: true
  84228. });
  84229. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  84230. /**
  84231. * Gets or sets the maximum yaw angle that the bone can look to
  84232. */
  84233. get: function () {
  84234. return this._maxYaw;
  84235. },
  84236. set: function (value) {
  84237. this._maxYaw = value;
  84238. this._maxYawSin = Math.sin(value);
  84239. this._maxYawCos = Math.cos(value);
  84240. if (this._minYaw != null) {
  84241. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  84242. this._yawRange = this._maxYaw - this._minYaw;
  84243. }
  84244. },
  84245. enumerable: true,
  84246. configurable: true
  84247. });
  84248. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  84249. /**
  84250. * Gets or sets the minimum pitch angle that the bone can look to
  84251. */
  84252. get: function () {
  84253. return this._minPitch;
  84254. },
  84255. set: function (value) {
  84256. this._minPitch = value;
  84257. this._minPitchTan = Math.tan(value);
  84258. },
  84259. enumerable: true,
  84260. configurable: true
  84261. });
  84262. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  84263. /**
  84264. * Gets or sets the maximum pitch angle that the bone can look to
  84265. */
  84266. get: function () {
  84267. return this._maxPitch;
  84268. },
  84269. set: function (value) {
  84270. this._maxPitch = value;
  84271. this._maxPitchTan = Math.tan(value);
  84272. },
  84273. enumerable: true,
  84274. configurable: true
  84275. });
  84276. /**
  84277. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  84278. */
  84279. BoneLookController.prototype.update = function () {
  84280. //skip the first frame when slerping so that the mesh rotation is correct
  84281. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  84282. this._firstFrameSkipped = true;
  84283. return;
  84284. }
  84285. var bone = this.bone;
  84286. var bonePos = BoneLookController._tmpVecs[0];
  84287. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  84288. var target = this.target;
  84289. var _tmpMat1 = BoneLookController._tmpMats[0];
  84290. var _tmpMat2 = BoneLookController._tmpMats[1];
  84291. var mesh = this.mesh;
  84292. var parentBone = bone.getParent();
  84293. var upAxis = BoneLookController._tmpVecs[1];
  84294. upAxis.copyFrom(this.upAxis);
  84295. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  84296. if (this._transformYawPitch) {
  84297. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  84298. }
  84299. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  84300. }
  84301. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  84302. mesh.getDirectionToRef(upAxis, upAxis);
  84303. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  84304. upAxis.normalize();
  84305. }
  84306. }
  84307. var checkYaw = false;
  84308. var checkPitch = false;
  84309. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  84310. checkYaw = true;
  84311. }
  84312. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  84313. checkPitch = true;
  84314. }
  84315. if (checkYaw || checkPitch) {
  84316. var spaceMat = BoneLookController._tmpMats[2];
  84317. var spaceMatInv = BoneLookController._tmpMats[3];
  84318. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  84319. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  84320. }
  84321. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  84322. spaceMat.copyFrom(mesh.getWorldMatrix());
  84323. }
  84324. else {
  84325. var forwardAxis = BoneLookController._tmpVecs[2];
  84326. forwardAxis.copyFrom(this._fowardAxis);
  84327. if (this._transformYawPitch) {
  84328. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  84329. }
  84330. if (parentBone) {
  84331. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  84332. }
  84333. else {
  84334. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  84335. }
  84336. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  84337. rightAxis.normalize();
  84338. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  84339. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  84340. }
  84341. spaceMat.invertToRef(spaceMatInv);
  84342. var xzlen = null;
  84343. if (checkPitch) {
  84344. var localTarget = BoneLookController._tmpVecs[3];
  84345. target.subtractToRef(bonePos, localTarget);
  84346. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  84347. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  84348. var pitch = Math.atan2(localTarget.y, xzlen);
  84349. var newPitch = pitch;
  84350. if (pitch > this._maxPitch) {
  84351. localTarget.y = this._maxPitchTan * xzlen;
  84352. newPitch = this._maxPitch;
  84353. }
  84354. else if (pitch < this._minPitch) {
  84355. localTarget.y = this._minPitchTan * xzlen;
  84356. newPitch = this._minPitch;
  84357. }
  84358. if (pitch != newPitch) {
  84359. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  84360. localTarget.addInPlace(bonePos);
  84361. target = localTarget;
  84362. }
  84363. }
  84364. if (checkYaw) {
  84365. var localTarget = BoneLookController._tmpVecs[4];
  84366. target.subtractToRef(bonePos, localTarget);
  84367. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  84368. var yaw = Math.atan2(localTarget.x, localTarget.z);
  84369. var newYaw = yaw;
  84370. if (yaw > this._maxYaw || yaw < this._minYaw) {
  84371. if (xzlen == null) {
  84372. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  84373. }
  84374. if (this._yawRange > Math.PI) {
  84375. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  84376. localTarget.z = this._maxYawCos * xzlen;
  84377. localTarget.x = this._maxYawSin * xzlen;
  84378. newYaw = this._maxYaw;
  84379. }
  84380. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  84381. localTarget.z = this._minYawCos * xzlen;
  84382. localTarget.x = this._minYawSin * xzlen;
  84383. newYaw = this._minYaw;
  84384. }
  84385. }
  84386. else {
  84387. if (yaw > this._maxYaw) {
  84388. localTarget.z = this._maxYawCos * xzlen;
  84389. localTarget.x = this._maxYawSin * xzlen;
  84390. newYaw = this._maxYaw;
  84391. }
  84392. else if (yaw < this._minYaw) {
  84393. localTarget.z = this._minYawCos * xzlen;
  84394. localTarget.x = this._minYawSin * xzlen;
  84395. newYaw = this._minYaw;
  84396. }
  84397. }
  84398. }
  84399. if (this._slerping && this._yawRange > Math.PI) {
  84400. //are we going to be crossing into the min/max region?
  84401. var boneFwd = BoneLookController._tmpVecs[8];
  84402. boneFwd.copyFrom(BABYLON.Axis.Z);
  84403. if (this._transformYawPitch) {
  84404. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  84405. }
  84406. var boneRotMat = BoneLookController._tmpMats[4];
  84407. this._boneQuat.toRotationMatrix(boneRotMat);
  84408. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  84409. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  84410. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  84411. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  84412. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  84413. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  84414. if (angBtwTar > angBtwMidYaw) {
  84415. if (xzlen == null) {
  84416. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  84417. }
  84418. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  84419. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  84420. if (angBtwMin < angBtwMax) {
  84421. newYaw = boneYaw + Math.PI * .75;
  84422. localTarget.z = Math.cos(newYaw) * xzlen;
  84423. localTarget.x = Math.sin(newYaw) * xzlen;
  84424. }
  84425. else {
  84426. newYaw = boneYaw - Math.PI * .75;
  84427. localTarget.z = Math.cos(newYaw) * xzlen;
  84428. localTarget.x = Math.sin(newYaw) * xzlen;
  84429. }
  84430. }
  84431. }
  84432. if (yaw != newYaw) {
  84433. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  84434. localTarget.addInPlace(bonePos);
  84435. target = localTarget;
  84436. }
  84437. }
  84438. }
  84439. var zaxis = BoneLookController._tmpVecs[5];
  84440. var xaxis = BoneLookController._tmpVecs[6];
  84441. var yaxis = BoneLookController._tmpVecs[7];
  84442. var _tmpQuat = BoneLookController._tmpQuat;
  84443. target.subtractToRef(bonePos, zaxis);
  84444. zaxis.normalize();
  84445. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  84446. xaxis.normalize();
  84447. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  84448. yaxis.normalize();
  84449. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  84450. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  84451. return;
  84452. }
  84453. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  84454. return;
  84455. }
  84456. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  84457. return;
  84458. }
  84459. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  84460. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  84461. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  84462. }
  84463. if (this.slerpAmount < 1) {
  84464. if (!this._slerping) {
  84465. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  84466. }
  84467. if (this._transformYawPitch) {
  84468. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  84469. }
  84470. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  84471. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  84472. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  84473. this._slerping = true;
  84474. }
  84475. else {
  84476. if (this._transformYawPitch) {
  84477. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  84478. }
  84479. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  84480. this._slerping = false;
  84481. }
  84482. };
  84483. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  84484. var angDiff = ang2 - ang1;
  84485. angDiff %= Math.PI * 2;
  84486. if (angDiff > Math.PI) {
  84487. angDiff -= Math.PI * 2;
  84488. }
  84489. else if (angDiff < -Math.PI) {
  84490. angDiff += Math.PI * 2;
  84491. }
  84492. return angDiff;
  84493. };
  84494. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  84495. ang1 %= (2 * Math.PI);
  84496. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  84497. ang2 %= (2 * Math.PI);
  84498. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  84499. var ab = 0;
  84500. if (ang1 < ang2) {
  84501. ab = ang2 - ang1;
  84502. }
  84503. else {
  84504. ab = ang1 - ang2;
  84505. }
  84506. if (ab > Math.PI) {
  84507. ab = Math.PI * 2 - ab;
  84508. }
  84509. return ab;
  84510. };
  84511. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  84512. ang %= (2 * Math.PI);
  84513. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  84514. ang1 %= (2 * Math.PI);
  84515. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  84516. ang2 %= (2 * Math.PI);
  84517. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  84518. if (ang1 < ang2) {
  84519. if (ang > ang1 && ang < ang2) {
  84520. return true;
  84521. }
  84522. }
  84523. else {
  84524. if (ang > ang2 && ang < ang1) {
  84525. return true;
  84526. }
  84527. }
  84528. return false;
  84529. };
  84530. 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()];
  84531. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  84532. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  84533. return BoneLookController;
  84534. }());
  84535. BABYLON.BoneLookController = BoneLookController;
  84536. })(BABYLON || (BABYLON = {}));
  84537. //# sourceMappingURL=babylon.boneLookController.js.map
  84538. var BABYLON;
  84539. (function (BABYLON) {
  84540. /**
  84541. * Class used to handle skinning animations
  84542. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  84543. */
  84544. var Skeleton = /** @class */ (function () {
  84545. /**
  84546. * Creates a new skeleton
  84547. * @param name defines the skeleton name
  84548. * @param id defines the skeleton Id
  84549. * @param scene defines the hosting scene
  84550. */
  84551. function Skeleton(
  84552. /** defines the skeleton name */
  84553. name,
  84554. /** defines the skeleton Id */
  84555. id, scene) {
  84556. this.name = name;
  84557. this.id = id;
  84558. /**
  84559. * Gets the list of child bones
  84560. */
  84561. this.bones = new Array();
  84562. /**
  84563. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  84564. */
  84565. this.needInitialSkinMatrix = false;
  84566. this._isDirty = true;
  84567. this._meshesWithPoseMatrix = new Array();
  84568. this._identity = BABYLON.Matrix.Identity();
  84569. this._ranges = {};
  84570. this._lastAbsoluteTransformsUpdateId = -1;
  84571. /**
  84572. * Specifies if the skeleton should be serialized
  84573. */
  84574. this.doNotSerialize = false;
  84575. this._animationPropertiesOverride = null;
  84576. // Events
  84577. /**
  84578. * An observable triggered before computing the skeleton's matrices
  84579. */
  84580. this.onBeforeComputeObservable = new BABYLON.Observable();
  84581. this.bones = [];
  84582. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  84583. scene.skeletons.push(this);
  84584. //make sure it will recalculate the matrix next time prepare is called.
  84585. this._isDirty = true;
  84586. }
  84587. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  84588. /**
  84589. * Gets or sets the animation properties override
  84590. */
  84591. get: function () {
  84592. if (!this._animationPropertiesOverride) {
  84593. return this._scene.animationPropertiesOverride;
  84594. }
  84595. return this._animationPropertiesOverride;
  84596. },
  84597. set: function (value) {
  84598. this._animationPropertiesOverride = value;
  84599. },
  84600. enumerable: true,
  84601. configurable: true
  84602. });
  84603. // Members
  84604. /**
  84605. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  84606. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  84607. * @returns a Float32Array containing matrices data
  84608. */
  84609. Skeleton.prototype.getTransformMatrices = function (mesh) {
  84610. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  84611. return mesh._bonesTransformMatrices;
  84612. }
  84613. if (!this._transformMatrices) {
  84614. this.prepare();
  84615. }
  84616. return this._transformMatrices;
  84617. };
  84618. /**
  84619. * Gets the current hosting scene
  84620. * @returns a scene object
  84621. */
  84622. Skeleton.prototype.getScene = function () {
  84623. return this._scene;
  84624. };
  84625. // Methods
  84626. /**
  84627. * Gets a string representing the current skeleton data
  84628. * @param fullDetails defines a boolean indicating if we want a verbose version
  84629. * @returns a string representing the current skeleton data
  84630. */
  84631. Skeleton.prototype.toString = function (fullDetails) {
  84632. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  84633. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  84634. if (fullDetails) {
  84635. ret += ", Ranges: {";
  84636. var first = true;
  84637. for (var name_1 in this._ranges) {
  84638. if (first) {
  84639. ret += ", ";
  84640. first = false;
  84641. }
  84642. ret += name_1;
  84643. }
  84644. ret += "}";
  84645. }
  84646. return ret;
  84647. };
  84648. /**
  84649. * Get bone's index searching by name
  84650. * @param name defines bone's name to search for
  84651. * @return the indice of the bone. Returns -1 if not found
  84652. */
  84653. Skeleton.prototype.getBoneIndexByName = function (name) {
  84654. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  84655. if (this.bones[boneIndex].name === name) {
  84656. return boneIndex;
  84657. }
  84658. }
  84659. return -1;
  84660. };
  84661. /**
  84662. * Creater a new animation range
  84663. * @param name defines the name of the range
  84664. * @param from defines the start key
  84665. * @param to defines the end key
  84666. */
  84667. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  84668. // check name not already in use
  84669. if (!this._ranges[name]) {
  84670. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  84671. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  84672. if (this.bones[i].animations[0]) {
  84673. this.bones[i].animations[0].createRange(name, from, to);
  84674. }
  84675. }
  84676. }
  84677. };
  84678. /**
  84679. * Delete a specific animation range
  84680. * @param name defines the name of the range
  84681. * @param deleteFrames defines if frames must be removed as well
  84682. */
  84683. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  84684. if (deleteFrames === void 0) { deleteFrames = true; }
  84685. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  84686. if (this.bones[i].animations[0]) {
  84687. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  84688. }
  84689. }
  84690. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  84691. };
  84692. /**
  84693. * Gets a specific animation range
  84694. * @param name defines the name of the range to look for
  84695. * @returns the requested animation range or null if not found
  84696. */
  84697. Skeleton.prototype.getAnimationRange = function (name) {
  84698. return this._ranges[name];
  84699. };
  84700. /**
  84701. * Gets the list of all animation ranges defined on this skeleton
  84702. * @returns an array
  84703. */
  84704. Skeleton.prototype.getAnimationRanges = function () {
  84705. var animationRanges = [];
  84706. var name;
  84707. var i = 0;
  84708. for (name in this._ranges) {
  84709. animationRanges[i] = this._ranges[name];
  84710. i++;
  84711. }
  84712. return animationRanges;
  84713. };
  84714. /**
  84715. * Copy animation range from a source skeleton.
  84716. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  84717. * @param source defines the source skeleton
  84718. * @param name defines the name of the range to copy
  84719. * @param rescaleAsRequired defines if rescaling must be applied if required
  84720. * @returns true if operation was successful
  84721. */
  84722. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  84723. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  84724. if (this._ranges[name] || !source.getAnimationRange(name)) {
  84725. return false;
  84726. }
  84727. var ret = true;
  84728. var frameOffset = this._getHighestAnimationFrame() + 1;
  84729. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  84730. var boneDict = {};
  84731. var sourceBones = source.bones;
  84732. var nBones;
  84733. var i;
  84734. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  84735. boneDict[sourceBones[i].name] = sourceBones[i];
  84736. }
  84737. if (this.bones.length !== sourceBones.length) {
  84738. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  84739. ret = false;
  84740. }
  84741. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  84742. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  84743. var boneName = this.bones[i].name;
  84744. var sourceBone = boneDict[boneName];
  84745. if (sourceBone) {
  84746. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  84747. }
  84748. else {
  84749. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  84750. ret = false;
  84751. }
  84752. }
  84753. // do not call createAnimationRange(), since it also is done to bones, which was already done
  84754. var range = source.getAnimationRange(name);
  84755. if (range) {
  84756. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  84757. }
  84758. return ret;
  84759. };
  84760. /**
  84761. * Forces the skeleton to go to rest pose
  84762. */
  84763. Skeleton.prototype.returnToRest = function () {
  84764. for (var index = 0; index < this.bones.length; index++) {
  84765. this.bones[index].returnToRest();
  84766. }
  84767. };
  84768. Skeleton.prototype._getHighestAnimationFrame = function () {
  84769. var ret = 0;
  84770. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  84771. if (this.bones[i].animations[0]) {
  84772. var highest = this.bones[i].animations[0].getHighestFrame();
  84773. if (ret < highest) {
  84774. ret = highest;
  84775. }
  84776. }
  84777. }
  84778. return ret;
  84779. };
  84780. /**
  84781. * Begin a specific animation range
  84782. * @param name defines the name of the range to start
  84783. * @param loop defines if looping must be turned on (false by default)
  84784. * @param speedRatio defines the speed ratio to apply (1 by default)
  84785. * @param onAnimationEnd defines a callback which will be called when animation will end
  84786. * @returns a new animatable
  84787. */
  84788. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  84789. var range = this.getAnimationRange(name);
  84790. if (!range) {
  84791. return null;
  84792. }
  84793. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  84794. };
  84795. /** @hidden */
  84796. Skeleton.prototype._markAsDirty = function () {
  84797. this._isDirty = true;
  84798. };
  84799. /** @hidden */
  84800. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  84801. this._meshesWithPoseMatrix.push(mesh);
  84802. };
  84803. /** @hidden */
  84804. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  84805. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  84806. if (index > -1) {
  84807. this._meshesWithPoseMatrix.splice(index, 1);
  84808. }
  84809. };
  84810. /** @hidden */
  84811. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  84812. this.onBeforeComputeObservable.notifyObservers(this);
  84813. for (var index = 0; index < this.bones.length; index++) {
  84814. var bone = this.bones[index];
  84815. var parentBone = bone.getParent();
  84816. if (parentBone) {
  84817. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  84818. }
  84819. else {
  84820. if (initialSkinMatrix) {
  84821. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  84822. }
  84823. else {
  84824. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  84825. }
  84826. }
  84827. if (bone._index !== -1) {
  84828. var mappedIndex = bone._index === null ? index : bone._index;
  84829. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  84830. }
  84831. }
  84832. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  84833. };
  84834. /**
  84835. * Build all resources required to render a skeleton
  84836. */
  84837. Skeleton.prototype.prepare = function () {
  84838. if (!this._isDirty) {
  84839. return;
  84840. }
  84841. if (this.needInitialSkinMatrix) {
  84842. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  84843. var mesh = this._meshesWithPoseMatrix[index];
  84844. var poseMatrix = mesh.getPoseMatrix();
  84845. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  84846. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  84847. }
  84848. if (this._synchronizedWithMesh !== mesh) {
  84849. this._synchronizedWithMesh = mesh;
  84850. // Prepare bones
  84851. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  84852. var bone = this.bones[boneIndex];
  84853. if (!bone.getParent()) {
  84854. var matrix = bone.getBaseMatrix();
  84855. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  84856. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  84857. }
  84858. }
  84859. }
  84860. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  84861. }
  84862. }
  84863. else {
  84864. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  84865. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  84866. }
  84867. this._computeTransformMatrices(this._transformMatrices, null);
  84868. }
  84869. this._isDirty = false;
  84870. this._scene._activeBones.addCount(this.bones.length, false);
  84871. };
  84872. /**
  84873. * Gets the list of animatables currently running for this skeleton
  84874. * @returns an array of animatables
  84875. */
  84876. Skeleton.prototype.getAnimatables = function () {
  84877. if (!this._animatables || this._animatables.length !== this.bones.length) {
  84878. this._animatables = [];
  84879. for (var index = 0; index < this.bones.length; index++) {
  84880. this._animatables.push(this.bones[index]);
  84881. }
  84882. }
  84883. return this._animatables;
  84884. };
  84885. /**
  84886. * Clone the current skeleton
  84887. * @param name defines the name of the new skeleton
  84888. * @param id defines the id of the enw skeleton
  84889. * @returns the new skeleton
  84890. */
  84891. Skeleton.prototype.clone = function (name, id) {
  84892. var result = new Skeleton(name, id || name, this._scene);
  84893. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  84894. for (var index = 0; index < this.bones.length; index++) {
  84895. var source = this.bones[index];
  84896. var parentBone = null;
  84897. var parent_1 = source.getParent();
  84898. if (parent_1) {
  84899. var parentIndex = this.bones.indexOf(parent_1);
  84900. parentBone = result.bones[parentIndex];
  84901. }
  84902. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  84903. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  84904. }
  84905. if (this._ranges) {
  84906. result._ranges = {};
  84907. for (var rangeName in this._ranges) {
  84908. var range = this._ranges[rangeName];
  84909. if (range) {
  84910. result._ranges[rangeName] = range.clone();
  84911. }
  84912. }
  84913. }
  84914. this._isDirty = true;
  84915. return result;
  84916. };
  84917. /**
  84918. * Enable animation blending for this skeleton
  84919. * @param blendingSpeed defines the blending speed to apply
  84920. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  84921. */
  84922. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  84923. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  84924. this.bones.forEach(function (bone) {
  84925. bone.animations.forEach(function (animation) {
  84926. animation.enableBlending = true;
  84927. animation.blendingSpeed = blendingSpeed;
  84928. });
  84929. });
  84930. };
  84931. /**
  84932. * Releases all resources associated with the current skeleton
  84933. */
  84934. Skeleton.prototype.dispose = function () {
  84935. this._meshesWithPoseMatrix = [];
  84936. // Animations
  84937. this.getScene().stopAnimation(this);
  84938. // Remove from scene
  84939. this.getScene().removeSkeleton(this);
  84940. };
  84941. /**
  84942. * Serialize the skeleton in a JSON object
  84943. * @returns a JSON object
  84944. */
  84945. Skeleton.prototype.serialize = function () {
  84946. var serializationObject = {};
  84947. serializationObject.name = this.name;
  84948. serializationObject.id = this.id;
  84949. if (this.dimensionsAtRest) {
  84950. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  84951. }
  84952. serializationObject.bones = [];
  84953. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  84954. for (var index = 0; index < this.bones.length; index++) {
  84955. var bone = this.bones[index];
  84956. var parent_2 = bone.getParent();
  84957. var serializedBone = {
  84958. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  84959. name: bone.name,
  84960. matrix: bone.getBaseMatrix().toArray(),
  84961. rest: bone.getRestPose().toArray()
  84962. };
  84963. serializationObject.bones.push(serializedBone);
  84964. if (bone.length) {
  84965. serializedBone.length = bone.length;
  84966. }
  84967. if (bone.metadata) {
  84968. serializedBone.metadata = bone.metadata;
  84969. }
  84970. if (bone.animations && bone.animations.length > 0) {
  84971. serializedBone.animation = bone.animations[0].serialize();
  84972. }
  84973. serializationObject.ranges = [];
  84974. for (var name in this._ranges) {
  84975. var source = this._ranges[name];
  84976. if (!source) {
  84977. continue;
  84978. }
  84979. var range = {};
  84980. range.name = name;
  84981. range.from = source.from;
  84982. range.to = source.to;
  84983. serializationObject.ranges.push(range);
  84984. }
  84985. }
  84986. return serializationObject;
  84987. };
  84988. /**
  84989. * Creates a new skeleton from serialized data
  84990. * @param parsedSkeleton defines the serialized data
  84991. * @param scene defines the hosting scene
  84992. * @returns a new skeleton
  84993. */
  84994. Skeleton.Parse = function (parsedSkeleton, scene) {
  84995. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  84996. if (parsedSkeleton.dimensionsAtRest) {
  84997. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  84998. }
  84999. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  85000. var index;
  85001. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  85002. var parsedBone = parsedSkeleton.bones[index];
  85003. var parentBone = null;
  85004. if (parsedBone.parentBoneIndex > -1) {
  85005. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  85006. }
  85007. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  85008. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  85009. if (parsedBone.length) {
  85010. bone.length = parsedBone.length;
  85011. }
  85012. if (parsedBone.metadata) {
  85013. bone.metadata = parsedBone.metadata;
  85014. }
  85015. if (parsedBone.animation) {
  85016. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  85017. }
  85018. }
  85019. // placed after bones, so createAnimationRange can cascade down
  85020. if (parsedSkeleton.ranges) {
  85021. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  85022. var data = parsedSkeleton.ranges[index];
  85023. skeleton.createAnimationRange(data.name, data.from, data.to);
  85024. }
  85025. }
  85026. return skeleton;
  85027. };
  85028. /**
  85029. * Compute all node absolute transforms
  85030. * @param forceUpdate defines if computation must be done even if cache is up to date
  85031. */
  85032. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  85033. if (forceUpdate === void 0) { forceUpdate = false; }
  85034. var renderId = this._scene.getRenderId();
  85035. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  85036. this.bones[0].computeAbsoluteTransforms();
  85037. this._lastAbsoluteTransformsUpdateId = renderId;
  85038. }
  85039. };
  85040. /**
  85041. * Gets the root pose matrix
  85042. * @returns a matrix
  85043. */
  85044. Skeleton.prototype.getPoseMatrix = function () {
  85045. var poseMatrix = null;
  85046. if (this._meshesWithPoseMatrix.length > 0) {
  85047. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  85048. }
  85049. return poseMatrix;
  85050. };
  85051. /**
  85052. * Sorts bones per internal index
  85053. */
  85054. Skeleton.prototype.sortBones = function () {
  85055. var bones = new Array();
  85056. var visited = new Array(this.bones.length);
  85057. for (var index = 0; index < this.bones.length; index++) {
  85058. this._sortBones(index, bones, visited);
  85059. }
  85060. this.bones = bones;
  85061. };
  85062. Skeleton.prototype._sortBones = function (index, bones, visited) {
  85063. if (visited[index]) {
  85064. return;
  85065. }
  85066. visited[index] = true;
  85067. var bone = this.bones[index];
  85068. if (bone._index === undefined) {
  85069. bone._index = index;
  85070. }
  85071. var parentBone = bone.getParent();
  85072. if (parentBone) {
  85073. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  85074. }
  85075. bones.push(bone);
  85076. };
  85077. return Skeleton;
  85078. }());
  85079. BABYLON.Skeleton = Skeleton;
  85080. })(BABYLON || (BABYLON = {}));
  85081. //# sourceMappingURL=babylon.skeleton.js.map
  85082. var BABYLON;
  85083. (function (BABYLON) {
  85084. ;
  85085. /**
  85086. * This groups tools to convert HDR texture to native colors array.
  85087. */
  85088. var HDRTools = /** @class */ (function () {
  85089. function HDRTools() {
  85090. }
  85091. HDRTools.Ldexp = function (mantissa, exponent) {
  85092. if (exponent > 1023) {
  85093. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  85094. }
  85095. if (exponent < -1074) {
  85096. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  85097. }
  85098. return mantissa * Math.pow(2, exponent);
  85099. };
  85100. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  85101. if (exponent > 0) { /*nonzero pixel*/
  85102. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  85103. float32array[index + 0] = red * exponent;
  85104. float32array[index + 1] = green * exponent;
  85105. float32array[index + 2] = blue * exponent;
  85106. }
  85107. else {
  85108. float32array[index + 0] = 0;
  85109. float32array[index + 1] = 0;
  85110. float32array[index + 2] = 0;
  85111. }
  85112. };
  85113. HDRTools.readStringLine = function (uint8array, startIndex) {
  85114. var line = "";
  85115. var character = "";
  85116. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  85117. character = String.fromCharCode(uint8array[i]);
  85118. if (character == "\n") {
  85119. break;
  85120. }
  85121. line += character;
  85122. }
  85123. return line;
  85124. };
  85125. /**
  85126. * Reads header information from an RGBE texture stored in a native array.
  85127. * More information on this format are available here:
  85128. * https://en.wikipedia.org/wiki/RGBE_image_format
  85129. *
  85130. * @param uint8array The binary file stored in native array.
  85131. * @return The header information.
  85132. */
  85133. HDRTools.RGBE_ReadHeader = function (uint8array) {
  85134. var height = 0;
  85135. var width = 0;
  85136. var line = this.readStringLine(uint8array, 0);
  85137. if (line[0] != '#' || line[1] != '?') {
  85138. throw "Bad HDR Format.";
  85139. }
  85140. var endOfHeader = false;
  85141. var findFormat = false;
  85142. var lineIndex = 0;
  85143. do {
  85144. lineIndex += (line.length + 1);
  85145. line = this.readStringLine(uint8array, lineIndex);
  85146. if (line == "FORMAT=32-bit_rle_rgbe") {
  85147. findFormat = true;
  85148. }
  85149. else if (line.length == 0) {
  85150. endOfHeader = true;
  85151. }
  85152. } while (!endOfHeader);
  85153. if (!findFormat) {
  85154. throw "HDR Bad header format, unsupported FORMAT";
  85155. }
  85156. lineIndex += (line.length + 1);
  85157. line = this.readStringLine(uint8array, lineIndex);
  85158. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  85159. var match = sizeRegexp.exec(line);
  85160. // TODO. Support +Y and -X if needed.
  85161. if (!match || match.length < 3) {
  85162. throw "HDR Bad header format, no size";
  85163. }
  85164. width = parseInt(match[2]);
  85165. height = parseInt(match[1]);
  85166. if (width < 8 || width > 0x7fff) {
  85167. throw "HDR Bad header format, unsupported size";
  85168. }
  85169. lineIndex += (line.length + 1);
  85170. return {
  85171. height: height,
  85172. width: width,
  85173. dataPosition: lineIndex
  85174. };
  85175. };
  85176. /**
  85177. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  85178. * This RGBE texture needs to store the information as a panorama.
  85179. *
  85180. * More information on this format are available here:
  85181. * https://en.wikipedia.org/wiki/RGBE_image_format
  85182. *
  85183. * @param buffer The binary file stored in an array buffer.
  85184. * @param size The expected size of the extracted cubemap.
  85185. * @return The Cube Map information.
  85186. */
  85187. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  85188. var uint8array = new Uint8Array(buffer);
  85189. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  85190. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  85191. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  85192. return cubeMapData;
  85193. };
  85194. /**
  85195. * Returns the pixels data extracted from an RGBE texture.
  85196. * This pixels will be stored left to right up to down in the R G B order in one array.
  85197. *
  85198. * More information on this format are available here:
  85199. * https://en.wikipedia.org/wiki/RGBE_image_format
  85200. *
  85201. * @param uint8array The binary file stored in an array buffer.
  85202. * @param hdrInfo The header information of the file.
  85203. * @return The pixels data in RGB right to left up to down order.
  85204. */
  85205. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  85206. // Keep for multi format supports.
  85207. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  85208. };
  85209. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  85210. var num_scanlines = hdrInfo.height;
  85211. var scanline_width = hdrInfo.width;
  85212. var a, b, c, d, count;
  85213. var dataIndex = hdrInfo.dataPosition;
  85214. var index = 0, endIndex = 0, i = 0;
  85215. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  85216. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  85217. // 3 channels of 4 bytes per pixel in float.
  85218. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  85219. var resultArray = new Float32Array(resultBuffer);
  85220. // read in each successive scanline
  85221. while (num_scanlines > 0) {
  85222. a = uint8array[dataIndex++];
  85223. b = uint8array[dataIndex++];
  85224. c = uint8array[dataIndex++];
  85225. d = uint8array[dataIndex++];
  85226. if (a != 2 || b != 2 || (c & 0x80)) {
  85227. // this file is not run length encoded
  85228. throw "HDR Bad header format, not RLE";
  85229. }
  85230. if (((c << 8) | d) != scanline_width) {
  85231. throw "HDR Bad header format, wrong scan line width";
  85232. }
  85233. index = 0;
  85234. // read each of the four channels for the scanline into the buffer
  85235. for (i = 0; i < 4; i++) {
  85236. endIndex = (i + 1) * scanline_width;
  85237. while (index < endIndex) {
  85238. a = uint8array[dataIndex++];
  85239. b = uint8array[dataIndex++];
  85240. if (a > 128) {
  85241. // a run of the same value
  85242. count = a - 128;
  85243. if ((count == 0) || (count > endIndex - index)) {
  85244. throw "HDR Bad Format, bad scanline data (run)";
  85245. }
  85246. while (count-- > 0) {
  85247. scanLineArray[index++] = b;
  85248. }
  85249. }
  85250. else {
  85251. // a non-run
  85252. count = a;
  85253. if ((count == 0) || (count > endIndex - index)) {
  85254. throw "HDR Bad Format, bad scanline data (non-run)";
  85255. }
  85256. scanLineArray[index++] = b;
  85257. if (--count > 0) {
  85258. for (var j = 0; j < count; j++) {
  85259. scanLineArray[index++] = uint8array[dataIndex++];
  85260. }
  85261. }
  85262. }
  85263. }
  85264. }
  85265. // now convert data from buffer into floats
  85266. for (i = 0; i < scanline_width; i++) {
  85267. a = scanLineArray[i];
  85268. b = scanLineArray[i + scanline_width];
  85269. c = scanLineArray[i + 2 * scanline_width];
  85270. d = scanLineArray[i + 3 * scanline_width];
  85271. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  85272. }
  85273. num_scanlines--;
  85274. }
  85275. return resultArray;
  85276. };
  85277. return HDRTools;
  85278. }());
  85279. BABYLON.HDRTools = HDRTools;
  85280. })(BABYLON || (BABYLON = {}));
  85281. //# sourceMappingURL=babylon.hdr.js.map
  85282. var BABYLON;
  85283. (function (BABYLON) {
  85284. /**
  85285. * This represents a texture coming from an HDR input.
  85286. *
  85287. * The only supported format is currently panorama picture stored in RGBE format.
  85288. * Example of such files can be found on HDRLib: http://hdrlib.com/
  85289. */
  85290. var HDRCubeTexture = /** @class */ (function (_super) {
  85291. __extends(HDRCubeTexture, _super);
  85292. /**
  85293. * Instantiates an HDRTexture from the following parameters.
  85294. *
  85295. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  85296. * @param scene The scene the texture will be used in
  85297. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  85298. * @param noMipmap Forces to not generate the mipmap if true
  85299. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  85300. * @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)
  85301. * @param reserved Reserved flag for internal use.
  85302. */
  85303. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  85304. if (noMipmap === void 0) { noMipmap = false; }
  85305. if (generateHarmonics === void 0) { generateHarmonics = true; }
  85306. if (gammaSpace === void 0) { gammaSpace = false; }
  85307. if (reserved === void 0) { reserved = false; }
  85308. if (onLoad === void 0) { onLoad = null; }
  85309. if (onError === void 0) { onError = null; }
  85310. var _this = _super.call(this, scene) || this;
  85311. _this._generateHarmonics = true;
  85312. _this._onLoad = null;
  85313. _this._onError = null;
  85314. /**
  85315. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  85316. */
  85317. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  85318. _this._isBlocking = true;
  85319. _this._rotationY = 0;
  85320. /**
  85321. * Gets or sets the center of the bounding box associated with the cube texture
  85322. * It must define where the camera used to render the texture was set
  85323. */
  85324. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  85325. if (!url) {
  85326. return _this;
  85327. }
  85328. _this.name = url;
  85329. _this.url = url;
  85330. _this.hasAlpha = false;
  85331. _this.isCube = true;
  85332. _this._textureMatrix = BABYLON.Matrix.Identity();
  85333. _this._onLoad = onLoad;
  85334. _this._onError = onError;
  85335. _this.gammaSpace = gammaSpace;
  85336. _this._noMipmap = noMipmap;
  85337. _this._size = size;
  85338. _this._texture = _this._getFromCache(url, _this._noMipmap);
  85339. if (!_this._texture) {
  85340. if (!scene.useDelayedTextureLoading) {
  85341. _this.loadTexture();
  85342. }
  85343. else {
  85344. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  85345. }
  85346. }
  85347. return _this;
  85348. }
  85349. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  85350. /**
  85351. * Gets wether or not the texture is blocking during loading.
  85352. */
  85353. get: function () {
  85354. return this._isBlocking;
  85355. },
  85356. /**
  85357. * Sets wether or not the texture is blocking during loading.
  85358. */
  85359. set: function (value) {
  85360. this._isBlocking = value;
  85361. },
  85362. enumerable: true,
  85363. configurable: true
  85364. });
  85365. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  85366. /**
  85367. * Gets texture matrix rotation angle around Y axis radians.
  85368. */
  85369. get: function () {
  85370. return this._rotationY;
  85371. },
  85372. /**
  85373. * Sets texture matrix rotation angle around Y axis in radians.
  85374. */
  85375. set: function (value) {
  85376. this._rotationY = value;
  85377. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  85378. },
  85379. enumerable: true,
  85380. configurable: true
  85381. });
  85382. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  85383. get: function () {
  85384. return this._boundingBoxSize;
  85385. },
  85386. /**
  85387. * Gets or sets the size of the bounding box associated with the cube texture
  85388. * When defined, the cubemap will switch to local mode
  85389. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  85390. * @example https://www.babylonjs-playground.com/#RNASML
  85391. */
  85392. set: function (value) {
  85393. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  85394. return;
  85395. }
  85396. this._boundingBoxSize = value;
  85397. var scene = this.getScene();
  85398. if (scene) {
  85399. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  85400. }
  85401. },
  85402. enumerable: true,
  85403. configurable: true
  85404. });
  85405. /**
  85406. * Occurs when the file is raw .hdr file.
  85407. */
  85408. HDRCubeTexture.prototype.loadTexture = function () {
  85409. var _this = this;
  85410. var callback = function (buffer) {
  85411. _this.lodGenerationOffset = 0.0;
  85412. _this.lodGenerationScale = 0.8;
  85413. var scene = _this.getScene();
  85414. if (!scene) {
  85415. return null;
  85416. }
  85417. // Extract the raw linear data.
  85418. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  85419. // Generate harmonics if needed.
  85420. if (_this._generateHarmonics) {
  85421. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  85422. _this.sphericalPolynomial = sphericalPolynomial;
  85423. }
  85424. var results = [];
  85425. var byteArray = null;
  85426. // Push each faces.
  85427. for (var j = 0; j < 6; j++) {
  85428. // Create uintarray fallback.
  85429. if (!scene.getEngine().getCaps().textureFloat) {
  85430. // 3 channels of 1 bytes per pixel in bytes.
  85431. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  85432. byteArray = new Uint8Array(byteBuffer);
  85433. }
  85434. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  85435. // If special cases.
  85436. if (_this.gammaSpace || byteArray) {
  85437. for (var i = 0; i < _this._size * _this._size; i++) {
  85438. // Put in gamma space if requested.
  85439. if (_this.gammaSpace) {
  85440. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  85441. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  85442. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  85443. }
  85444. // Convert to int texture for fallback.
  85445. if (byteArray) {
  85446. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  85447. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  85448. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  85449. // May use luminance instead if the result is not accurate.
  85450. var max = Math.max(Math.max(r, g), b);
  85451. if (max > 255) {
  85452. var scale = 255 / max;
  85453. r *= scale;
  85454. g *= scale;
  85455. b *= scale;
  85456. }
  85457. byteArray[(i * 3) + 0] = r;
  85458. byteArray[(i * 3) + 1] = g;
  85459. byteArray[(i * 3) + 2] = b;
  85460. }
  85461. }
  85462. }
  85463. if (byteArray) {
  85464. results.push(byteArray);
  85465. }
  85466. else {
  85467. results.push(dataFace);
  85468. }
  85469. }
  85470. return results;
  85471. };
  85472. var scene = this.getScene();
  85473. if (scene) {
  85474. 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);
  85475. }
  85476. };
  85477. HDRCubeTexture.prototype.clone = function () {
  85478. var scene = this.getScene();
  85479. if (!scene) {
  85480. return this;
  85481. }
  85482. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  85483. // Base texture
  85484. newTexture.level = this.level;
  85485. newTexture.wrapU = this.wrapU;
  85486. newTexture.wrapV = this.wrapV;
  85487. newTexture.coordinatesIndex = this.coordinatesIndex;
  85488. newTexture.coordinatesMode = this.coordinatesMode;
  85489. return newTexture;
  85490. };
  85491. // Methods
  85492. HDRCubeTexture.prototype.delayLoad = function () {
  85493. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  85494. return;
  85495. }
  85496. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  85497. this._texture = this._getFromCache(this.url, this._noMipmap);
  85498. if (!this._texture) {
  85499. this.loadTexture();
  85500. }
  85501. };
  85502. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  85503. return this._textureMatrix;
  85504. };
  85505. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  85506. this._textureMatrix = value;
  85507. };
  85508. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  85509. var texture = null;
  85510. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  85511. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  85512. texture.name = parsedTexture.name;
  85513. texture.hasAlpha = parsedTexture.hasAlpha;
  85514. texture.level = parsedTexture.level;
  85515. texture.coordinatesMode = parsedTexture.coordinatesMode;
  85516. texture.isBlocking = parsedTexture.isBlocking;
  85517. }
  85518. if (texture) {
  85519. if (parsedTexture.boundingBoxPosition) {
  85520. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  85521. }
  85522. if (parsedTexture.boundingBoxSize) {
  85523. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  85524. }
  85525. if (parsedTexture.rotationY) {
  85526. texture.rotationY = parsedTexture.rotationY;
  85527. }
  85528. }
  85529. return texture;
  85530. };
  85531. HDRCubeTexture.prototype.serialize = function () {
  85532. if (!this.name) {
  85533. return null;
  85534. }
  85535. var serializationObject = {};
  85536. serializationObject.name = this.name;
  85537. serializationObject.hasAlpha = this.hasAlpha;
  85538. serializationObject.isCube = true;
  85539. serializationObject.level = this.level;
  85540. serializationObject.size = this._size;
  85541. serializationObject.coordinatesMode = this.coordinatesMode;
  85542. serializationObject.useInGammaSpace = this.gammaSpace;
  85543. serializationObject.generateHarmonics = this._generateHarmonics;
  85544. serializationObject.customType = "BABYLON.HDRCubeTexture";
  85545. serializationObject.noMipmap = this._noMipmap;
  85546. serializationObject.isBlocking = this._isBlocking;
  85547. serializationObject.rotationY = this._rotationY;
  85548. return serializationObject;
  85549. };
  85550. HDRCubeTexture._facesMapping = [
  85551. "right",
  85552. "left",
  85553. "up",
  85554. "down",
  85555. "front",
  85556. "back"
  85557. ];
  85558. return HDRCubeTexture;
  85559. }(BABYLON.BaseTexture));
  85560. BABYLON.HDRCubeTexture = HDRCubeTexture;
  85561. })(BABYLON || (BABYLON = {}));
  85562. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  85563. var BABYLON;
  85564. (function (BABYLON) {
  85565. /**
  85566. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  85567. */
  85568. var PanoramaToCubeMapTools = /** @class */ (function () {
  85569. function PanoramaToCubeMapTools() {
  85570. }
  85571. /**
  85572. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  85573. *
  85574. * @param float32Array The source data.
  85575. * @param inputWidth The width of the input panorama.
  85576. * @param inputhHeight The height of the input panorama.
  85577. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  85578. * @return The cubemap data
  85579. */
  85580. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  85581. if (!float32Array) {
  85582. throw "ConvertPanoramaToCubemap: input cannot be null";
  85583. }
  85584. if (float32Array.length != inputWidth * inputHeight * 3) {
  85585. throw "ConvertPanoramaToCubemap: input size is wrong";
  85586. }
  85587. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  85588. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  85589. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  85590. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  85591. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  85592. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  85593. return {
  85594. front: textureFront,
  85595. back: textureBack,
  85596. left: textureLeft,
  85597. right: textureRight,
  85598. up: textureUp,
  85599. down: textureDown,
  85600. size: size,
  85601. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  85602. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  85603. gammaSpace: false,
  85604. };
  85605. };
  85606. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  85607. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  85608. var textureArray = new Float32Array(buffer);
  85609. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  85610. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  85611. var dy = 1 / texSize;
  85612. var fy = 0;
  85613. for (var y = 0; y < texSize; y++) {
  85614. var xv1 = faceData[0];
  85615. var xv2 = faceData[2];
  85616. for (var x = 0; x < texSize; x++) {
  85617. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  85618. v.normalize();
  85619. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  85620. // 3 channels per pixels
  85621. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  85622. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  85623. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  85624. xv1 = xv1.add(rotDX1);
  85625. xv2 = xv2.add(rotDX2);
  85626. }
  85627. fy += dy;
  85628. }
  85629. return textureArray;
  85630. };
  85631. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  85632. var theta = Math.atan2(vDir.z, vDir.x);
  85633. var phi = Math.acos(vDir.y);
  85634. while (theta < -Math.PI)
  85635. theta += 2 * Math.PI;
  85636. while (theta > Math.PI)
  85637. theta -= 2 * Math.PI;
  85638. var dx = theta / Math.PI;
  85639. var dy = phi / Math.PI;
  85640. // recenter.
  85641. dx = dx * 0.5 + 0.5;
  85642. var px = Math.round(dx * inputWidth);
  85643. if (px < 0)
  85644. px = 0;
  85645. else if (px >= inputWidth)
  85646. px = inputWidth - 1;
  85647. var py = Math.round(dy * inputHeight);
  85648. if (py < 0)
  85649. py = 0;
  85650. else if (py >= inputHeight)
  85651. py = inputHeight - 1;
  85652. var inputY = (inputHeight - py - 1);
  85653. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  85654. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  85655. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  85656. return {
  85657. r: r,
  85658. g: g,
  85659. b: b
  85660. };
  85661. };
  85662. PanoramaToCubeMapTools.FACE_FRONT = [
  85663. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  85664. new BABYLON.Vector3(1.0, -1.0, -1.0),
  85665. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  85666. new BABYLON.Vector3(1.0, 1.0, -1.0)
  85667. ];
  85668. PanoramaToCubeMapTools.FACE_BACK = [
  85669. new BABYLON.Vector3(1.0, -1.0, 1.0),
  85670. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  85671. new BABYLON.Vector3(1.0, 1.0, 1.0),
  85672. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  85673. ];
  85674. PanoramaToCubeMapTools.FACE_RIGHT = [
  85675. new BABYLON.Vector3(1.0, -1.0, -1.0),
  85676. new BABYLON.Vector3(1.0, -1.0, 1.0),
  85677. new BABYLON.Vector3(1.0, 1.0, -1.0),
  85678. new BABYLON.Vector3(1.0, 1.0, 1.0)
  85679. ];
  85680. PanoramaToCubeMapTools.FACE_LEFT = [
  85681. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  85682. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  85683. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  85684. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  85685. ];
  85686. PanoramaToCubeMapTools.FACE_DOWN = [
  85687. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  85688. new BABYLON.Vector3(1.0, 1.0, -1.0),
  85689. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  85690. new BABYLON.Vector3(1.0, 1.0, 1.0)
  85691. ];
  85692. PanoramaToCubeMapTools.FACE_UP = [
  85693. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  85694. new BABYLON.Vector3(1.0, -1.0, 1.0),
  85695. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  85696. new BABYLON.Vector3(1.0, -1.0, -1.0)
  85697. ];
  85698. return PanoramaToCubeMapTools;
  85699. }());
  85700. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  85701. })(BABYLON || (BABYLON = {}));
  85702. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  85703. var BABYLON;
  85704. (function (BABYLON) {
  85705. var IndexedVector2 = /** @class */ (function (_super) {
  85706. __extends(IndexedVector2, _super);
  85707. function IndexedVector2(original, index) {
  85708. var _this = _super.call(this, original.x, original.y) || this;
  85709. _this.index = index;
  85710. return _this;
  85711. }
  85712. return IndexedVector2;
  85713. }(BABYLON.Vector2));
  85714. var PolygonPoints = /** @class */ (function () {
  85715. function PolygonPoints() {
  85716. this.elements = new Array();
  85717. }
  85718. PolygonPoints.prototype.add = function (originalPoints) {
  85719. var _this = this;
  85720. var result = new Array();
  85721. originalPoints.forEach(function (point) {
  85722. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  85723. var newPoint = new IndexedVector2(point, _this.elements.length);
  85724. result.push(newPoint);
  85725. _this.elements.push(newPoint);
  85726. }
  85727. });
  85728. return result;
  85729. };
  85730. PolygonPoints.prototype.computeBounds = function () {
  85731. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  85732. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  85733. this.elements.forEach(function (point) {
  85734. // x
  85735. if (point.x < lmin.x) {
  85736. lmin.x = point.x;
  85737. }
  85738. else if (point.x > lmax.x) {
  85739. lmax.x = point.x;
  85740. }
  85741. // y
  85742. if (point.y < lmin.y) {
  85743. lmin.y = point.y;
  85744. }
  85745. else if (point.y > lmax.y) {
  85746. lmax.y = point.y;
  85747. }
  85748. });
  85749. return {
  85750. min: lmin,
  85751. max: lmax,
  85752. width: lmax.x - lmin.x,
  85753. height: lmax.y - lmin.y
  85754. };
  85755. };
  85756. return PolygonPoints;
  85757. }());
  85758. var Polygon = /** @class */ (function () {
  85759. function Polygon() {
  85760. }
  85761. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  85762. return [
  85763. new BABYLON.Vector2(xmin, ymin),
  85764. new BABYLON.Vector2(xmax, ymin),
  85765. new BABYLON.Vector2(xmax, ymax),
  85766. new BABYLON.Vector2(xmin, ymax)
  85767. ];
  85768. };
  85769. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  85770. if (cx === void 0) { cx = 0; }
  85771. if (cy === void 0) { cy = 0; }
  85772. if (numberOfSides === void 0) { numberOfSides = 32; }
  85773. var result = new Array();
  85774. var angle = 0;
  85775. var increment = (Math.PI * 2) / numberOfSides;
  85776. for (var i = 0; i < numberOfSides; i++) {
  85777. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  85778. angle -= increment;
  85779. }
  85780. return result;
  85781. };
  85782. Polygon.Parse = function (input) {
  85783. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  85784. var i, result = [];
  85785. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  85786. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  85787. }
  85788. return result;
  85789. };
  85790. Polygon.StartingAt = function (x, y) {
  85791. return BABYLON.Path2.StartingAt(x, y);
  85792. };
  85793. return Polygon;
  85794. }());
  85795. BABYLON.Polygon = Polygon;
  85796. var PolygonMeshBuilder = /** @class */ (function () {
  85797. function PolygonMeshBuilder(name, contours, scene) {
  85798. this._points = new PolygonPoints();
  85799. this._outlinepoints = new PolygonPoints();
  85800. this._holes = new Array();
  85801. this._epoints = new Array();
  85802. this._eholes = new Array();
  85803. this._name = name;
  85804. this._scene = scene;
  85805. var points;
  85806. if (contours instanceof BABYLON.Path2) {
  85807. points = contours.getPoints();
  85808. }
  85809. else {
  85810. points = contours;
  85811. }
  85812. this._addToepoint(points);
  85813. this._points.add(points);
  85814. this._outlinepoints.add(points);
  85815. if (typeof earcut === 'undefined') {
  85816. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  85817. }
  85818. }
  85819. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  85820. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  85821. var p = points_1[_i];
  85822. this._epoints.push(p.x, p.y);
  85823. }
  85824. };
  85825. PolygonMeshBuilder.prototype.addHole = function (hole) {
  85826. this._points.add(hole);
  85827. var holepoints = new PolygonPoints();
  85828. holepoints.add(hole);
  85829. this._holes.push(holepoints);
  85830. this._eholes.push(this._epoints.length / 2);
  85831. this._addToepoint(hole);
  85832. return this;
  85833. };
  85834. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  85835. var _this = this;
  85836. if (updatable === void 0) { updatable = false; }
  85837. if (depth === void 0) { depth = 0; }
  85838. var result = new BABYLON.Mesh(this._name, this._scene);
  85839. var normals = new Array();
  85840. var positions = new Array();
  85841. var uvs = new Array();
  85842. var bounds = this._points.computeBounds();
  85843. this._points.elements.forEach(function (p) {
  85844. normals.push(0, 1.0, 0);
  85845. positions.push(p.x, 0, p.y);
  85846. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  85847. });
  85848. var indices = new Array();
  85849. var res = earcut(this._epoints, this._eholes, 2);
  85850. for (var i = 0; i < res.length; i++) {
  85851. indices.push(res[i]);
  85852. }
  85853. if (depth > 0) {
  85854. var positionscount = (positions.length / 3); //get the current pointcount
  85855. this._points.elements.forEach(function (p) {
  85856. normals.push(0, -1.0, 0);
  85857. positions.push(p.x, -depth, p.y);
  85858. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  85859. });
  85860. var totalCount = indices.length;
  85861. for (var i = 0; i < totalCount; i += 3) {
  85862. var i0 = indices[i + 0];
  85863. var i1 = indices[i + 1];
  85864. var i2 = indices[i + 2];
  85865. indices.push(i2 + positionscount);
  85866. indices.push(i1 + positionscount);
  85867. indices.push(i0 + positionscount);
  85868. }
  85869. //Add the sides
  85870. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  85871. this._holes.forEach(function (hole) {
  85872. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  85873. });
  85874. }
  85875. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  85876. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  85877. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  85878. result.setIndices(indices);
  85879. return result;
  85880. };
  85881. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  85882. var StartIndex = positions.length / 3;
  85883. var ulength = 0;
  85884. for (var i = 0; i < points.elements.length; i++) {
  85885. var p = points.elements[i];
  85886. var p1;
  85887. if ((i + 1) > points.elements.length - 1) {
  85888. p1 = points.elements[0];
  85889. }
  85890. else {
  85891. p1 = points.elements[i + 1];
  85892. }
  85893. positions.push(p.x, 0, p.y);
  85894. positions.push(p.x, -depth, p.y);
  85895. positions.push(p1.x, 0, p1.y);
  85896. positions.push(p1.x, -depth, p1.y);
  85897. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  85898. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  85899. var v3 = v2.subtract(v1);
  85900. var v4 = new BABYLON.Vector3(0, 1, 0);
  85901. var vn = BABYLON.Vector3.Cross(v3, v4);
  85902. vn = vn.normalize();
  85903. uvs.push(ulength / bounds.width, 0);
  85904. uvs.push(ulength / bounds.width, 1);
  85905. ulength += v3.length();
  85906. uvs.push((ulength / bounds.width), 0);
  85907. uvs.push((ulength / bounds.width), 1);
  85908. if (!flip) {
  85909. normals.push(-vn.x, -vn.y, -vn.z);
  85910. normals.push(-vn.x, -vn.y, -vn.z);
  85911. normals.push(-vn.x, -vn.y, -vn.z);
  85912. normals.push(-vn.x, -vn.y, -vn.z);
  85913. indices.push(StartIndex);
  85914. indices.push(StartIndex + 1);
  85915. indices.push(StartIndex + 2);
  85916. indices.push(StartIndex + 1);
  85917. indices.push(StartIndex + 3);
  85918. indices.push(StartIndex + 2);
  85919. }
  85920. else {
  85921. normals.push(vn.x, vn.y, vn.z);
  85922. normals.push(vn.x, vn.y, vn.z);
  85923. normals.push(vn.x, vn.y, vn.z);
  85924. normals.push(vn.x, vn.y, vn.z);
  85925. indices.push(StartIndex);
  85926. indices.push(StartIndex + 2);
  85927. indices.push(StartIndex + 1);
  85928. indices.push(StartIndex + 1);
  85929. indices.push(StartIndex + 2);
  85930. indices.push(StartIndex + 3);
  85931. }
  85932. StartIndex += 4;
  85933. }
  85934. ;
  85935. };
  85936. return PolygonMeshBuilder;
  85937. }());
  85938. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  85939. })(BABYLON || (BABYLON = {}));
  85940. //# sourceMappingURL=babylon.polygonMesh.js.map
  85941. var BABYLON;
  85942. (function (BABYLON) {
  85943. // Unique ID when we import meshes from Babylon to CSG
  85944. var currentCSGMeshId = 0;
  85945. // # class Vertex
  85946. // Represents a vertex of a polygon. Use your own vertex class instead of this
  85947. // one to provide additional features like texture coordinates and vertex
  85948. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  85949. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  85950. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  85951. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  85952. // is not used anywhere else.
  85953. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  85954. var Vertex = /** @class */ (function () {
  85955. function Vertex(pos, normal, uv) {
  85956. this.pos = pos;
  85957. this.normal = normal;
  85958. this.uv = uv;
  85959. }
  85960. Vertex.prototype.clone = function () {
  85961. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  85962. };
  85963. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  85964. // orientation of a polygon is flipped.
  85965. Vertex.prototype.flip = function () {
  85966. this.normal = this.normal.scale(-1);
  85967. };
  85968. // Create a new vertex between this vertex and `other` by linearly
  85969. // interpolating all properties using a parameter of `t`. Subclasses should
  85970. // override this to interpolate additional properties.
  85971. Vertex.prototype.interpolate = function (other, t) {
  85972. 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));
  85973. };
  85974. return Vertex;
  85975. }());
  85976. // # class Plane
  85977. // Represents a plane in 3D space.
  85978. var Plane = /** @class */ (function () {
  85979. function Plane(normal, w) {
  85980. this.normal = normal;
  85981. this.w = w;
  85982. }
  85983. Plane.FromPoints = function (a, b, c) {
  85984. var v0 = c.subtract(a);
  85985. var v1 = b.subtract(a);
  85986. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  85987. return null;
  85988. }
  85989. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  85990. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  85991. };
  85992. Plane.prototype.clone = function () {
  85993. return new Plane(this.normal.clone(), this.w);
  85994. };
  85995. Plane.prototype.flip = function () {
  85996. this.normal.scaleInPlace(-1);
  85997. this.w = -this.w;
  85998. };
  85999. // Split `polygon` by this plane if needed, then put the polygon or polygon
  86000. // fragments in the appropriate lists. Coplanar polygons go into either
  86001. // `coplanarFront` or `coplanarBack` depending on their orientation with
  86002. // respect to this plane. Polygons in front or in back of this plane go into
  86003. // either `front` or `back`.
  86004. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  86005. var COPLANAR = 0;
  86006. var FRONT = 1;
  86007. var BACK = 2;
  86008. var SPANNING = 3;
  86009. // Classify each point as well as the entire polygon into one of the above
  86010. // four classes.
  86011. var polygonType = 0;
  86012. var types = [];
  86013. var i;
  86014. var t;
  86015. for (i = 0; i < polygon.vertices.length; i++) {
  86016. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  86017. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  86018. polygonType |= type;
  86019. types.push(type);
  86020. }
  86021. // Put the polygon in the correct list, splitting it when necessary.
  86022. switch (polygonType) {
  86023. case COPLANAR:
  86024. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  86025. break;
  86026. case FRONT:
  86027. front.push(polygon);
  86028. break;
  86029. case BACK:
  86030. back.push(polygon);
  86031. break;
  86032. case SPANNING:
  86033. var f = [], b = [];
  86034. for (i = 0; i < polygon.vertices.length; i++) {
  86035. var j = (i + 1) % polygon.vertices.length;
  86036. var ti = types[i], tj = types[j];
  86037. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  86038. if (ti !== BACK)
  86039. f.push(vi);
  86040. if (ti !== FRONT)
  86041. b.push(ti !== BACK ? vi.clone() : vi);
  86042. if ((ti | tj) === SPANNING) {
  86043. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  86044. var v = vi.interpolate(vj, t);
  86045. f.push(v);
  86046. b.push(v.clone());
  86047. }
  86048. }
  86049. var poly;
  86050. if (f.length >= 3) {
  86051. poly = new Polygon(f, polygon.shared);
  86052. if (poly.plane)
  86053. front.push(poly);
  86054. }
  86055. if (b.length >= 3) {
  86056. poly = new Polygon(b, polygon.shared);
  86057. if (poly.plane)
  86058. back.push(poly);
  86059. }
  86060. break;
  86061. }
  86062. };
  86063. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  86064. // point is on the plane.
  86065. Plane.EPSILON = 1e-5;
  86066. return Plane;
  86067. }());
  86068. // # class Polygon
  86069. // Represents a convex polygon. The vertices used to initialize a polygon must
  86070. // be coplanar and form a convex loop.
  86071. //
  86072. // Each convex polygon has a `shared` property, which is shared between all
  86073. // polygons that are clones of each other or were split from the same polygon.
  86074. // This can be used to define per-polygon properties (such as surface color).
  86075. var Polygon = /** @class */ (function () {
  86076. function Polygon(vertices, shared) {
  86077. this.vertices = vertices;
  86078. this.shared = shared;
  86079. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  86080. }
  86081. Polygon.prototype.clone = function () {
  86082. var vertices = this.vertices.map(function (v) { return v.clone(); });
  86083. return new Polygon(vertices, this.shared);
  86084. };
  86085. Polygon.prototype.flip = function () {
  86086. this.vertices.reverse().map(function (v) { v.flip(); });
  86087. this.plane.flip();
  86088. };
  86089. return Polygon;
  86090. }());
  86091. // # class Node
  86092. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  86093. // by picking a polygon to split along. That polygon (and all other coplanar
  86094. // polygons) are added directly to that node and the other polygons are added to
  86095. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  86096. // no distinction between internal and leaf nodes.
  86097. var Node = /** @class */ (function () {
  86098. function Node(polygons) {
  86099. this.plane = null;
  86100. this.front = null;
  86101. this.back = null;
  86102. this.polygons = new Array();
  86103. if (polygons) {
  86104. this.build(polygons);
  86105. }
  86106. }
  86107. Node.prototype.clone = function () {
  86108. var node = new Node();
  86109. node.plane = this.plane && this.plane.clone();
  86110. node.front = this.front && this.front.clone();
  86111. node.back = this.back && this.back.clone();
  86112. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  86113. return node;
  86114. };
  86115. // Convert solid space to empty space and empty space to solid space.
  86116. Node.prototype.invert = function () {
  86117. for (var i = 0; i < this.polygons.length; i++) {
  86118. this.polygons[i].flip();
  86119. }
  86120. if (this.plane) {
  86121. this.plane.flip();
  86122. }
  86123. if (this.front) {
  86124. this.front.invert();
  86125. }
  86126. if (this.back) {
  86127. this.back.invert();
  86128. }
  86129. var temp = this.front;
  86130. this.front = this.back;
  86131. this.back = temp;
  86132. };
  86133. // Recursively remove all polygons in `polygons` that are inside this BSP
  86134. // tree.
  86135. Node.prototype.clipPolygons = function (polygons) {
  86136. if (!this.plane)
  86137. return polygons.slice();
  86138. var front = new Array(), back = new Array();
  86139. for (var i = 0; i < polygons.length; i++) {
  86140. this.plane.splitPolygon(polygons[i], front, back, front, back);
  86141. }
  86142. if (this.front) {
  86143. front = this.front.clipPolygons(front);
  86144. }
  86145. if (this.back) {
  86146. back = this.back.clipPolygons(back);
  86147. }
  86148. else {
  86149. back = [];
  86150. }
  86151. return front.concat(back);
  86152. };
  86153. // Remove all polygons in this BSP tree that are inside the other BSP tree
  86154. // `bsp`.
  86155. Node.prototype.clipTo = function (bsp) {
  86156. this.polygons = bsp.clipPolygons(this.polygons);
  86157. if (this.front)
  86158. this.front.clipTo(bsp);
  86159. if (this.back)
  86160. this.back.clipTo(bsp);
  86161. };
  86162. // Return a list of all polygons in this BSP tree.
  86163. Node.prototype.allPolygons = function () {
  86164. var polygons = this.polygons.slice();
  86165. if (this.front)
  86166. polygons = polygons.concat(this.front.allPolygons());
  86167. if (this.back)
  86168. polygons = polygons.concat(this.back.allPolygons());
  86169. return polygons;
  86170. };
  86171. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  86172. // new polygons are filtered down to the bottom of the tree and become new
  86173. // nodes there. Each set of polygons is partitioned using the first polygon
  86174. // (no heuristic is used to pick a good split).
  86175. Node.prototype.build = function (polygons) {
  86176. if (!polygons.length)
  86177. return;
  86178. if (!this.plane)
  86179. this.plane = polygons[0].plane.clone();
  86180. var front = new Array(), back = new Array();
  86181. for (var i = 0; i < polygons.length; i++) {
  86182. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  86183. }
  86184. if (front.length) {
  86185. if (!this.front)
  86186. this.front = new Node();
  86187. this.front.build(front);
  86188. }
  86189. if (back.length) {
  86190. if (!this.back)
  86191. this.back = new Node();
  86192. this.back.build(back);
  86193. }
  86194. };
  86195. return Node;
  86196. }());
  86197. var CSG = /** @class */ (function () {
  86198. function CSG() {
  86199. this.polygons = new Array();
  86200. }
  86201. // Convert BABYLON.Mesh to BABYLON.CSG
  86202. CSG.FromMesh = function (mesh) {
  86203. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  86204. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  86205. if (mesh instanceof BABYLON.Mesh) {
  86206. mesh.computeWorldMatrix(true);
  86207. matrix = mesh.getWorldMatrix();
  86208. meshPosition = mesh.position.clone();
  86209. meshRotation = mesh.rotation.clone();
  86210. if (mesh.rotationQuaternion) {
  86211. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  86212. }
  86213. meshScaling = mesh.scaling.clone();
  86214. }
  86215. else {
  86216. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  86217. }
  86218. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  86219. var subMeshes = mesh.subMeshes;
  86220. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  86221. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  86222. vertices = [];
  86223. for (var j = 0; j < 3; j++) {
  86224. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  86225. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  86226. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  86227. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  86228. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  86229. vertex = new Vertex(position, normal, uv);
  86230. vertices.push(vertex);
  86231. }
  86232. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  86233. // To handle the case of degenerated triangle
  86234. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  86235. if (polygon.plane)
  86236. polygons.push(polygon);
  86237. }
  86238. }
  86239. var csg = CSG.FromPolygons(polygons);
  86240. csg.matrix = matrix;
  86241. csg.position = meshPosition;
  86242. csg.rotation = meshRotation;
  86243. csg.scaling = meshScaling;
  86244. csg.rotationQuaternion = meshRotationQuaternion;
  86245. currentCSGMeshId++;
  86246. return csg;
  86247. };
  86248. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  86249. CSG.FromPolygons = function (polygons) {
  86250. var csg = new CSG();
  86251. csg.polygons = polygons;
  86252. return csg;
  86253. };
  86254. CSG.prototype.clone = function () {
  86255. var csg = new CSG();
  86256. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  86257. csg.copyTransformAttributes(this);
  86258. return csg;
  86259. };
  86260. CSG.prototype.union = function (csg) {
  86261. var a = new Node(this.clone().polygons);
  86262. var b = new Node(csg.clone().polygons);
  86263. a.clipTo(b);
  86264. b.clipTo(a);
  86265. b.invert();
  86266. b.clipTo(a);
  86267. b.invert();
  86268. a.build(b.allPolygons());
  86269. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  86270. };
  86271. CSG.prototype.unionInPlace = function (csg) {
  86272. var a = new Node(this.polygons);
  86273. var b = new Node(csg.polygons);
  86274. a.clipTo(b);
  86275. b.clipTo(a);
  86276. b.invert();
  86277. b.clipTo(a);
  86278. b.invert();
  86279. a.build(b.allPolygons());
  86280. this.polygons = a.allPolygons();
  86281. };
  86282. CSG.prototype.subtract = function (csg) {
  86283. var a = new Node(this.clone().polygons);
  86284. var b = new Node(csg.clone().polygons);
  86285. a.invert();
  86286. a.clipTo(b);
  86287. b.clipTo(a);
  86288. b.invert();
  86289. b.clipTo(a);
  86290. b.invert();
  86291. a.build(b.allPolygons());
  86292. a.invert();
  86293. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  86294. };
  86295. CSG.prototype.subtractInPlace = function (csg) {
  86296. var a = new Node(this.polygons);
  86297. var b = new Node(csg.polygons);
  86298. a.invert();
  86299. a.clipTo(b);
  86300. b.clipTo(a);
  86301. b.invert();
  86302. b.clipTo(a);
  86303. b.invert();
  86304. a.build(b.allPolygons());
  86305. a.invert();
  86306. this.polygons = a.allPolygons();
  86307. };
  86308. CSG.prototype.intersect = function (csg) {
  86309. var a = new Node(this.clone().polygons);
  86310. var b = new Node(csg.clone().polygons);
  86311. a.invert();
  86312. b.clipTo(a);
  86313. b.invert();
  86314. a.clipTo(b);
  86315. b.clipTo(a);
  86316. a.build(b.allPolygons());
  86317. a.invert();
  86318. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  86319. };
  86320. CSG.prototype.intersectInPlace = function (csg) {
  86321. var a = new Node(this.polygons);
  86322. var b = new Node(csg.polygons);
  86323. a.invert();
  86324. b.clipTo(a);
  86325. b.invert();
  86326. a.clipTo(b);
  86327. b.clipTo(a);
  86328. a.build(b.allPolygons());
  86329. a.invert();
  86330. this.polygons = a.allPolygons();
  86331. };
  86332. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  86333. // not modified.
  86334. CSG.prototype.inverse = function () {
  86335. var csg = this.clone();
  86336. csg.inverseInPlace();
  86337. return csg;
  86338. };
  86339. CSG.prototype.inverseInPlace = function () {
  86340. this.polygons.map(function (p) { p.flip(); });
  86341. };
  86342. // This is used to keep meshes transformations so they can be restored
  86343. // when we build back a Babylon Mesh
  86344. // NB : All CSG operations are performed in world coordinates
  86345. CSG.prototype.copyTransformAttributes = function (csg) {
  86346. this.matrix = csg.matrix;
  86347. this.position = csg.position;
  86348. this.rotation = csg.rotation;
  86349. this.scaling = csg.scaling;
  86350. this.rotationQuaternion = csg.rotationQuaternion;
  86351. return this;
  86352. };
  86353. // Build Raw mesh from CSG
  86354. // Coordinates here are in world space
  86355. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  86356. var matrix = this.matrix.clone();
  86357. matrix.invert();
  86358. 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;
  86359. if (keepSubMeshes) {
  86360. // Sort Polygons, since subMeshes are indices range
  86361. polygons.sort(function (a, b) {
  86362. if (a.shared.meshId === b.shared.meshId) {
  86363. return a.shared.subMeshId - b.shared.subMeshId;
  86364. }
  86365. else {
  86366. return a.shared.meshId - b.shared.meshId;
  86367. }
  86368. });
  86369. }
  86370. for (var i = 0, il = polygons.length; i < il; i++) {
  86371. polygon = polygons[i];
  86372. // Building SubMeshes
  86373. if (!subMesh_dict[polygon.shared.meshId]) {
  86374. subMesh_dict[polygon.shared.meshId] = {};
  86375. }
  86376. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  86377. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  86378. indexStart: +Infinity,
  86379. indexEnd: -Infinity,
  86380. materialIndex: polygon.shared.materialIndex
  86381. };
  86382. }
  86383. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  86384. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  86385. polygonIndices[0] = 0;
  86386. polygonIndices[1] = j - 1;
  86387. polygonIndices[2] = j;
  86388. for (var k = 0; k < 3; k++) {
  86389. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  86390. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  86391. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  86392. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  86393. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  86394. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  86395. // Check if 2 points can be merged
  86396. if (!(typeof vertex_idx !== 'undefined' &&
  86397. normals[vertex_idx * 3] === localNormal.x &&
  86398. normals[vertex_idx * 3 + 1] === localNormal.y &&
  86399. normals[vertex_idx * 3 + 2] === localNormal.z &&
  86400. uvs[vertex_idx * 2] === uv.x &&
  86401. uvs[vertex_idx * 2 + 1] === uv.y)) {
  86402. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  86403. uvs.push(uv.x, uv.y);
  86404. normals.push(normal.x, normal.y, normal.z);
  86405. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  86406. }
  86407. indices.push(vertex_idx);
  86408. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  86409. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  86410. currentIndex++;
  86411. }
  86412. }
  86413. }
  86414. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  86415. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  86416. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  86417. mesh.setIndices(indices, null);
  86418. if (keepSubMeshes) {
  86419. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  86420. var materialIndexOffset = 0, materialMaxIndex;
  86421. mesh.subMeshes = new Array();
  86422. for (var m in subMesh_dict) {
  86423. materialMaxIndex = -1;
  86424. for (var sm in subMesh_dict[m]) {
  86425. subMesh_obj = subMesh_dict[m][sm];
  86426. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  86427. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  86428. }
  86429. materialIndexOffset += ++materialMaxIndex;
  86430. }
  86431. }
  86432. return mesh;
  86433. };
  86434. // Build Mesh from CSG taking material and transforms into account
  86435. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  86436. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  86437. mesh.material = material;
  86438. mesh.position.copyFrom(this.position);
  86439. mesh.rotation.copyFrom(this.rotation);
  86440. if (this.rotationQuaternion) {
  86441. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  86442. }
  86443. mesh.scaling.copyFrom(this.scaling);
  86444. mesh.computeWorldMatrix(true);
  86445. return mesh;
  86446. };
  86447. return CSG;
  86448. }());
  86449. BABYLON.CSG = CSG;
  86450. })(BABYLON || (BABYLON = {}));
  86451. //# sourceMappingURL=babylon.csg.js.map
  86452. var BABYLON;
  86453. (function (BABYLON) {
  86454. var LensFlare = /** @class */ (function () {
  86455. function LensFlare(size, position, color, imgUrl, system) {
  86456. this.size = size;
  86457. this.position = position;
  86458. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  86459. this.color = color || new BABYLON.Color3(1, 1, 1);
  86460. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  86461. this._system = system;
  86462. system.lensFlares.push(this);
  86463. }
  86464. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  86465. return new LensFlare(size, position, color, imgUrl, system);
  86466. };
  86467. LensFlare.prototype.dispose = function () {
  86468. if (this.texture) {
  86469. this.texture.dispose();
  86470. }
  86471. // Remove from scene
  86472. var index = this._system.lensFlares.indexOf(this);
  86473. this._system.lensFlares.splice(index, 1);
  86474. };
  86475. ;
  86476. return LensFlare;
  86477. }());
  86478. BABYLON.LensFlare = LensFlare;
  86479. })(BABYLON || (BABYLON = {}));
  86480. //# sourceMappingURL=babylon.lensFlare.js.map
  86481. var BABYLON;
  86482. (function (BABYLON) {
  86483. // Adds the parser to the scene parsers.
  86484. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  86485. // Lens flares
  86486. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  86487. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  86488. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  86489. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  86490. container.lensFlareSystems.push(lf);
  86491. }
  86492. }
  86493. });
  86494. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  86495. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  86496. if (this.lensFlareSystems[index].name === name) {
  86497. return this.lensFlareSystems[index];
  86498. }
  86499. }
  86500. return null;
  86501. };
  86502. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  86503. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  86504. if (this.lensFlareSystems[index].id === id) {
  86505. return this.lensFlareSystems[index];
  86506. }
  86507. }
  86508. return null;
  86509. };
  86510. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  86511. var index = this.lensFlareSystems.indexOf(toRemove);
  86512. if (index !== -1) {
  86513. this.lensFlareSystems.splice(index, 1);
  86514. }
  86515. return index;
  86516. };
  86517. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  86518. this.lensFlareSystems.push(newLensFlareSystem);
  86519. };
  86520. /**
  86521. * Defines the lens flare scene component responsible to manage any lens flares
  86522. * in a given scene.
  86523. */
  86524. var LensFlareSystemSceneComponent = /** @class */ (function () {
  86525. /**
  86526. * Creates a new instance of the component for the given scene
  86527. * @param scene Defines the scene to register the component in
  86528. */
  86529. function LensFlareSystemSceneComponent(scene) {
  86530. /**
  86531. * The component name helpfull to identify the component in the list of scene components.
  86532. */
  86533. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  86534. this.scene = scene;
  86535. scene.lensFlareSystems = new Array();
  86536. }
  86537. /**
  86538. * Registers the component in a given scene
  86539. */
  86540. LensFlareSystemSceneComponent.prototype.register = function () {
  86541. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  86542. };
  86543. /**
  86544. * Rebuilds the elements related to this component in case of
  86545. * context lost for instance.
  86546. */
  86547. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  86548. // Nothing to do for lens flare
  86549. };
  86550. /**
  86551. * Adds all the element from the container to the scene
  86552. * @param container the container holding the elements
  86553. */
  86554. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  86555. var _this = this;
  86556. if (!container.lensFlareSystems) {
  86557. return;
  86558. }
  86559. container.lensFlareSystems.forEach(function (o) {
  86560. _this.scene.addLensFlareSystem(o);
  86561. });
  86562. };
  86563. /**
  86564. * Removes all the elements in the container from the scene
  86565. * @param container contains the elements to remove
  86566. */
  86567. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  86568. var _this = this;
  86569. if (!container.lensFlareSystems) {
  86570. return;
  86571. }
  86572. container.lensFlareSystems.forEach(function (o) {
  86573. _this.scene.removeLensFlareSystem(o);
  86574. });
  86575. };
  86576. /**
  86577. * Serializes the component data to the specified json object
  86578. * @param serializationObject The object to serialize to
  86579. */
  86580. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  86581. // Lens flares
  86582. serializationObject.lensFlareSystems = [];
  86583. var lensFlareSystems = this.scene.lensFlareSystems;
  86584. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  86585. var lensFlareSystem = lensFlareSystems_1[_i];
  86586. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  86587. }
  86588. };
  86589. /**
  86590. * Disposes the component and the associated ressources.
  86591. */
  86592. LensFlareSystemSceneComponent.prototype.dispose = function () {
  86593. var lensFlareSystems = this.scene.lensFlareSystems;
  86594. while (lensFlareSystems.length) {
  86595. lensFlareSystems[0].dispose();
  86596. }
  86597. };
  86598. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  86599. // Lens flares
  86600. if (this.scene.lensFlaresEnabled) {
  86601. var lensFlareSystems = this.scene.lensFlareSystems;
  86602. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  86603. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  86604. var lensFlareSystem = lensFlareSystems_2[_i];
  86605. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  86606. lensFlareSystem.render();
  86607. }
  86608. }
  86609. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  86610. }
  86611. };
  86612. return LensFlareSystemSceneComponent;
  86613. }());
  86614. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  86615. })(BABYLON || (BABYLON = {}));
  86616. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  86617. var BABYLON;
  86618. (function (BABYLON) {
  86619. var LensFlareSystem = /** @class */ (function () {
  86620. function LensFlareSystem(name, emitter, scene) {
  86621. this.name = name;
  86622. this.lensFlares = new Array();
  86623. this.borderLimit = 300;
  86624. this.viewportBorder = 0;
  86625. this.layerMask = 0x0FFFFFFF;
  86626. this._vertexBuffers = {};
  86627. this._isEnabled = true;
  86628. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  86629. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  86630. if (!component) {
  86631. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  86632. scene._addComponent(component);
  86633. }
  86634. this._emitter = emitter;
  86635. this.id = name;
  86636. scene.lensFlareSystems.push(this);
  86637. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  86638. var engine = scene.getEngine();
  86639. // VBO
  86640. var vertices = [];
  86641. vertices.push(1, 1);
  86642. vertices.push(-1, 1);
  86643. vertices.push(-1, -1);
  86644. vertices.push(1, -1);
  86645. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  86646. // Indices
  86647. var indices = [];
  86648. indices.push(0);
  86649. indices.push(1);
  86650. indices.push(2);
  86651. indices.push(0);
  86652. indices.push(2);
  86653. indices.push(3);
  86654. this._indexBuffer = engine.createIndexBuffer(indices);
  86655. // Effects
  86656. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  86657. }
  86658. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  86659. get: function () {
  86660. return this._isEnabled;
  86661. },
  86662. set: function (value) {
  86663. this._isEnabled = value;
  86664. },
  86665. enumerable: true,
  86666. configurable: true
  86667. });
  86668. LensFlareSystem.prototype.getScene = function () {
  86669. return this._scene;
  86670. };
  86671. LensFlareSystem.prototype.getEmitter = function () {
  86672. return this._emitter;
  86673. };
  86674. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  86675. this._emitter = newEmitter;
  86676. };
  86677. LensFlareSystem.prototype.getEmitterPosition = function () {
  86678. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  86679. };
  86680. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  86681. var position = this.getEmitterPosition();
  86682. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  86683. this._positionX = position.x;
  86684. this._positionY = position.y;
  86685. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  86686. if (this.viewportBorder > 0) {
  86687. globalViewport.x -= this.viewportBorder;
  86688. globalViewport.y -= this.viewportBorder;
  86689. globalViewport.width += this.viewportBorder * 2;
  86690. globalViewport.height += this.viewportBorder * 2;
  86691. position.x += this.viewportBorder;
  86692. position.y += this.viewportBorder;
  86693. this._positionX += this.viewportBorder;
  86694. this._positionY += this.viewportBorder;
  86695. }
  86696. if (position.z > 0) {
  86697. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  86698. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  86699. return true;
  86700. }
  86701. return true;
  86702. }
  86703. return false;
  86704. };
  86705. /** @hidden */
  86706. LensFlareSystem.prototype._isVisible = function () {
  86707. if (!this._isEnabled || !this._scene.activeCamera) {
  86708. return false;
  86709. }
  86710. var emitterPosition = this.getEmitterPosition();
  86711. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  86712. var distance = direction.length();
  86713. direction.normalize();
  86714. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  86715. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  86716. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  86717. };
  86718. LensFlareSystem.prototype.render = function () {
  86719. if (!this._effect.isReady() || !this._scene.activeCamera)
  86720. return false;
  86721. var engine = this._scene.getEngine();
  86722. var viewport = this._scene.activeCamera.viewport;
  86723. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  86724. // Position
  86725. if (!this.computeEffectivePosition(globalViewport)) {
  86726. return false;
  86727. }
  86728. // Visibility
  86729. if (!this._isVisible()) {
  86730. return false;
  86731. }
  86732. // Intensity
  86733. var awayX;
  86734. var awayY;
  86735. if (this._positionX < this.borderLimit + globalViewport.x) {
  86736. awayX = this.borderLimit + globalViewport.x - this._positionX;
  86737. }
  86738. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  86739. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  86740. }
  86741. else {
  86742. awayX = 0;
  86743. }
  86744. if (this._positionY < this.borderLimit + globalViewport.y) {
  86745. awayY = this.borderLimit + globalViewport.y - this._positionY;
  86746. }
  86747. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  86748. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  86749. }
  86750. else {
  86751. awayY = 0;
  86752. }
  86753. var away = (awayX > awayY) ? awayX : awayY;
  86754. away -= this.viewportBorder;
  86755. if (away > this.borderLimit) {
  86756. away = this.borderLimit;
  86757. }
  86758. var intensity = 1.0 - (away / this.borderLimit);
  86759. if (intensity < 0) {
  86760. return false;
  86761. }
  86762. if (intensity > 1.0) {
  86763. intensity = 1.0;
  86764. }
  86765. if (this.viewportBorder > 0) {
  86766. globalViewport.x += this.viewportBorder;
  86767. globalViewport.y += this.viewportBorder;
  86768. globalViewport.width -= this.viewportBorder * 2;
  86769. globalViewport.height -= this.viewportBorder * 2;
  86770. this._positionX -= this.viewportBorder;
  86771. this._positionY -= this.viewportBorder;
  86772. }
  86773. // Position
  86774. var centerX = globalViewport.x + globalViewport.width / 2;
  86775. var centerY = globalViewport.y + globalViewport.height / 2;
  86776. var distX = centerX - this._positionX;
  86777. var distY = centerY - this._positionY;
  86778. // Effects
  86779. engine.enableEffect(this._effect);
  86780. engine.setState(false);
  86781. engine.setDepthBuffer(false);
  86782. // VBOs
  86783. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  86784. // Flares
  86785. for (var index = 0; index < this.lensFlares.length; index++) {
  86786. var flare = this.lensFlares[index];
  86787. engine.setAlphaMode(flare.alphaMode);
  86788. var x = centerX - (distX * flare.position);
  86789. var y = centerY - (distY * flare.position);
  86790. var cw = flare.size;
  86791. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  86792. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  86793. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  86794. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  86795. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  86796. // Texture
  86797. this._effect.setTexture("textureSampler", flare.texture);
  86798. // Color
  86799. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  86800. // Draw order
  86801. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86802. }
  86803. engine.setDepthBuffer(true);
  86804. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  86805. return true;
  86806. };
  86807. LensFlareSystem.prototype.dispose = function () {
  86808. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86809. if (vertexBuffer) {
  86810. vertexBuffer.dispose();
  86811. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  86812. }
  86813. if (this._indexBuffer) {
  86814. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  86815. this._indexBuffer = null;
  86816. }
  86817. while (this.lensFlares.length) {
  86818. this.lensFlares[0].dispose();
  86819. }
  86820. // Remove from scene
  86821. var index = this._scene.lensFlareSystems.indexOf(this);
  86822. this._scene.lensFlareSystems.splice(index, 1);
  86823. };
  86824. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  86825. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  86826. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  86827. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  86828. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  86829. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  86830. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  86831. var parsedFlare = parsedLensFlareSystem.flares[index];
  86832. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  86833. }
  86834. return lensFlareSystem;
  86835. };
  86836. LensFlareSystem.prototype.serialize = function () {
  86837. var serializationObject = {};
  86838. serializationObject.id = this.id;
  86839. serializationObject.name = this.name;
  86840. serializationObject.emitterId = this.getEmitter().id;
  86841. serializationObject.borderLimit = this.borderLimit;
  86842. serializationObject.flares = [];
  86843. for (var index = 0; index < this.lensFlares.length; index++) {
  86844. var flare = this.lensFlares[index];
  86845. serializationObject.flares.push({
  86846. size: flare.size,
  86847. position: flare.position,
  86848. color: flare.color.asArray(),
  86849. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  86850. });
  86851. }
  86852. return serializationObject;
  86853. };
  86854. return LensFlareSystem;
  86855. }());
  86856. BABYLON.LensFlareSystem = LensFlareSystem;
  86857. })(BABYLON || (BABYLON = {}));
  86858. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  86859. var BABYLON;
  86860. (function (BABYLON) {
  86861. /**
  86862. * This is a holder class for the physics joint created by the physics plugin.
  86863. * It holds a set of functions to control the underlying joint.
  86864. */
  86865. var PhysicsJoint = /** @class */ (function () {
  86866. function PhysicsJoint(type, jointData) {
  86867. this.type = type;
  86868. this.jointData = jointData;
  86869. jointData.nativeParams = jointData.nativeParams || {};
  86870. }
  86871. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  86872. get: function () {
  86873. return this._physicsJoint;
  86874. },
  86875. set: function (newJoint) {
  86876. if (this._physicsJoint) {
  86877. //remove from the wolrd
  86878. }
  86879. this._physicsJoint = newJoint;
  86880. },
  86881. enumerable: true,
  86882. configurable: true
  86883. });
  86884. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  86885. set: function (physicsPlugin) {
  86886. this._physicsPlugin = physicsPlugin;
  86887. },
  86888. enumerable: true,
  86889. configurable: true
  86890. });
  86891. /**
  86892. * Execute a function that is physics-plugin specific.
  86893. * @param {Function} func the function that will be executed.
  86894. * It accepts two parameters: the physics world and the physics joint.
  86895. */
  86896. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  86897. func(this._physicsPlugin.world, this._physicsJoint);
  86898. };
  86899. //TODO check if the native joints are the same
  86900. //Joint Types
  86901. PhysicsJoint.DistanceJoint = 0;
  86902. PhysicsJoint.HingeJoint = 1;
  86903. PhysicsJoint.BallAndSocketJoint = 2;
  86904. PhysicsJoint.WheelJoint = 3;
  86905. PhysicsJoint.SliderJoint = 4;
  86906. //OIMO
  86907. PhysicsJoint.PrismaticJoint = 5;
  86908. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  86909. PhysicsJoint.UniversalJoint = 6;
  86910. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  86911. //Cannon
  86912. //Similar to a Ball-Joint. Different in params
  86913. PhysicsJoint.PointToPointJoint = 8;
  86914. //Cannon only at the moment
  86915. PhysicsJoint.SpringJoint = 9;
  86916. PhysicsJoint.LockJoint = 10;
  86917. return PhysicsJoint;
  86918. }());
  86919. BABYLON.PhysicsJoint = PhysicsJoint;
  86920. /**
  86921. * A class representing a physics distance joint.
  86922. */
  86923. var DistanceJoint = /** @class */ (function (_super) {
  86924. __extends(DistanceJoint, _super);
  86925. function DistanceJoint(jointData) {
  86926. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  86927. }
  86928. /**
  86929. * Update the predefined distance.
  86930. */
  86931. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  86932. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  86933. };
  86934. return DistanceJoint;
  86935. }(PhysicsJoint));
  86936. BABYLON.DistanceJoint = DistanceJoint;
  86937. var MotorEnabledJoint = /** @class */ (function (_super) {
  86938. __extends(MotorEnabledJoint, _super);
  86939. function MotorEnabledJoint(type, jointData) {
  86940. return _super.call(this, type, jointData) || this;
  86941. }
  86942. /**
  86943. * Set the motor values.
  86944. * Attention, this function is plugin specific. Engines won't react 100% the same.
  86945. * @param {number} force the force to apply
  86946. * @param {number} maxForce max force for this motor.
  86947. */
  86948. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  86949. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  86950. };
  86951. /**
  86952. * Set the motor's limits.
  86953. * Attention, this function is plugin specific. Engines won't react 100% the same.
  86954. */
  86955. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  86956. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  86957. };
  86958. return MotorEnabledJoint;
  86959. }(PhysicsJoint));
  86960. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  86961. /**
  86962. * This class represents a single hinge physics joint
  86963. */
  86964. var HingeJoint = /** @class */ (function (_super) {
  86965. __extends(HingeJoint, _super);
  86966. function HingeJoint(jointData) {
  86967. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  86968. }
  86969. /**
  86970. * Set the motor values.
  86971. * Attention, this function is plugin specific. Engines won't react 100% the same.
  86972. * @param {number} force the force to apply
  86973. * @param {number} maxForce max force for this motor.
  86974. */
  86975. HingeJoint.prototype.setMotor = function (force, maxForce) {
  86976. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  86977. };
  86978. /**
  86979. * Set the motor's limits.
  86980. * Attention, this function is plugin specific. Engines won't react 100% the same.
  86981. */
  86982. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  86983. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  86984. };
  86985. return HingeJoint;
  86986. }(MotorEnabledJoint));
  86987. BABYLON.HingeJoint = HingeJoint;
  86988. /**
  86989. * This class represents a dual hinge physics joint (same as wheel joint)
  86990. */
  86991. var Hinge2Joint = /** @class */ (function (_super) {
  86992. __extends(Hinge2Joint, _super);
  86993. function Hinge2Joint(jointData) {
  86994. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  86995. }
  86996. /**
  86997. * Set the motor values.
  86998. * Attention, this function is plugin specific. Engines won't react 100% the same.
  86999. * @param {number} force the force to apply
  87000. * @param {number} maxForce max force for this motor.
  87001. * @param {motorIndex} the motor's index, 0 or 1.
  87002. */
  87003. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  87004. if (motorIndex === void 0) { motorIndex = 0; }
  87005. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  87006. };
  87007. /**
  87008. * Set the motor limits.
  87009. * Attention, this function is plugin specific. Engines won't react 100% the same.
  87010. * @param {number} upperLimit the upper limit
  87011. * @param {number} lowerLimit lower limit
  87012. * @param {motorIndex} the motor's index, 0 or 1.
  87013. */
  87014. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  87015. if (motorIndex === void 0) { motorIndex = 0; }
  87016. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  87017. };
  87018. return Hinge2Joint;
  87019. }(MotorEnabledJoint));
  87020. BABYLON.Hinge2Joint = Hinge2Joint;
  87021. })(BABYLON || (BABYLON = {}));
  87022. //# sourceMappingURL=babylon.physicsJoint.js.map
  87023. var BABYLON;
  87024. (function (BABYLON) {
  87025. var PhysicsImpostor = /** @class */ (function () {
  87026. function PhysicsImpostor(object, type, _options, _scene) {
  87027. if (_options === void 0) { _options = { mass: 0 }; }
  87028. var _this = this;
  87029. this.object = object;
  87030. this.type = type;
  87031. this._options = _options;
  87032. this._scene = _scene;
  87033. this._bodyUpdateRequired = false;
  87034. this._onBeforePhysicsStepCallbacks = new Array();
  87035. this._onAfterPhysicsStepCallbacks = new Array();
  87036. this._onPhysicsCollideCallbacks = [];
  87037. this._deltaPosition = BABYLON.Vector3.Zero();
  87038. this._isDisposed = false;
  87039. //temp variables for parent rotation calculations
  87040. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  87041. this._tmpQuat = new BABYLON.Quaternion();
  87042. this._tmpQuat2 = new BABYLON.Quaternion();
  87043. /**
  87044. * this function is executed by the physics engine.
  87045. */
  87046. this.beforeStep = function () {
  87047. if (!_this._physicsEngine) {
  87048. return;
  87049. }
  87050. _this.object.translate(_this._deltaPosition, -1);
  87051. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  87052. _this.object.computeWorldMatrix(false);
  87053. if (_this.object.parent && _this.object.rotationQuaternion) {
  87054. _this.getParentsRotation();
  87055. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  87056. }
  87057. else {
  87058. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  87059. }
  87060. if (!_this._options.disableBidirectionalTransformation) {
  87061. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  87062. }
  87063. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  87064. func(_this);
  87065. });
  87066. };
  87067. /**
  87068. * this function is executed by the physics engine.
  87069. */
  87070. this.afterStep = function () {
  87071. if (!_this._physicsEngine) {
  87072. return;
  87073. }
  87074. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  87075. func(_this);
  87076. });
  87077. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  87078. // object has now its world rotation. needs to be converted to local.
  87079. if (_this.object.parent && _this.object.rotationQuaternion) {
  87080. _this.getParentsRotation();
  87081. _this._tmpQuat.conjugateInPlace();
  87082. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  87083. }
  87084. // take the position set and make it the absolute position of this object.
  87085. _this.object.setAbsolutePosition(_this.object.position);
  87086. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  87087. _this.object.translate(_this._deltaPosition, 1);
  87088. };
  87089. /**
  87090. * Legacy collision detection event support
  87091. */
  87092. this.onCollideEvent = null;
  87093. //event and body object due to cannon's event-based architecture.
  87094. this.onCollide = function (e) {
  87095. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  87096. return;
  87097. }
  87098. if (!_this._physicsEngine) {
  87099. return;
  87100. }
  87101. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  87102. if (otherImpostor) {
  87103. // Legacy collision detection event support
  87104. if (_this.onCollideEvent) {
  87105. _this.onCollideEvent(_this, otherImpostor);
  87106. }
  87107. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  87108. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  87109. }).forEach(function (obj) {
  87110. obj.callback(_this, otherImpostor);
  87111. });
  87112. }
  87113. };
  87114. //sanity check!
  87115. if (!this.object) {
  87116. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  87117. return;
  87118. }
  87119. //legacy support for old syntax.
  87120. if (!this._scene && object.getScene) {
  87121. this._scene = object.getScene();
  87122. }
  87123. if (!this._scene) {
  87124. return;
  87125. }
  87126. this._physicsEngine = this._scene.getPhysicsEngine();
  87127. if (!this._physicsEngine) {
  87128. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  87129. }
  87130. else {
  87131. //set the object's quaternion, if not set
  87132. if (!this.object.rotationQuaternion) {
  87133. if (this.object.rotation) {
  87134. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  87135. }
  87136. else {
  87137. this.object.rotationQuaternion = new BABYLON.Quaternion();
  87138. }
  87139. }
  87140. //default options params
  87141. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  87142. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  87143. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  87144. this._joints = [];
  87145. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  87146. if (!this.object.parent || this._options.ignoreParent) {
  87147. this._init();
  87148. }
  87149. else if (this.object.parent.physicsImpostor) {
  87150. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  87151. }
  87152. }
  87153. }
  87154. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  87155. get: function () {
  87156. return this._isDisposed;
  87157. },
  87158. enumerable: true,
  87159. configurable: true
  87160. });
  87161. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  87162. get: function () {
  87163. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  87164. },
  87165. set: function (value) {
  87166. this.setMass(value);
  87167. },
  87168. enumerable: true,
  87169. configurable: true
  87170. });
  87171. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  87172. get: function () {
  87173. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  87174. },
  87175. set: function (value) {
  87176. if (!this._physicsEngine) {
  87177. return;
  87178. }
  87179. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  87180. },
  87181. enumerable: true,
  87182. configurable: true
  87183. });
  87184. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  87185. get: function () {
  87186. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  87187. },
  87188. set: function (value) {
  87189. if (!this._physicsEngine) {
  87190. return;
  87191. }
  87192. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  87193. },
  87194. enumerable: true,
  87195. configurable: true
  87196. });
  87197. /**
  87198. * This function will completly initialize this impostor.
  87199. * It will create a new body - but only if this mesh has no parent.
  87200. * If it has, this impostor will not be used other than to define the impostor
  87201. * of the child mesh.
  87202. * @hidden
  87203. */
  87204. PhysicsImpostor.prototype._init = function () {
  87205. if (!this._physicsEngine) {
  87206. return;
  87207. }
  87208. this._physicsEngine.removeImpostor(this);
  87209. this.physicsBody = null;
  87210. this._parent = this._parent || this._getPhysicsParent();
  87211. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  87212. this._physicsEngine.addImpostor(this);
  87213. }
  87214. };
  87215. PhysicsImpostor.prototype._getPhysicsParent = function () {
  87216. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  87217. var parentMesh = this.object.parent;
  87218. return parentMesh.physicsImpostor;
  87219. }
  87220. return null;
  87221. };
  87222. /**
  87223. * Should a new body be generated.
  87224. */
  87225. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  87226. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  87227. };
  87228. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  87229. this.forceUpdate();
  87230. };
  87231. /**
  87232. * Force a regeneration of this or the parent's impostor's body.
  87233. * Use under cautious - This will remove all joints already implemented.
  87234. */
  87235. PhysicsImpostor.prototype.forceUpdate = function () {
  87236. this._init();
  87237. if (this.parent && !this._options.ignoreParent) {
  87238. this.parent.forceUpdate();
  87239. }
  87240. };
  87241. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  87242. /*public get mesh(): AbstractMesh {
  87243. return this._mesh;
  87244. }*/
  87245. /**
  87246. * Gets the body that holds this impostor. Either its own, or its parent.
  87247. */
  87248. get: function () {
  87249. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  87250. },
  87251. /**
  87252. * Set the physics body. Used mainly by the physics engine/plugin
  87253. */
  87254. set: function (physicsBody) {
  87255. if (this._physicsBody && this._physicsEngine) {
  87256. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  87257. }
  87258. this._physicsBody = physicsBody;
  87259. this.resetUpdateFlags();
  87260. },
  87261. enumerable: true,
  87262. configurable: true
  87263. });
  87264. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  87265. get: function () {
  87266. return !this._options.ignoreParent && this._parent ? this._parent : null;
  87267. },
  87268. set: function (value) {
  87269. this._parent = value;
  87270. },
  87271. enumerable: true,
  87272. configurable: true
  87273. });
  87274. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  87275. this._bodyUpdateRequired = false;
  87276. };
  87277. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  87278. if (this.object.getBoundingInfo) {
  87279. var q = this.object.rotationQuaternion;
  87280. //reset rotation
  87281. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  87282. //calculate the world matrix with no rotation
  87283. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  87284. var boundingInfo = this.object.getBoundingInfo();
  87285. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  87286. //bring back the rotation
  87287. this.object.rotationQuaternion = q;
  87288. //calculate the world matrix with the new rotation
  87289. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  87290. return size;
  87291. }
  87292. else {
  87293. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  87294. }
  87295. };
  87296. PhysicsImpostor.prototype.getObjectCenter = function () {
  87297. if (this.object.getBoundingInfo) {
  87298. var boundingInfo = this.object.getBoundingInfo();
  87299. return boundingInfo.boundingBox.centerWorld;
  87300. }
  87301. else {
  87302. return this.object.position;
  87303. }
  87304. };
  87305. /**
  87306. * Get a specific parametes from the options parameter.
  87307. */
  87308. PhysicsImpostor.prototype.getParam = function (paramName) {
  87309. return this._options[paramName];
  87310. };
  87311. /**
  87312. * Sets a specific parameter in the options given to the physics plugin
  87313. */
  87314. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  87315. this._options[paramName] = value;
  87316. this._bodyUpdateRequired = true;
  87317. };
  87318. /**
  87319. * Specifically change the body's mass option. Won't recreate the physics body object
  87320. */
  87321. PhysicsImpostor.prototype.setMass = function (mass) {
  87322. if (this.getParam("mass") !== mass) {
  87323. this.setParam("mass", mass);
  87324. }
  87325. if (this._physicsEngine) {
  87326. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  87327. }
  87328. };
  87329. PhysicsImpostor.prototype.getLinearVelocity = function () {
  87330. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  87331. };
  87332. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  87333. if (this._physicsEngine) {
  87334. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  87335. }
  87336. };
  87337. PhysicsImpostor.prototype.getAngularVelocity = function () {
  87338. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  87339. };
  87340. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  87341. if (this._physicsEngine) {
  87342. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  87343. }
  87344. };
  87345. /**
  87346. * Execute a function with the physics plugin native code.
  87347. * Provide a function the will have two variables - the world object and the physics body object.
  87348. */
  87349. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  87350. if (this._physicsEngine) {
  87351. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  87352. }
  87353. };
  87354. /**
  87355. * Register a function that will be executed before the physics world is stepping forward.
  87356. */
  87357. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  87358. this._onBeforePhysicsStepCallbacks.push(func);
  87359. };
  87360. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  87361. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  87362. if (index > -1) {
  87363. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  87364. }
  87365. else {
  87366. BABYLON.Tools.Warn("Function to remove was not found");
  87367. }
  87368. };
  87369. /**
  87370. * Register a function that will be executed after the physics step
  87371. */
  87372. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  87373. this._onAfterPhysicsStepCallbacks.push(func);
  87374. };
  87375. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  87376. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  87377. if (index > -1) {
  87378. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  87379. }
  87380. else {
  87381. BABYLON.Tools.Warn("Function to remove was not found");
  87382. }
  87383. };
  87384. /**
  87385. * register a function that will be executed when this impostor collides against a different body.
  87386. */
  87387. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  87388. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  87389. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  87390. };
  87391. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  87392. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  87393. var index = -1;
  87394. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  87395. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  87396. // chcek the arrays match
  87397. var sameList = cbDef.otherImpostors.every(function (impostor) {
  87398. return collidedAgainstList.indexOf(impostor) > -1;
  87399. });
  87400. if (sameList) {
  87401. index = idx;
  87402. }
  87403. return sameList;
  87404. }
  87405. return false;
  87406. });
  87407. if (found) {
  87408. this._onPhysicsCollideCallbacks.splice(index, 1);
  87409. }
  87410. else {
  87411. BABYLON.Tools.Warn("Function to remove was not found");
  87412. }
  87413. };
  87414. PhysicsImpostor.prototype.getParentsRotation = function () {
  87415. var parent = this.object.parent;
  87416. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  87417. while (parent) {
  87418. if (parent.rotationQuaternion) {
  87419. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  87420. }
  87421. else {
  87422. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  87423. }
  87424. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  87425. parent = parent.parent;
  87426. }
  87427. return this._tmpQuat;
  87428. };
  87429. /**
  87430. * Apply a force
  87431. */
  87432. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  87433. if (this._physicsEngine) {
  87434. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  87435. }
  87436. return this;
  87437. };
  87438. /**
  87439. * Apply an impulse
  87440. */
  87441. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  87442. if (this._physicsEngine) {
  87443. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  87444. }
  87445. return this;
  87446. };
  87447. /**
  87448. * A help function to create a joint.
  87449. */
  87450. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  87451. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  87452. this.addJoint(otherImpostor, joint);
  87453. return this;
  87454. };
  87455. /**
  87456. * Add a joint to this impostor with a different impostor.
  87457. */
  87458. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  87459. this._joints.push({
  87460. otherImpostor: otherImpostor,
  87461. joint: joint
  87462. });
  87463. if (this._physicsEngine) {
  87464. this._physicsEngine.addJoint(this, otherImpostor, joint);
  87465. }
  87466. return this;
  87467. };
  87468. /**
  87469. * Will keep this body still, in a sleep mode.
  87470. */
  87471. PhysicsImpostor.prototype.sleep = function () {
  87472. if (this._physicsEngine) {
  87473. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  87474. }
  87475. return this;
  87476. };
  87477. /**
  87478. * Wake the body up.
  87479. */
  87480. PhysicsImpostor.prototype.wakeUp = function () {
  87481. if (this._physicsEngine) {
  87482. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  87483. }
  87484. return this;
  87485. };
  87486. PhysicsImpostor.prototype.clone = function (newObject) {
  87487. if (!newObject)
  87488. return null;
  87489. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  87490. };
  87491. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  87492. var _this = this;
  87493. //no dispose if no physics engine is available.
  87494. if (!this._physicsEngine) {
  87495. return;
  87496. }
  87497. this._joints.forEach(function (j) {
  87498. if (_this._physicsEngine) {
  87499. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  87500. }
  87501. });
  87502. //dispose the physics body
  87503. this._physicsEngine.removeImpostor(this);
  87504. if (this.parent) {
  87505. this.parent.forceUpdate();
  87506. }
  87507. else {
  87508. /*this._object.getChildMeshes().forEach(function(mesh) {
  87509. if (mesh.physicsImpostor) {
  87510. if (disposeChildren) {
  87511. mesh.physicsImpostor.dispose();
  87512. mesh.physicsImpostor = null;
  87513. }
  87514. }
  87515. })*/
  87516. }
  87517. this._isDisposed = true;
  87518. };
  87519. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  87520. this._deltaPosition.copyFrom(position);
  87521. };
  87522. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  87523. if (!this._deltaRotation) {
  87524. this._deltaRotation = new BABYLON.Quaternion();
  87525. }
  87526. this._deltaRotation.copyFrom(rotation);
  87527. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  87528. };
  87529. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  87530. if (this._physicsEngine) {
  87531. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  87532. }
  87533. return this;
  87534. };
  87535. PhysicsImpostor.prototype.getRadius = function () {
  87536. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  87537. };
  87538. /**
  87539. * Sync a bone with this impostor
  87540. * @param bone The bone to sync to the impostor.
  87541. * @param boneMesh The mesh that the bone is influencing.
  87542. * @param jointPivot The pivot of the joint / bone in local space.
  87543. * @param distToJoint Optional distance from the impostor to the joint.
  87544. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  87545. */
  87546. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  87547. var tempVec = PhysicsImpostor._tmpVecs[0];
  87548. var mesh = this.object;
  87549. if (mesh.rotationQuaternion) {
  87550. if (adjustRotation) {
  87551. var tempQuat = PhysicsImpostor._tmpQuat;
  87552. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  87553. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  87554. }
  87555. else {
  87556. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  87557. }
  87558. }
  87559. tempVec.x = 0;
  87560. tempVec.y = 0;
  87561. tempVec.z = 0;
  87562. if (jointPivot) {
  87563. tempVec.x = jointPivot.x;
  87564. tempVec.y = jointPivot.y;
  87565. tempVec.z = jointPivot.z;
  87566. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  87567. if (distToJoint === undefined || distToJoint === null) {
  87568. distToJoint = jointPivot.length();
  87569. }
  87570. tempVec.x *= distToJoint;
  87571. tempVec.y *= distToJoint;
  87572. tempVec.z *= distToJoint;
  87573. }
  87574. if (bone.getParent()) {
  87575. tempVec.addInPlace(mesh.getAbsolutePosition());
  87576. bone.setAbsolutePosition(tempVec, boneMesh);
  87577. }
  87578. else {
  87579. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  87580. boneMesh.position.x -= tempVec.x;
  87581. boneMesh.position.y -= tempVec.y;
  87582. boneMesh.position.z -= tempVec.z;
  87583. }
  87584. };
  87585. /**
  87586. * Sync impostor to a bone
  87587. * @param bone The bone that the impostor will be synced to.
  87588. * @param boneMesh The mesh that the bone is influencing.
  87589. * @param jointPivot The pivot of the joint / bone in local space.
  87590. * @param distToJoint Optional distance from the impostor to the joint.
  87591. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  87592. * @param boneAxis Optional vector3 axis the bone is aligned with
  87593. */
  87594. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  87595. var mesh = this.object;
  87596. if (mesh.rotationQuaternion) {
  87597. if (adjustRotation) {
  87598. var tempQuat = PhysicsImpostor._tmpQuat;
  87599. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  87600. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  87601. }
  87602. else {
  87603. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  87604. }
  87605. }
  87606. var pos = PhysicsImpostor._tmpVecs[0];
  87607. var boneDir = PhysicsImpostor._tmpVecs[1];
  87608. if (!boneAxis) {
  87609. boneAxis = PhysicsImpostor._tmpVecs[2];
  87610. boneAxis.x = 0;
  87611. boneAxis.y = 1;
  87612. boneAxis.z = 0;
  87613. }
  87614. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  87615. bone.getAbsolutePositionToRef(boneMesh, pos);
  87616. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  87617. distToJoint = jointPivot.length();
  87618. }
  87619. if (distToJoint !== undefined && distToJoint !== null) {
  87620. pos.x += boneDir.x * distToJoint;
  87621. pos.y += boneDir.y * distToJoint;
  87622. pos.z += boneDir.z * distToJoint;
  87623. }
  87624. mesh.setAbsolutePosition(pos);
  87625. };
  87626. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  87627. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  87628. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87629. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  87630. //Impostor types
  87631. PhysicsImpostor.NoImpostor = 0;
  87632. PhysicsImpostor.SphereImpostor = 1;
  87633. PhysicsImpostor.BoxImpostor = 2;
  87634. PhysicsImpostor.PlaneImpostor = 3;
  87635. PhysicsImpostor.MeshImpostor = 4;
  87636. PhysicsImpostor.CylinderImpostor = 7;
  87637. PhysicsImpostor.ParticleImpostor = 8;
  87638. PhysicsImpostor.HeightmapImpostor = 9;
  87639. return PhysicsImpostor;
  87640. }());
  87641. BABYLON.PhysicsImpostor = PhysicsImpostor;
  87642. })(BABYLON || (BABYLON = {}));
  87643. //# sourceMappingURL=babylon.physicsImpostor.js.map
  87644. var BABYLON;
  87645. (function (BABYLON) {
  87646. var PhysicsEngine = /** @class */ (function () {
  87647. function PhysicsEngine(gravity, _physicsPlugin) {
  87648. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  87649. this._physicsPlugin = _physicsPlugin;
  87650. //new methods and parameters
  87651. this._impostors = [];
  87652. this._joints = [];
  87653. if (!this._physicsPlugin.isSupported()) {
  87654. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  87655. + "Please make sure it is included.");
  87656. }
  87657. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  87658. this.setGravity(gravity);
  87659. this.setTimeStep();
  87660. }
  87661. PhysicsEngine.prototype.setGravity = function (gravity) {
  87662. this.gravity = gravity;
  87663. this._physicsPlugin.setGravity(this.gravity);
  87664. };
  87665. /**
  87666. * Set the time step of the physics engine.
  87667. * default is 1/60.
  87668. * To slow it down, enter 1/600 for example.
  87669. * To speed it up, 1/30
  87670. * @param {number} newTimeStep the new timestep to apply to this world.
  87671. */
  87672. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  87673. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  87674. this._physicsPlugin.setTimeStep(newTimeStep);
  87675. };
  87676. /**
  87677. * Get the time step of the physics engine.
  87678. */
  87679. PhysicsEngine.prototype.getTimeStep = function () {
  87680. return this._physicsPlugin.getTimeStep();
  87681. };
  87682. PhysicsEngine.prototype.dispose = function () {
  87683. this._impostors.forEach(function (impostor) {
  87684. impostor.dispose();
  87685. });
  87686. this._physicsPlugin.dispose();
  87687. };
  87688. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  87689. return this._physicsPlugin.name;
  87690. };
  87691. /**
  87692. * Adding a new impostor for the impostor tracking.
  87693. * This will be done by the impostor itself.
  87694. * @param {PhysicsImpostor} impostor the impostor to add
  87695. */
  87696. PhysicsEngine.prototype.addImpostor = function (impostor) {
  87697. impostor.uniqueId = this._impostors.push(impostor);
  87698. //if no parent, generate the body
  87699. if (!impostor.parent) {
  87700. this._physicsPlugin.generatePhysicsBody(impostor);
  87701. }
  87702. };
  87703. /**
  87704. * Remove an impostor from the engine.
  87705. * This impostor and its mesh will not longer be updated by the physics engine.
  87706. * @param {PhysicsImpostor} impostor the impostor to remove
  87707. */
  87708. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  87709. var index = this._impostors.indexOf(impostor);
  87710. if (index > -1) {
  87711. var removed = this._impostors.splice(index, 1);
  87712. //Is it needed?
  87713. if (removed.length) {
  87714. //this will also remove it from the world.
  87715. removed[0].physicsBody = null;
  87716. }
  87717. }
  87718. };
  87719. /**
  87720. * Add a joint to the physics engine
  87721. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  87722. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  87723. * @param {PhysicsJoint} the joint that will connect both impostors.
  87724. */
  87725. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  87726. var impostorJoint = {
  87727. mainImpostor: mainImpostor,
  87728. connectedImpostor: connectedImpostor,
  87729. joint: joint
  87730. };
  87731. joint.physicsPlugin = this._physicsPlugin;
  87732. this._joints.push(impostorJoint);
  87733. this._physicsPlugin.generateJoint(impostorJoint);
  87734. };
  87735. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  87736. var matchingJoints = this._joints.filter(function (impostorJoint) {
  87737. return (impostorJoint.connectedImpostor === connectedImpostor
  87738. && impostorJoint.joint === joint
  87739. && impostorJoint.mainImpostor === mainImpostor);
  87740. });
  87741. if (matchingJoints.length) {
  87742. this._physicsPlugin.removeJoint(matchingJoints[0]);
  87743. //TODO remove it from the list as well
  87744. }
  87745. };
  87746. /**
  87747. * Called by the scene. no need to call it.
  87748. * @hidden
  87749. */
  87750. PhysicsEngine.prototype._step = function (delta) {
  87751. var _this = this;
  87752. //check if any mesh has no body / requires an update
  87753. this._impostors.forEach(function (impostor) {
  87754. if (impostor.isBodyInitRequired()) {
  87755. _this._physicsPlugin.generatePhysicsBody(impostor);
  87756. }
  87757. });
  87758. if (delta > 0.1) {
  87759. delta = 0.1;
  87760. }
  87761. else if (delta <= 0) {
  87762. delta = 1.0 / 60.0;
  87763. }
  87764. this._physicsPlugin.executeStep(delta, this._impostors);
  87765. };
  87766. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  87767. return this._physicsPlugin;
  87768. };
  87769. PhysicsEngine.prototype.getImpostors = function () {
  87770. return this._impostors;
  87771. };
  87772. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  87773. for (var i = 0; i < this._impostors.length; ++i) {
  87774. if (this._impostors[i].object === object) {
  87775. return this._impostors[i];
  87776. }
  87777. }
  87778. return null;
  87779. };
  87780. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  87781. for (var i = 0; i < this._impostors.length; ++i) {
  87782. if (this._impostors[i].physicsBody === body) {
  87783. return this._impostors[i];
  87784. }
  87785. }
  87786. return null;
  87787. };
  87788. // Statics
  87789. PhysicsEngine.Epsilon = 0.001;
  87790. return PhysicsEngine;
  87791. }());
  87792. BABYLON.PhysicsEngine = PhysicsEngine;
  87793. })(BABYLON || (BABYLON = {}));
  87794. //# sourceMappingURL=babylon.physicsEngine.js.map
  87795. var BABYLON;
  87796. (function (BABYLON) {
  87797. var PhysicsHelper = /** @class */ (function () {
  87798. function PhysicsHelper(scene) {
  87799. this._scene = scene;
  87800. this._physicsEngine = this._scene.getPhysicsEngine();
  87801. if (!this._physicsEngine) {
  87802. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  87803. }
  87804. }
  87805. /**
  87806. * @param {Vector3} origin the origin of the explosion
  87807. * @param {number} radius the explosion radius
  87808. * @param {number} strength the explosion strength
  87809. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  87810. */
  87811. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  87812. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  87813. if (!this._physicsEngine) {
  87814. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  87815. return null;
  87816. }
  87817. var impostors = this._physicsEngine.getImpostors();
  87818. if (impostors.length === 0) {
  87819. return null;
  87820. }
  87821. var event = new PhysicsRadialExplosionEvent(this._scene);
  87822. impostors.forEach(function (impostor) {
  87823. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  87824. if (!impostorForceAndContactPoint) {
  87825. return;
  87826. }
  87827. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  87828. });
  87829. event.dispose(false);
  87830. return event;
  87831. };
  87832. /**
  87833. * @param {Vector3} origin the origin of the explosion
  87834. * @param {number} radius the explosion radius
  87835. * @param {number} strength the explosion strength
  87836. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  87837. */
  87838. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  87839. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  87840. if (!this._physicsEngine) {
  87841. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  87842. return null;
  87843. }
  87844. var impostors = this._physicsEngine.getImpostors();
  87845. if (impostors.length === 0) {
  87846. return null;
  87847. }
  87848. var event = new PhysicsRadialExplosionEvent(this._scene);
  87849. impostors.forEach(function (impostor) {
  87850. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  87851. if (!impostorForceAndContactPoint) {
  87852. return;
  87853. }
  87854. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  87855. });
  87856. event.dispose(false);
  87857. return event;
  87858. };
  87859. /**
  87860. * @param {Vector3} origin the origin of the explosion
  87861. * @param {number} radius the explosion radius
  87862. * @param {number} strength the explosion strength
  87863. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  87864. */
  87865. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  87866. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  87867. if (!this._physicsEngine) {
  87868. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  87869. return null;
  87870. }
  87871. var impostors = this._physicsEngine.getImpostors();
  87872. if (impostors.length === 0) {
  87873. return null;
  87874. }
  87875. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  87876. event.dispose(false);
  87877. return event;
  87878. };
  87879. /**
  87880. * @param {Vector3} origin the origin of the updraft
  87881. * @param {number} radius the radius of the updraft
  87882. * @param {number} strength the strength of the updraft
  87883. * @param {number} height the height of the updraft
  87884. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  87885. */
  87886. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  87887. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  87888. if (!this._physicsEngine) {
  87889. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  87890. return null;
  87891. }
  87892. if (this._physicsEngine.getImpostors().length === 0) {
  87893. return null;
  87894. }
  87895. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  87896. event.dispose(false);
  87897. return event;
  87898. };
  87899. /**
  87900. * @param {Vector3} origin the of the vortex
  87901. * @param {number} radius the radius of the vortex
  87902. * @param {number} strength the strength of the vortex
  87903. * @param {number} height the height of the vortex
  87904. */
  87905. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  87906. if (!this._physicsEngine) {
  87907. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  87908. return null;
  87909. }
  87910. if (this._physicsEngine.getImpostors().length === 0) {
  87911. return null;
  87912. }
  87913. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  87914. event.dispose(false);
  87915. return event;
  87916. };
  87917. return PhysicsHelper;
  87918. }());
  87919. BABYLON.PhysicsHelper = PhysicsHelper;
  87920. /***** Radial explosion *****/
  87921. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  87922. function PhysicsRadialExplosionEvent(scene) {
  87923. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  87924. this._rays = [];
  87925. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  87926. this._scene = scene;
  87927. }
  87928. /**
  87929. * Returns the data related to the radial explosion event (sphere & rays).
  87930. * @returns {PhysicsRadialExplosionEventData}
  87931. */
  87932. PhysicsRadialExplosionEvent.prototype.getData = function () {
  87933. this._dataFetched = true;
  87934. return {
  87935. sphere: this._sphere,
  87936. rays: this._rays,
  87937. };
  87938. };
  87939. /**
  87940. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  87941. * @param impostor
  87942. * @param {Vector3} origin the origin of the explosion
  87943. * @param {number} radius the explosion radius
  87944. * @param {number} strength the explosion strength
  87945. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  87946. * @returns {Nullable<PhysicsForceAndContactPoint>}
  87947. */
  87948. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  87949. if (impostor.mass === 0) {
  87950. return null;
  87951. }
  87952. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  87953. return null;
  87954. }
  87955. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  87956. return null;
  87957. }
  87958. var impostorObjectCenter = impostor.getObjectCenter();
  87959. var direction = impostorObjectCenter.subtract(origin);
  87960. var ray = new BABYLON.Ray(origin, direction, radius);
  87961. this._rays.push(ray);
  87962. var hit = ray.intersectsMesh(impostor.object);
  87963. var contactPoint = hit.pickedPoint;
  87964. if (!contactPoint) {
  87965. return null;
  87966. }
  87967. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  87968. if (distanceFromOrigin > radius) {
  87969. return null;
  87970. }
  87971. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  87972. ? strength
  87973. : strength * (1 - (distanceFromOrigin / radius));
  87974. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  87975. return { force: force, contactPoint: contactPoint };
  87976. };
  87977. /**
  87978. * Disposes the sphere.
  87979. * @param {bolean} force
  87980. */
  87981. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  87982. var _this = this;
  87983. if (force === void 0) { force = true; }
  87984. if (force) {
  87985. this._sphere.dispose();
  87986. }
  87987. else {
  87988. setTimeout(function () {
  87989. if (!_this._dataFetched) {
  87990. _this._sphere.dispose();
  87991. }
  87992. }, 0);
  87993. }
  87994. };
  87995. /*** Helpers ***/
  87996. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  87997. if (!this._sphere) {
  87998. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  87999. this._sphere.isVisible = false;
  88000. }
  88001. };
  88002. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  88003. var impostorObject = impostor.object;
  88004. this._prepareSphere();
  88005. this._sphere.position = origin;
  88006. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  88007. this._sphere._updateBoundingInfo();
  88008. this._sphere.computeWorldMatrix(true);
  88009. return this._sphere.intersectsMesh(impostorObject, true);
  88010. };
  88011. return PhysicsRadialExplosionEvent;
  88012. }());
  88013. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  88014. /***** Gravitational Field *****/
  88015. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  88016. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  88017. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  88018. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  88019. this._physicsHelper = physicsHelper;
  88020. this._scene = scene;
  88021. this._origin = origin;
  88022. this._radius = radius;
  88023. this._strength = strength;
  88024. this._falloff = falloff;
  88025. this._tickCallback = this._tick.bind(this);
  88026. }
  88027. /**
  88028. * Returns the data related to the gravitational field event (sphere).
  88029. * @returns {PhysicsGravitationalFieldEventData}
  88030. */
  88031. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  88032. this._dataFetched = true;
  88033. return {
  88034. sphere: this._sphere,
  88035. };
  88036. };
  88037. /**
  88038. * Enables the gravitational field.
  88039. */
  88040. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  88041. this._tickCallback.call(this);
  88042. this._scene.registerBeforeRender(this._tickCallback);
  88043. };
  88044. /**
  88045. * Disables the gravitational field.
  88046. */
  88047. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  88048. this._scene.unregisterBeforeRender(this._tickCallback);
  88049. };
  88050. /**
  88051. * Disposes the sphere.
  88052. * @param {bolean} force
  88053. */
  88054. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  88055. var _this = this;
  88056. if (force === void 0) { force = true; }
  88057. if (force) {
  88058. this._sphere.dispose();
  88059. }
  88060. else {
  88061. setTimeout(function () {
  88062. if (!_this._dataFetched) {
  88063. _this._sphere.dispose();
  88064. }
  88065. }, 0);
  88066. }
  88067. };
  88068. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  88069. // Since the params won't change, we fetch the event only once
  88070. if (this._sphere) {
  88071. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  88072. }
  88073. else {
  88074. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  88075. if (radialExplosionEvent) {
  88076. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  88077. }
  88078. }
  88079. };
  88080. return PhysicsGravitationalFieldEvent;
  88081. }());
  88082. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  88083. /***** Updraft *****/
  88084. var PhysicsUpdraftEvent = /** @class */ (function () {
  88085. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  88086. this._scene = _scene;
  88087. this._origin = _origin;
  88088. this._radius = _radius;
  88089. this._strength = _strength;
  88090. this._height = _height;
  88091. this._updraftMode = _updraftMode;
  88092. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  88093. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  88094. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  88095. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  88096. this._physicsEngine = this._scene.getPhysicsEngine();
  88097. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  88098. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  88099. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  88100. this._originDirection = this._origin.subtract(this._originTop).normalize();
  88101. }
  88102. this._tickCallback = this._tick.bind(this);
  88103. }
  88104. /**
  88105. * Returns the data related to the updraft event (cylinder).
  88106. * @returns {PhysicsUpdraftEventData}
  88107. */
  88108. PhysicsUpdraftEvent.prototype.getData = function () {
  88109. this._dataFetched = true;
  88110. return {
  88111. cylinder: this._cylinder,
  88112. };
  88113. };
  88114. /**
  88115. * Enables the updraft.
  88116. */
  88117. PhysicsUpdraftEvent.prototype.enable = function () {
  88118. this._tickCallback.call(this);
  88119. this._scene.registerBeforeRender(this._tickCallback);
  88120. };
  88121. /**
  88122. * Disables the cortex.
  88123. */
  88124. PhysicsUpdraftEvent.prototype.disable = function () {
  88125. this._scene.unregisterBeforeRender(this._tickCallback);
  88126. };
  88127. /**
  88128. * Disposes the sphere.
  88129. * @param {bolean} force
  88130. */
  88131. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  88132. var _this = this;
  88133. if (force === void 0) { force = true; }
  88134. if (force) {
  88135. this._cylinder.dispose();
  88136. }
  88137. else {
  88138. setTimeout(function () {
  88139. if (!_this._dataFetched) {
  88140. _this._cylinder.dispose();
  88141. }
  88142. }, 0);
  88143. }
  88144. };
  88145. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  88146. if (impostor.mass === 0) {
  88147. return null;
  88148. }
  88149. if (!this._intersectsWithCylinder(impostor)) {
  88150. return null;
  88151. }
  88152. var impostorObjectCenter = impostor.getObjectCenter();
  88153. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  88154. var direction = this._originDirection;
  88155. }
  88156. else {
  88157. var direction = impostorObjectCenter.subtract(this._originTop);
  88158. }
  88159. var multiplier = this._strength * -1;
  88160. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  88161. return { force: force, contactPoint: impostorObjectCenter };
  88162. };
  88163. PhysicsUpdraftEvent.prototype._tick = function () {
  88164. var _this = this;
  88165. this._physicsEngine.getImpostors().forEach(function (impostor) {
  88166. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  88167. if (!impostorForceAndContactPoint) {
  88168. return;
  88169. }
  88170. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  88171. });
  88172. };
  88173. /*** Helpers ***/
  88174. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  88175. if (!this._cylinder) {
  88176. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  88177. height: this._height,
  88178. diameter: this._radius * 2,
  88179. }, this._scene);
  88180. this._cylinder.isVisible = false;
  88181. }
  88182. };
  88183. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  88184. var impostorObject = impostor.object;
  88185. this._prepareCylinder();
  88186. this._cylinder.position = this._cylinderPosition;
  88187. return this._cylinder.intersectsMesh(impostorObject, true);
  88188. };
  88189. return PhysicsUpdraftEvent;
  88190. }());
  88191. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  88192. /***** Vortex *****/
  88193. var PhysicsVortexEvent = /** @class */ (function () {
  88194. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  88195. this._scene = _scene;
  88196. this._origin = _origin;
  88197. this._radius = _radius;
  88198. this._strength = _strength;
  88199. this._height = _height;
  88200. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  88201. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  88202. this._updraftMultiplier = 0.02;
  88203. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  88204. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  88205. this._physicsEngine = this._scene.getPhysicsEngine();
  88206. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  88207. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  88208. this._tickCallback = this._tick.bind(this);
  88209. }
  88210. /**
  88211. * Returns the data related to the vortex event (cylinder).
  88212. * @returns {PhysicsVortexEventData}
  88213. */
  88214. PhysicsVortexEvent.prototype.getData = function () {
  88215. this._dataFetched = true;
  88216. return {
  88217. cylinder: this._cylinder,
  88218. };
  88219. };
  88220. /**
  88221. * Enables the vortex.
  88222. */
  88223. PhysicsVortexEvent.prototype.enable = function () {
  88224. this._tickCallback.call(this);
  88225. this._scene.registerBeforeRender(this._tickCallback);
  88226. };
  88227. /**
  88228. * Disables the cortex.
  88229. */
  88230. PhysicsVortexEvent.prototype.disable = function () {
  88231. this._scene.unregisterBeforeRender(this._tickCallback);
  88232. };
  88233. /**
  88234. * Disposes the sphere.
  88235. * @param {bolean} force
  88236. */
  88237. PhysicsVortexEvent.prototype.dispose = function (force) {
  88238. var _this = this;
  88239. if (force === void 0) { force = true; }
  88240. if (force) {
  88241. this._cylinder.dispose();
  88242. }
  88243. else {
  88244. setTimeout(function () {
  88245. if (!_this._dataFetched) {
  88246. _this._cylinder.dispose();
  88247. }
  88248. }, 0);
  88249. }
  88250. };
  88251. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  88252. if (impostor.mass === 0) {
  88253. return null;
  88254. }
  88255. if (!this._intersectsWithCylinder(impostor)) {
  88256. return null;
  88257. }
  88258. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  88259. return null;
  88260. }
  88261. var impostorObjectCenter = impostor.getObjectCenter();
  88262. 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)
  88263. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  88264. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  88265. var hit = ray.intersectsMesh(impostor.object);
  88266. var contactPoint = hit.pickedPoint;
  88267. if (!contactPoint) {
  88268. return null;
  88269. }
  88270. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  88271. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  88272. var directionToOrigin = contactPoint.normalize();
  88273. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  88274. directionToOrigin = directionToOrigin.negate();
  88275. }
  88276. // TODO: find a more physically based solution
  88277. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  88278. var forceX = directionToOrigin.x * this._strength / 8;
  88279. var forceY = directionToOrigin.y * this._updraftMultiplier;
  88280. var forceZ = directionToOrigin.z * this._strength / 8;
  88281. }
  88282. else {
  88283. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  88284. var forceY = this._originTop.y * this._updraftMultiplier;
  88285. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  88286. }
  88287. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  88288. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  88289. return { force: force, contactPoint: impostorObjectCenter };
  88290. };
  88291. PhysicsVortexEvent.prototype._tick = function () {
  88292. var _this = this;
  88293. this._physicsEngine.getImpostors().forEach(function (impostor) {
  88294. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  88295. if (!impostorForceAndContactPoint) {
  88296. return;
  88297. }
  88298. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  88299. });
  88300. };
  88301. /*** Helpers ***/
  88302. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  88303. if (!this._cylinder) {
  88304. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  88305. height: this._height,
  88306. diameter: this._radius * 2,
  88307. }, this._scene);
  88308. this._cylinder.isVisible = false;
  88309. }
  88310. };
  88311. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  88312. var impostorObject = impostor.object;
  88313. this._prepareCylinder();
  88314. this._cylinder.position = this._cylinderPosition;
  88315. return this._cylinder.intersectsMesh(impostorObject, true);
  88316. };
  88317. return PhysicsVortexEvent;
  88318. }());
  88319. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  88320. /***** Enums *****/
  88321. /**
  88322. * The strenght of the force in correspondence to the distance of the affected object
  88323. */
  88324. var PhysicsRadialImpulseFalloff;
  88325. (function (PhysicsRadialImpulseFalloff) {
  88326. /** Defines that impulse is constant in strength across it's whole radius */
  88327. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  88328. /** DEfines that impulse gets weaker if it's further from the origin */
  88329. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  88330. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  88331. /**
  88332. * The strenght of the force in correspondence to the distance of the affected object
  88333. */
  88334. var PhysicsUpdraftMode;
  88335. (function (PhysicsUpdraftMode) {
  88336. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  88337. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  88338. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  88339. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  88340. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  88341. })(BABYLON || (BABYLON = {}));
  88342. //# sourceMappingURL=babylon.physicsHelper.js.map
  88343. var BABYLON;
  88344. (function (BABYLON) {
  88345. var CannonJSPlugin = /** @class */ (function () {
  88346. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  88347. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  88348. if (iterations === void 0) { iterations = 10; }
  88349. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  88350. this.name = "CannonJSPlugin";
  88351. this._physicsMaterials = new Array();
  88352. this._fixedTimeStep = 1 / 60;
  88353. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  88354. this.BJSCANNON = CANNON;
  88355. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  88356. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  88357. this._tmpPosition = BABYLON.Vector3.Zero();
  88358. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  88359. this._tmpUnityRotation = new BABYLON.Quaternion();
  88360. if (!this.isSupported()) {
  88361. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  88362. return;
  88363. }
  88364. this._extendNamespace();
  88365. this.world = new this.BJSCANNON.World();
  88366. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  88367. this.world.solver.iterations = iterations;
  88368. }
  88369. CannonJSPlugin.prototype.setGravity = function (gravity) {
  88370. this.world.gravity.copy(gravity);
  88371. };
  88372. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  88373. this._fixedTimeStep = timeStep;
  88374. };
  88375. CannonJSPlugin.prototype.getTimeStep = function () {
  88376. return this._fixedTimeStep;
  88377. };
  88378. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  88379. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  88380. };
  88381. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  88382. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  88383. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  88384. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  88385. };
  88386. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  88387. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  88388. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  88389. impostor.physicsBody.applyForce(impulse, worldPoint);
  88390. };
  88391. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  88392. //parent-child relationship. Does this impostor has a parent impostor?
  88393. if (impostor.parent) {
  88394. if (impostor.physicsBody) {
  88395. this.removePhysicsBody(impostor);
  88396. //TODO is that needed?
  88397. impostor.forceUpdate();
  88398. }
  88399. return;
  88400. }
  88401. //should a new body be created for this impostor?
  88402. if (impostor.isBodyInitRequired()) {
  88403. var shape = this._createShape(impostor);
  88404. //unregister events, if body is being changed
  88405. var oldBody = impostor.physicsBody;
  88406. if (oldBody) {
  88407. this.removePhysicsBody(impostor);
  88408. }
  88409. //create the body and material
  88410. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  88411. var bodyCreationObject = {
  88412. mass: impostor.getParam("mass"),
  88413. material: material
  88414. };
  88415. // A simple extend, in case native options were used.
  88416. var nativeOptions = impostor.getParam("nativeOptions");
  88417. for (var key in nativeOptions) {
  88418. if (nativeOptions.hasOwnProperty(key)) {
  88419. bodyCreationObject[key] = nativeOptions[key];
  88420. }
  88421. }
  88422. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  88423. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  88424. this.world.addEventListener("preStep", impostor.beforeStep);
  88425. this.world.addEventListener("postStep", impostor.afterStep);
  88426. impostor.physicsBody.addShape(shape);
  88427. this.world.add(impostor.physicsBody);
  88428. //try to keep the body moving in the right direction by taking old properties.
  88429. //Should be tested!
  88430. if (oldBody) {
  88431. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  88432. impostor.physicsBody[param].copy(oldBody[param]);
  88433. });
  88434. }
  88435. this._processChildMeshes(impostor);
  88436. }
  88437. //now update the body's transformation
  88438. this._updatePhysicsBodyTransformation(impostor);
  88439. };
  88440. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  88441. var _this = this;
  88442. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  88443. var currentRotation = mainImpostor.object.rotationQuaternion;
  88444. if (meshChildren.length) {
  88445. var processMesh = function (localPosition, mesh) {
  88446. if (!currentRotation || !mesh.rotationQuaternion) {
  88447. return;
  88448. }
  88449. var childImpostor = mesh.getPhysicsImpostor();
  88450. if (childImpostor) {
  88451. var parent = childImpostor.parent;
  88452. if (parent !== mainImpostor) {
  88453. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  88454. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  88455. if (childImpostor.physicsBody) {
  88456. _this.removePhysicsBody(childImpostor);
  88457. childImpostor.physicsBody = null;
  88458. }
  88459. childImpostor.parent = mainImpostor;
  88460. childImpostor.resetUpdateFlags();
  88461. 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));
  88462. //Add the mass of the children.
  88463. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  88464. }
  88465. }
  88466. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  88467. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  88468. };
  88469. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  88470. }
  88471. };
  88472. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  88473. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  88474. this.world.removeEventListener("preStep", impostor.beforeStep);
  88475. this.world.removeEventListener("postStep", impostor.afterStep);
  88476. this.world.remove(impostor.physicsBody);
  88477. };
  88478. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  88479. var mainBody = impostorJoint.mainImpostor.physicsBody;
  88480. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  88481. if (!mainBody || !connectedBody) {
  88482. return;
  88483. }
  88484. var constraint;
  88485. var jointData = impostorJoint.joint.jointData;
  88486. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  88487. var constraintData = {
  88488. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  88489. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  88490. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  88491. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  88492. maxForce: jointData.nativeParams.maxForce,
  88493. collideConnected: !!jointData.collision
  88494. };
  88495. switch (impostorJoint.joint.type) {
  88496. case BABYLON.PhysicsJoint.HingeJoint:
  88497. case BABYLON.PhysicsJoint.Hinge2Joint:
  88498. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  88499. break;
  88500. case BABYLON.PhysicsJoint.DistanceJoint:
  88501. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  88502. break;
  88503. case BABYLON.PhysicsJoint.SpringJoint:
  88504. var springData = jointData;
  88505. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  88506. restLength: springData.length,
  88507. stiffness: springData.stiffness,
  88508. damping: springData.damping,
  88509. localAnchorA: constraintData.pivotA,
  88510. localAnchorB: constraintData.pivotB
  88511. });
  88512. break;
  88513. case BABYLON.PhysicsJoint.LockJoint:
  88514. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  88515. break;
  88516. case BABYLON.PhysicsJoint.PointToPointJoint:
  88517. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  88518. default:
  88519. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  88520. break;
  88521. }
  88522. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  88523. constraint.collideConnected = !!jointData.collision;
  88524. impostorJoint.joint.physicsJoint = constraint;
  88525. //don't add spring as constraint, as it is not one.
  88526. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  88527. this.world.addConstraint(constraint);
  88528. }
  88529. else {
  88530. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  88531. constraint.applyForce();
  88532. });
  88533. }
  88534. };
  88535. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  88536. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  88537. };
  88538. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  88539. var index;
  88540. var mat;
  88541. for (index = 0; index < this._physicsMaterials.length; index++) {
  88542. mat = this._physicsMaterials[index];
  88543. if (mat.friction === friction && mat.restitution === restitution) {
  88544. return mat;
  88545. }
  88546. }
  88547. var currentMat = new this.BJSCANNON.Material(name);
  88548. currentMat.friction = friction;
  88549. currentMat.restitution = restitution;
  88550. this._physicsMaterials.push(currentMat);
  88551. return currentMat;
  88552. };
  88553. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  88554. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  88555. };
  88556. CannonJSPlugin.prototype._createShape = function (impostor) {
  88557. var object = impostor.object;
  88558. var returnValue;
  88559. var extendSize = impostor.getObjectExtendSize();
  88560. switch (impostor.type) {
  88561. case BABYLON.PhysicsImpostor.SphereImpostor:
  88562. var radiusX = extendSize.x;
  88563. var radiusY = extendSize.y;
  88564. var radiusZ = extendSize.z;
  88565. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  88566. break;
  88567. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  88568. case BABYLON.PhysicsImpostor.CylinderImpostor:
  88569. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  88570. break;
  88571. case BABYLON.PhysicsImpostor.BoxImpostor:
  88572. var box = extendSize.scale(0.5);
  88573. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  88574. break;
  88575. case BABYLON.PhysicsImpostor.PlaneImpostor:
  88576. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  88577. returnValue = new this.BJSCANNON.Plane();
  88578. break;
  88579. case BABYLON.PhysicsImpostor.MeshImpostor:
  88580. // should transform the vertex data to world coordinates!!
  88581. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  88582. var rawFaces = object.getIndices ? object.getIndices() : [];
  88583. if (!rawVerts)
  88584. return;
  88585. // get only scale! so the object could transform correctly.
  88586. var oldPosition = object.position.clone();
  88587. var oldRotation = object.rotation && object.rotation.clone();
  88588. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  88589. object.position.copyFromFloats(0, 0, 0);
  88590. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  88591. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  88592. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  88593. var transform = object.computeWorldMatrix(true);
  88594. // convert rawVerts to object space
  88595. var temp = new Array();
  88596. var index;
  88597. for (index = 0; index < rawVerts.length; index += 3) {
  88598. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  88599. }
  88600. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  88601. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  88602. //now set back the transformation!
  88603. object.position.copyFrom(oldPosition);
  88604. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  88605. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  88606. break;
  88607. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  88608. var oldPosition2 = object.position.clone();
  88609. var oldRotation2 = object.rotation && object.rotation.clone();
  88610. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  88611. object.position.copyFromFloats(0, 0, 0);
  88612. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  88613. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  88614. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  88615. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  88616. returnValue = this._createHeightmap(object);
  88617. object.position.copyFrom(oldPosition2);
  88618. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  88619. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  88620. object.computeWorldMatrix(true);
  88621. break;
  88622. case BABYLON.PhysicsImpostor.ParticleImpostor:
  88623. returnValue = new this.BJSCANNON.Particle();
  88624. break;
  88625. }
  88626. return returnValue;
  88627. };
  88628. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  88629. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  88630. var transform = object.computeWorldMatrix(true);
  88631. // convert rawVerts to object space
  88632. var temp = new Array();
  88633. var index;
  88634. for (index = 0; index < pos.length; index += 3) {
  88635. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  88636. }
  88637. pos = temp;
  88638. var matrix = new Array();
  88639. //For now pointDepth will not be used and will be automatically calculated.
  88640. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  88641. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  88642. var boundingInfo = object.getBoundingInfo();
  88643. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  88644. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  88645. var elementSize = dim * 2 / arraySize;
  88646. for (var i = 0; i < pos.length; i = i + 3) {
  88647. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  88648. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  88649. var y = -pos[i + 2] + minY;
  88650. if (!matrix[x]) {
  88651. matrix[x] = [];
  88652. }
  88653. if (!matrix[x][z]) {
  88654. matrix[x][z] = y;
  88655. }
  88656. matrix[x][z] = Math.max(y, matrix[x][z]);
  88657. }
  88658. for (var x = 0; x <= arraySize; ++x) {
  88659. if (!matrix[x]) {
  88660. var loc = 1;
  88661. while (!matrix[(x + loc) % arraySize]) {
  88662. loc++;
  88663. }
  88664. matrix[x] = matrix[(x + loc) % arraySize].slice();
  88665. //console.log("missing x", x);
  88666. }
  88667. for (var z = 0; z <= arraySize; ++z) {
  88668. if (!matrix[x][z]) {
  88669. var loc = 1;
  88670. var newValue;
  88671. while (newValue === undefined) {
  88672. newValue = matrix[x][(z + loc++) % arraySize];
  88673. }
  88674. matrix[x][z] = newValue;
  88675. }
  88676. }
  88677. }
  88678. var shape = new this.BJSCANNON.Heightfield(matrix, {
  88679. elementSize: elementSize
  88680. });
  88681. //For future reference, needed for body transformation
  88682. shape.minY = minY;
  88683. return shape;
  88684. };
  88685. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  88686. var object = impostor.object;
  88687. //make sure it is updated...
  88688. object.computeWorldMatrix && object.computeWorldMatrix(true);
  88689. // The delta between the mesh position and the mesh bounding box center
  88690. var bInfo = object.getBoundingInfo();
  88691. if (!bInfo)
  88692. return;
  88693. var center = impostor.getObjectCenter();
  88694. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  88695. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  88696. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  88697. this._tmpPosition.copyFrom(center);
  88698. var quaternion = object.rotationQuaternion;
  88699. if (!quaternion) {
  88700. return;
  88701. }
  88702. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  88703. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  88704. //-90 DEG in X, precalculated
  88705. quaternion = quaternion.multiply(this._minus90X);
  88706. //Invert! (Precalculated, 90 deg in X)
  88707. //No need to clone. this will never change.
  88708. impostor.setDeltaRotation(this._plus90X);
  88709. }
  88710. //If it is a heightfield, if should be centered.
  88711. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  88712. var mesh = object;
  88713. var boundingInfo = mesh.getBoundingInfo();
  88714. //calculate the correct body position:
  88715. var rotationQuaternion = mesh.rotationQuaternion;
  88716. mesh.rotationQuaternion = this._tmpUnityRotation;
  88717. mesh.computeWorldMatrix(true);
  88718. //get original center with no rotation
  88719. var c = center.clone();
  88720. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  88721. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  88722. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  88723. mesh.setPreTransformMatrix(p);
  88724. mesh.computeWorldMatrix(true);
  88725. //calculate the translation
  88726. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  88727. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  88728. //add it inverted to the delta
  88729. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  88730. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  88731. //rotation is back
  88732. mesh.rotationQuaternion = rotationQuaternion;
  88733. mesh.setPreTransformMatrix(oldPivot);
  88734. mesh.computeWorldMatrix(true);
  88735. }
  88736. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  88737. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  88738. //this._tmpPosition.copyFrom(object.position);
  88739. }
  88740. impostor.setDeltaPosition(this._tmpDeltaPosition);
  88741. //Now update the impostor object
  88742. impostor.physicsBody.position.copy(this._tmpPosition);
  88743. impostor.physicsBody.quaternion.copy(quaternion);
  88744. };
  88745. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  88746. impostor.object.position.copyFrom(impostor.physicsBody.position);
  88747. if (impostor.object.rotationQuaternion) {
  88748. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  88749. }
  88750. };
  88751. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  88752. impostor.physicsBody.position.copy(newPosition);
  88753. impostor.physicsBody.quaternion.copy(newRotation);
  88754. };
  88755. CannonJSPlugin.prototype.isSupported = function () {
  88756. return this.BJSCANNON !== undefined;
  88757. };
  88758. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  88759. impostor.physicsBody.velocity.copy(velocity);
  88760. };
  88761. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  88762. impostor.physicsBody.angularVelocity.copy(velocity);
  88763. };
  88764. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  88765. var v = impostor.physicsBody.velocity;
  88766. if (!v) {
  88767. return null;
  88768. }
  88769. return new BABYLON.Vector3(v.x, v.y, v.z);
  88770. };
  88771. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  88772. var v = impostor.physicsBody.angularVelocity;
  88773. if (!v) {
  88774. return null;
  88775. }
  88776. return new BABYLON.Vector3(v.x, v.y, v.z);
  88777. };
  88778. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  88779. impostor.physicsBody.mass = mass;
  88780. impostor.physicsBody.updateMassProperties();
  88781. };
  88782. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  88783. return impostor.physicsBody.mass;
  88784. };
  88785. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  88786. return impostor.physicsBody.material.friction;
  88787. };
  88788. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  88789. impostor.physicsBody.material.friction = friction;
  88790. };
  88791. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  88792. return impostor.physicsBody.material.restitution;
  88793. };
  88794. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  88795. impostor.physicsBody.material.restitution = restitution;
  88796. };
  88797. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  88798. impostor.physicsBody.sleep();
  88799. };
  88800. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  88801. impostor.physicsBody.wakeUp();
  88802. };
  88803. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  88804. joint.physicsJoint.distance = maxDistance;
  88805. };
  88806. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  88807. // if (!motorIndex) {
  88808. // joint.physicsJoint.enableMotor();
  88809. // }
  88810. // }
  88811. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  88812. // if (!motorIndex) {
  88813. // joint.physicsJoint.disableMotor();
  88814. // }
  88815. // }
  88816. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  88817. if (!motorIndex) {
  88818. joint.physicsJoint.enableMotor();
  88819. joint.physicsJoint.setMotorSpeed(speed);
  88820. if (maxForce) {
  88821. this.setLimit(joint, maxForce);
  88822. }
  88823. }
  88824. };
  88825. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  88826. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  88827. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  88828. };
  88829. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  88830. var body = impostor.physicsBody;
  88831. mesh.position.x = body.position.x;
  88832. mesh.position.y = body.position.y;
  88833. mesh.position.z = body.position.z;
  88834. if (mesh.rotationQuaternion) {
  88835. mesh.rotationQuaternion.x = body.quaternion.x;
  88836. mesh.rotationQuaternion.y = body.quaternion.y;
  88837. mesh.rotationQuaternion.z = body.quaternion.z;
  88838. mesh.rotationQuaternion.w = body.quaternion.w;
  88839. }
  88840. };
  88841. CannonJSPlugin.prototype.getRadius = function (impostor) {
  88842. var shape = impostor.physicsBody.shapes[0];
  88843. return shape.boundingSphereRadius;
  88844. };
  88845. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  88846. var shape = impostor.physicsBody.shapes[0];
  88847. result.x = shape.halfExtents.x * 2;
  88848. result.y = shape.halfExtents.y * 2;
  88849. result.z = shape.halfExtents.z * 2;
  88850. };
  88851. CannonJSPlugin.prototype.dispose = function () {
  88852. };
  88853. CannonJSPlugin.prototype._extendNamespace = function () {
  88854. //this will force cannon to execute at least one step when using interpolation
  88855. var step_tmp1 = new this.BJSCANNON.Vec3();
  88856. var Engine = this.BJSCANNON;
  88857. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  88858. maxSubSteps = maxSubSteps || 10;
  88859. timeSinceLastCalled = timeSinceLastCalled || 0;
  88860. if (timeSinceLastCalled === 0) {
  88861. this.internalStep(dt);
  88862. this.time += dt;
  88863. }
  88864. else {
  88865. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  88866. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  88867. var t0 = performance.now();
  88868. for (var i = 0; i !== internalSteps; i++) {
  88869. this.internalStep(dt);
  88870. if (performance.now() - t0 > dt * 1000) {
  88871. break;
  88872. }
  88873. }
  88874. this.time += timeSinceLastCalled;
  88875. var h = this.time % dt;
  88876. var h_div_dt = h / dt;
  88877. var interpvelo = step_tmp1;
  88878. var bodies = this.bodies;
  88879. for (var j = 0; j !== bodies.length; j++) {
  88880. var b = bodies[j];
  88881. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  88882. b.position.vsub(b.previousPosition, interpvelo);
  88883. interpvelo.scale(h_div_dt, interpvelo);
  88884. b.position.vadd(interpvelo, b.interpolatedPosition);
  88885. }
  88886. else {
  88887. b.interpolatedPosition.copy(b.position);
  88888. b.interpolatedQuaternion.copy(b.quaternion);
  88889. }
  88890. }
  88891. }
  88892. };
  88893. };
  88894. return CannonJSPlugin;
  88895. }());
  88896. BABYLON.CannonJSPlugin = CannonJSPlugin;
  88897. })(BABYLON || (BABYLON = {}));
  88898. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  88899. var BABYLON;
  88900. (function (BABYLON) {
  88901. var OimoJSPlugin = /** @class */ (function () {
  88902. function OimoJSPlugin(iterations) {
  88903. this.name = "OimoJSPlugin";
  88904. this._tmpImpostorsArray = [];
  88905. this._tmpPositionVector = BABYLON.Vector3.Zero();
  88906. this.BJSOIMO = OIMO;
  88907. this.world = new this.BJSOIMO.World({
  88908. iterations: iterations
  88909. });
  88910. this.world.clear();
  88911. }
  88912. OimoJSPlugin.prototype.setGravity = function (gravity) {
  88913. this.world.gravity.copy(gravity);
  88914. };
  88915. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  88916. this.world.timeStep = timeStep;
  88917. };
  88918. OimoJSPlugin.prototype.getTimeStep = function () {
  88919. return this.world.timeStep;
  88920. };
  88921. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  88922. var _this = this;
  88923. impostors.forEach(function (impostor) {
  88924. impostor.beforeStep();
  88925. });
  88926. this.world.step();
  88927. impostors.forEach(function (impostor) {
  88928. impostor.afterStep();
  88929. //update the ordered impostors array
  88930. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  88931. });
  88932. //check for collisions
  88933. var contact = this.world.contacts;
  88934. while (contact !== null) {
  88935. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  88936. contact = contact.next;
  88937. continue;
  88938. }
  88939. //is this body colliding with any other? get the impostor
  88940. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  88941. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  88942. if (!mainImpostor || !collidingImpostor) {
  88943. contact = contact.next;
  88944. continue;
  88945. }
  88946. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  88947. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  88948. contact = contact.next;
  88949. }
  88950. };
  88951. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  88952. var mass = impostor.physicsBody.mass;
  88953. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  88954. };
  88955. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  88956. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  88957. this.applyImpulse(impostor, force, contactPoint);
  88958. };
  88959. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  88960. var _this = this;
  88961. //parent-child relationship. Does this impostor has a parent impostor?
  88962. if (impostor.parent) {
  88963. if (impostor.physicsBody) {
  88964. this.removePhysicsBody(impostor);
  88965. //TODO is that needed?
  88966. impostor.forceUpdate();
  88967. }
  88968. return;
  88969. }
  88970. if (impostor.isBodyInitRequired()) {
  88971. var bodyConfig = {
  88972. name: impostor.uniqueId,
  88973. //Oimo must have mass, also for static objects.
  88974. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  88975. size: [],
  88976. type: [],
  88977. pos: [],
  88978. posShape: [],
  88979. rot: [],
  88980. rotShape: [],
  88981. move: impostor.getParam("mass") !== 0,
  88982. density: impostor.getParam("mass"),
  88983. friction: impostor.getParam("friction"),
  88984. restitution: impostor.getParam("restitution"),
  88985. //Supporting older versions of Oimo
  88986. world: this.world
  88987. };
  88988. var impostors = [impostor];
  88989. var addToArray = function (parent) {
  88990. if (!parent.getChildMeshes)
  88991. return;
  88992. parent.getChildMeshes().forEach(function (m) {
  88993. if (m.physicsImpostor) {
  88994. impostors.push(m.physicsImpostor);
  88995. //m.physicsImpostor._init();
  88996. }
  88997. });
  88998. };
  88999. addToArray(impostor.object);
  89000. var checkWithEpsilon_1 = function (value) {
  89001. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  89002. };
  89003. var globalQuaternion_1 = new BABYLON.Quaternion();
  89004. impostors.forEach(function (i) {
  89005. if (!i.object.rotationQuaternion) {
  89006. return;
  89007. }
  89008. //get the correct bounding box
  89009. var oldQuaternion = i.object.rotationQuaternion;
  89010. globalQuaternion_1 = oldQuaternion.clone();
  89011. var rot = oldQuaternion.toEulerAngles();
  89012. var extendSize = i.getObjectExtendSize();
  89013. var radToDeg = 57.295779513082320876;
  89014. if (i === impostor) {
  89015. var center = impostor.getObjectCenter();
  89016. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  89017. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  89018. //Can also use Array.prototype.push.apply
  89019. bodyConfig.pos.push(center.x);
  89020. bodyConfig.pos.push(center.y);
  89021. bodyConfig.pos.push(center.z);
  89022. bodyConfig.posShape.push(0, 0, 0);
  89023. //tmp solution
  89024. bodyConfig.rot.push(0);
  89025. bodyConfig.rot.push(0);
  89026. bodyConfig.rot.push(0);
  89027. bodyConfig.rotShape.push(0, 0, 0);
  89028. }
  89029. else {
  89030. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  89031. bodyConfig.posShape.push(localPosition.x);
  89032. bodyConfig.posShape.push(localPosition.y);
  89033. bodyConfig.posShape.push(localPosition.z);
  89034. bodyConfig.pos.push(0, 0, 0);
  89035. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  89036. bodyConfig.rot.push(0);
  89037. bodyConfig.rot.push(0);
  89038. bodyConfig.rot.push(0);
  89039. bodyConfig.rotShape.push(rot.x * radToDeg);
  89040. bodyConfig.rotShape.push(rot.y * radToDeg);
  89041. bodyConfig.rotShape.push(rot.z * radToDeg);
  89042. }
  89043. // register mesh
  89044. switch (i.type) {
  89045. case BABYLON.PhysicsImpostor.ParticleImpostor:
  89046. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  89047. case BABYLON.PhysicsImpostor.SphereImpostor:
  89048. var radiusX = extendSize.x;
  89049. var radiusY = extendSize.y;
  89050. var radiusZ = extendSize.z;
  89051. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  89052. bodyConfig.type.push('sphere');
  89053. //due to the way oimo works with compounds, add 3 times
  89054. bodyConfig.size.push(size);
  89055. bodyConfig.size.push(size);
  89056. bodyConfig.size.push(size);
  89057. break;
  89058. case BABYLON.PhysicsImpostor.CylinderImpostor:
  89059. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  89060. var sizeY = checkWithEpsilon_1(extendSize.y);
  89061. bodyConfig.type.push('cylinder');
  89062. bodyConfig.size.push(sizeX);
  89063. bodyConfig.size.push(sizeY);
  89064. //due to the way oimo works with compounds, add one more value.
  89065. bodyConfig.size.push(sizeY);
  89066. break;
  89067. case BABYLON.PhysicsImpostor.PlaneImpostor:
  89068. case BABYLON.PhysicsImpostor.BoxImpostor:
  89069. default:
  89070. var sizeX = checkWithEpsilon_1(extendSize.x);
  89071. var sizeY = checkWithEpsilon_1(extendSize.y);
  89072. var sizeZ = checkWithEpsilon_1(extendSize.z);
  89073. bodyConfig.type.push('box');
  89074. //if (i === impostor) {
  89075. bodyConfig.size.push(sizeX);
  89076. bodyConfig.size.push(sizeY);
  89077. bodyConfig.size.push(sizeZ);
  89078. //} else {
  89079. // bodyConfig.size.push(0,0,0);
  89080. //}
  89081. break;
  89082. }
  89083. //actually not needed, but hey...
  89084. i.object.rotationQuaternion = oldQuaternion;
  89085. });
  89086. impostor.physicsBody = this.world.add(bodyConfig);
  89087. // set the quaternion, ignoring the previously defined (euler) rotation
  89088. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  89089. // update with delta 0, so the body will reveive the new rotation.
  89090. impostor.physicsBody.updatePosition(0);
  89091. }
  89092. else {
  89093. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  89094. }
  89095. impostor.setDeltaPosition(this._tmpPositionVector);
  89096. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  89097. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  89098. };
  89099. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  89100. //impostor.physicsBody.dispose();
  89101. //Same as : (older oimo versions)
  89102. this.world.removeRigidBody(impostor.physicsBody);
  89103. };
  89104. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  89105. var mainBody = impostorJoint.mainImpostor.physicsBody;
  89106. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  89107. if (!mainBody || !connectedBody) {
  89108. return;
  89109. }
  89110. var jointData = impostorJoint.joint.jointData;
  89111. var options = jointData.nativeParams || {};
  89112. var type;
  89113. var nativeJointData = {
  89114. body1: mainBody,
  89115. body2: connectedBody,
  89116. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  89117. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  89118. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  89119. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  89120. min: options.min,
  89121. max: options.max,
  89122. collision: options.collision || jointData.collision,
  89123. spring: options.spring,
  89124. //supporting older version of Oimo
  89125. world: this.world
  89126. };
  89127. switch (impostorJoint.joint.type) {
  89128. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  89129. type = "jointBall";
  89130. break;
  89131. case BABYLON.PhysicsJoint.SpringJoint:
  89132. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  89133. var springData = jointData;
  89134. nativeJointData.min = springData.length || nativeJointData.min;
  89135. //Max should also be set, just make sure it is at least min
  89136. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  89137. case BABYLON.PhysicsJoint.DistanceJoint:
  89138. type = "jointDistance";
  89139. nativeJointData.max = jointData.maxDistance;
  89140. break;
  89141. case BABYLON.PhysicsJoint.PrismaticJoint:
  89142. type = "jointPrisme";
  89143. break;
  89144. case BABYLON.PhysicsJoint.SliderJoint:
  89145. type = "jointSlide";
  89146. break;
  89147. case BABYLON.PhysicsJoint.WheelJoint:
  89148. type = "jointWheel";
  89149. break;
  89150. case BABYLON.PhysicsJoint.HingeJoint:
  89151. default:
  89152. type = "jointHinge";
  89153. break;
  89154. }
  89155. nativeJointData.type = type;
  89156. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  89157. };
  89158. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  89159. //Bug in Oimo prevents us from disposing a joint in the playground
  89160. //joint.joint.physicsJoint.dispose();
  89161. //So we will bruteforce it!
  89162. try {
  89163. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  89164. }
  89165. catch (e) {
  89166. BABYLON.Tools.Warn(e);
  89167. }
  89168. };
  89169. OimoJSPlugin.prototype.isSupported = function () {
  89170. return this.BJSOIMO !== undefined;
  89171. };
  89172. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  89173. if (!impostor.physicsBody.sleeping) {
  89174. //TODO check that
  89175. /*if (impostor.physicsBody.shapes.next) {
  89176. var parentShape = this._getLastShape(impostor.physicsBody);
  89177. impostor.object.position.copyFrom(parentShape.position);
  89178. console.log(parentShape.position);
  89179. } else {*/
  89180. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  89181. //}
  89182. if (impostor.object.rotationQuaternion) {
  89183. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  89184. }
  89185. }
  89186. };
  89187. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  89188. var body = impostor.physicsBody;
  89189. body.position.copy(newPosition);
  89190. body.orientation.copy(newRotation);
  89191. body.syncShapes();
  89192. body.awake();
  89193. };
  89194. /*private _getLastShape(body: any): any {
  89195. var lastShape = body.shapes;
  89196. while (lastShape.next) {
  89197. lastShape = lastShape.next;
  89198. }
  89199. return lastShape;
  89200. }*/
  89201. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  89202. impostor.physicsBody.linearVelocity.copy(velocity);
  89203. };
  89204. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  89205. impostor.physicsBody.angularVelocity.copy(velocity);
  89206. };
  89207. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  89208. var v = impostor.physicsBody.linearVelocity;
  89209. if (!v) {
  89210. return null;
  89211. }
  89212. return new BABYLON.Vector3(v.x, v.y, v.z);
  89213. };
  89214. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  89215. var v = impostor.physicsBody.angularVelocity;
  89216. if (!v) {
  89217. return null;
  89218. }
  89219. return new BABYLON.Vector3(v.x, v.y, v.z);
  89220. };
  89221. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  89222. var staticBody = mass === 0;
  89223. //this will actually set the body's density and not its mass.
  89224. //But this is how oimo treats the mass variable.
  89225. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  89226. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  89227. };
  89228. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  89229. return impostor.physicsBody.shapes.density;
  89230. };
  89231. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  89232. return impostor.physicsBody.shapes.friction;
  89233. };
  89234. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  89235. impostor.physicsBody.shapes.friction = friction;
  89236. };
  89237. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  89238. return impostor.physicsBody.shapes.restitution;
  89239. };
  89240. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  89241. impostor.physicsBody.shapes.restitution = restitution;
  89242. };
  89243. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  89244. impostor.physicsBody.sleep();
  89245. };
  89246. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  89247. impostor.physicsBody.awake();
  89248. };
  89249. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  89250. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  89251. if (minDistance !== void 0) {
  89252. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  89253. }
  89254. };
  89255. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  89256. //TODO separate rotational and transational motors.
  89257. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  89258. if (motor) {
  89259. motor.setMotor(speed, maxForce);
  89260. }
  89261. };
  89262. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  89263. //TODO separate rotational and transational motors.
  89264. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  89265. if (motor) {
  89266. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  89267. }
  89268. };
  89269. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  89270. var body = impostor.physicsBody;
  89271. mesh.position.x = body.position.x;
  89272. mesh.position.y = body.position.y;
  89273. mesh.position.z = body.position.z;
  89274. if (mesh.rotationQuaternion) {
  89275. mesh.rotationQuaternion.x = body.orientation.x;
  89276. mesh.rotationQuaternion.y = body.orientation.y;
  89277. mesh.rotationQuaternion.z = body.orientation.z;
  89278. mesh.rotationQuaternion.w = body.orientation.s;
  89279. }
  89280. };
  89281. OimoJSPlugin.prototype.getRadius = function (impostor) {
  89282. return impostor.physicsBody.shapes.radius;
  89283. };
  89284. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  89285. var shape = impostor.physicsBody.shapes;
  89286. result.x = shape.halfWidth * 2;
  89287. result.y = shape.halfHeight * 2;
  89288. result.z = shape.halfDepth * 2;
  89289. };
  89290. OimoJSPlugin.prototype.dispose = function () {
  89291. this.world.clear();
  89292. };
  89293. return OimoJSPlugin;
  89294. }());
  89295. BABYLON.OimoJSPlugin = OimoJSPlugin;
  89296. })(BABYLON || (BABYLON = {}));
  89297. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  89298. var BABYLON;
  89299. (function (BABYLON) {
  89300. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  89301. // All values and structures referenced from:
  89302. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  89303. var DDS_MAGIC = 0x20534444;
  89304. var
  89305. //DDSD_CAPS = 0x1,
  89306. //DDSD_HEIGHT = 0x2,
  89307. //DDSD_WIDTH = 0x4,
  89308. //DDSD_PITCH = 0x8,
  89309. //DDSD_PIXELFORMAT = 0x1000,
  89310. DDSD_MIPMAPCOUNT = 0x20000;
  89311. //DDSD_LINEARSIZE = 0x80000,
  89312. //DDSD_DEPTH = 0x800000;
  89313. // var DDSCAPS_COMPLEX = 0x8,
  89314. // DDSCAPS_MIPMAP = 0x400000,
  89315. // DDSCAPS_TEXTURE = 0x1000;
  89316. var DDSCAPS2_CUBEMAP = 0x200;
  89317. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  89318. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  89319. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  89320. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  89321. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  89322. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  89323. // DDSCAPS2_VOLUME = 0x200000;
  89324. var
  89325. //DDPF_ALPHAPIXELS = 0x1,
  89326. //DDPF_ALPHA = 0x2,
  89327. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  89328. //DDPF_YUV = 0x200,
  89329. DDPF_LUMINANCE = 0x20000;
  89330. function FourCCToInt32(value) {
  89331. return value.charCodeAt(0) +
  89332. (value.charCodeAt(1) << 8) +
  89333. (value.charCodeAt(2) << 16) +
  89334. (value.charCodeAt(3) << 24);
  89335. }
  89336. function Int32ToFourCC(value) {
  89337. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  89338. }
  89339. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  89340. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  89341. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  89342. var FOURCC_DX10 = FourCCToInt32("DX10");
  89343. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  89344. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  89345. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  89346. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  89347. var headerLengthInt = 31; // The header length in 32 bit ints
  89348. // Offsets into the header array
  89349. var off_magic = 0;
  89350. var off_size = 1;
  89351. var off_flags = 2;
  89352. var off_height = 3;
  89353. var off_width = 4;
  89354. var off_mipmapCount = 7;
  89355. var off_pfFlags = 20;
  89356. var off_pfFourCC = 21;
  89357. var off_RGBbpp = 22;
  89358. var off_RMask = 23;
  89359. var off_GMask = 24;
  89360. var off_BMask = 25;
  89361. var off_AMask = 26;
  89362. // var off_caps1 = 27;
  89363. var off_caps2 = 28;
  89364. // var off_caps3 = 29;
  89365. // var off_caps4 = 30;
  89366. var off_dxgiFormat = 32;
  89367. ;
  89368. var DDSTools = /** @class */ (function () {
  89369. function DDSTools() {
  89370. }
  89371. DDSTools.GetDDSInfo = function (arrayBuffer) {
  89372. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  89373. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  89374. var mipmapCount = 1;
  89375. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  89376. mipmapCount = Math.max(1, header[off_mipmapCount]);
  89377. }
  89378. var fourCC = header[off_pfFourCC];
  89379. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  89380. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  89381. switch (fourCC) {
  89382. case FOURCC_D3DFMT_R16G16B16A16F:
  89383. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  89384. break;
  89385. case FOURCC_D3DFMT_R32G32B32A32F:
  89386. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  89387. break;
  89388. case FOURCC_DX10:
  89389. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  89390. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  89391. break;
  89392. }
  89393. }
  89394. return {
  89395. width: header[off_width],
  89396. height: header[off_height],
  89397. mipmapCount: mipmapCount,
  89398. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  89399. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  89400. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  89401. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  89402. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  89403. dxgiFormat: dxgiFormat,
  89404. textureType: textureType
  89405. };
  89406. };
  89407. DDSTools._ToHalfFloat = function (value) {
  89408. if (!DDSTools._FloatView) {
  89409. DDSTools._FloatView = new Float32Array(1);
  89410. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  89411. }
  89412. DDSTools._FloatView[0] = value;
  89413. var x = DDSTools._Int32View[0];
  89414. var bits = (x >> 16) & 0x8000; /* Get the sign */
  89415. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  89416. var e = (x >> 23) & 0xff; /* Using int is faster here */
  89417. /* If zero, or denormal, or exponent underflows too much for a denormal
  89418. * half, return signed zero. */
  89419. if (e < 103) {
  89420. return bits;
  89421. }
  89422. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  89423. if (e > 142) {
  89424. bits |= 0x7c00;
  89425. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  89426. * not Inf, so make sure we set one mantissa bit too. */
  89427. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  89428. return bits;
  89429. }
  89430. /* If exponent underflows but not too much, return a denormal */
  89431. if (e < 113) {
  89432. m |= 0x0800;
  89433. /* Extra rounding may overflow and set mantissa to 0 and exponent
  89434. * to 1, which is OK. */
  89435. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  89436. return bits;
  89437. }
  89438. bits |= ((e - 112) << 10) | (m >> 1);
  89439. bits += m & 1;
  89440. return bits;
  89441. };
  89442. DDSTools._FromHalfFloat = function (value) {
  89443. var s = (value & 0x8000) >> 15;
  89444. var e = (value & 0x7C00) >> 10;
  89445. var f = value & 0x03FF;
  89446. if (e === 0) {
  89447. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  89448. }
  89449. else if (e == 0x1F) {
  89450. return f ? NaN : ((s ? -1 : 1) * Infinity);
  89451. }
  89452. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  89453. };
  89454. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  89455. var destArray = new Float32Array(dataLength);
  89456. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  89457. var index = 0;
  89458. for (var y = 0; y < height; y++) {
  89459. for (var x = 0; x < width; x++) {
  89460. var srcPos = (x + y * width) * 4;
  89461. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  89462. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  89463. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  89464. if (DDSTools.StoreLODInAlphaChannel) {
  89465. destArray[index + 3] = lod;
  89466. }
  89467. else {
  89468. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  89469. }
  89470. index += 4;
  89471. }
  89472. }
  89473. return destArray;
  89474. };
  89475. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  89476. if (DDSTools.StoreLODInAlphaChannel) {
  89477. var destArray = new Uint16Array(dataLength);
  89478. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  89479. var index = 0;
  89480. for (var y = 0; y < height; y++) {
  89481. for (var x = 0; x < width; x++) {
  89482. var srcPos = (x + y * width) * 4;
  89483. destArray[index] = srcData[srcPos];
  89484. destArray[index + 1] = srcData[srcPos + 1];
  89485. destArray[index + 2] = srcData[srcPos + 2];
  89486. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  89487. index += 4;
  89488. }
  89489. }
  89490. return destArray;
  89491. }
  89492. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  89493. };
  89494. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  89495. if (DDSTools.StoreLODInAlphaChannel) {
  89496. var destArray = new Float32Array(dataLength);
  89497. var srcData = new Float32Array(arrayBuffer, dataOffset);
  89498. var index = 0;
  89499. for (var y = 0; y < height; y++) {
  89500. for (var x = 0; x < width; x++) {
  89501. var srcPos = (x + y * width) * 4;
  89502. destArray[index] = srcData[srcPos];
  89503. destArray[index + 1] = srcData[srcPos + 1];
  89504. destArray[index + 2] = srcData[srcPos + 2];
  89505. destArray[index + 3] = lod;
  89506. index += 4;
  89507. }
  89508. }
  89509. return destArray;
  89510. }
  89511. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  89512. };
  89513. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  89514. var destArray = new Uint8Array(dataLength);
  89515. var srcData = new Float32Array(arrayBuffer, dataOffset);
  89516. var index = 0;
  89517. for (var y = 0; y < height; y++) {
  89518. for (var x = 0; x < width; x++) {
  89519. var srcPos = (x + y * width) * 4;
  89520. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  89521. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  89522. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  89523. if (DDSTools.StoreLODInAlphaChannel) {
  89524. destArray[index + 3] = lod;
  89525. }
  89526. else {
  89527. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  89528. }
  89529. index += 4;
  89530. }
  89531. }
  89532. return destArray;
  89533. };
  89534. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  89535. var destArray = new Uint8Array(dataLength);
  89536. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  89537. var index = 0;
  89538. for (var y = 0; y < height; y++) {
  89539. for (var x = 0; x < width; x++) {
  89540. var srcPos = (x + y * width) * 4;
  89541. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  89542. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  89543. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  89544. if (DDSTools.StoreLODInAlphaChannel) {
  89545. destArray[index + 3] = lod;
  89546. }
  89547. else {
  89548. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  89549. }
  89550. index += 4;
  89551. }
  89552. }
  89553. return destArray;
  89554. };
  89555. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  89556. var byteArray = new Uint8Array(dataLength);
  89557. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  89558. var index = 0;
  89559. for (var y = 0; y < height; y++) {
  89560. for (var x = 0; x < width; x++) {
  89561. var srcPos = (x + y * width) * 4;
  89562. byteArray[index] = srcData[srcPos + rOffset];
  89563. byteArray[index + 1] = srcData[srcPos + gOffset];
  89564. byteArray[index + 2] = srcData[srcPos + bOffset];
  89565. byteArray[index + 3] = srcData[srcPos + aOffset];
  89566. index += 4;
  89567. }
  89568. }
  89569. return byteArray;
  89570. };
  89571. DDSTools._ExtractLongWordOrder = function (value) {
  89572. if (value === 0 || value === 255 || value === -16777216) {
  89573. return 0;
  89574. }
  89575. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  89576. };
  89577. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  89578. var byteArray = new Uint8Array(dataLength);
  89579. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  89580. var index = 0;
  89581. for (var y = 0; y < height; y++) {
  89582. for (var x = 0; x < width; x++) {
  89583. var srcPos = (x + y * width) * 3;
  89584. byteArray[index] = srcData[srcPos + rOffset];
  89585. byteArray[index + 1] = srcData[srcPos + gOffset];
  89586. byteArray[index + 2] = srcData[srcPos + bOffset];
  89587. index += 3;
  89588. }
  89589. }
  89590. return byteArray;
  89591. };
  89592. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  89593. var byteArray = new Uint8Array(dataLength);
  89594. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  89595. var index = 0;
  89596. for (var y = 0; y < height; y++) {
  89597. for (var x = 0; x < width; x++) {
  89598. var srcPos = (x + y * width);
  89599. byteArray[index] = srcData[srcPos];
  89600. index++;
  89601. }
  89602. }
  89603. return byteArray;
  89604. };
  89605. /**
  89606. * Uploads DDS Levels to a Babylon Texture
  89607. * @hidden
  89608. */
  89609. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  89610. if (lodIndex === void 0) { lodIndex = -1; }
  89611. var sphericalPolynomialFaces = null;
  89612. if (info.sphericalPolynomial) {
  89613. sphericalPolynomialFaces = new Array();
  89614. }
  89615. var ext = engine.getCaps().s3tc;
  89616. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  89617. var fourCC, width, height, dataLength = 0, dataOffset;
  89618. var byteArray, mipmapCount, mip;
  89619. var internalCompressedFormat = 0;
  89620. var blockBytes = 1;
  89621. if (header[off_magic] !== DDS_MAGIC) {
  89622. BABYLON.Tools.Error("Invalid magic number in DDS header");
  89623. return;
  89624. }
  89625. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  89626. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  89627. return;
  89628. }
  89629. if (info.isCompressed && !ext) {
  89630. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  89631. return;
  89632. }
  89633. var bpp = header[off_RGBbpp];
  89634. dataOffset = header[off_size] + 4;
  89635. var computeFormats = false;
  89636. if (info.isFourCC) {
  89637. fourCC = header[off_pfFourCC];
  89638. switch (fourCC) {
  89639. case FOURCC_DXT1:
  89640. blockBytes = 8;
  89641. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  89642. break;
  89643. case FOURCC_DXT3:
  89644. blockBytes = 16;
  89645. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  89646. break;
  89647. case FOURCC_DXT5:
  89648. blockBytes = 16;
  89649. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  89650. break;
  89651. case FOURCC_D3DFMT_R16G16B16A16F:
  89652. computeFormats = true;
  89653. break;
  89654. case FOURCC_D3DFMT_R32G32B32A32F:
  89655. computeFormats = true;
  89656. break;
  89657. case FOURCC_DX10:
  89658. // There is an additionnal header so dataOffset need to be changed
  89659. dataOffset += 5 * 4; // 5 uints
  89660. var supported = false;
  89661. switch (info.dxgiFormat) {
  89662. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  89663. computeFormats = true;
  89664. supported = true;
  89665. break;
  89666. case DXGI_FORMAT_B8G8R8X8_UNORM:
  89667. info.isRGB = true;
  89668. info.isFourCC = false;
  89669. bpp = 32;
  89670. supported = true;
  89671. break;
  89672. }
  89673. if (supported) {
  89674. break;
  89675. }
  89676. default:
  89677. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  89678. return;
  89679. }
  89680. }
  89681. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  89682. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  89683. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  89684. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  89685. if (computeFormats) {
  89686. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  89687. }
  89688. mipmapCount = 1;
  89689. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  89690. mipmapCount = Math.max(1, header[off_mipmapCount]);
  89691. }
  89692. for (var face = 0; face < faces; face++) {
  89693. width = header[off_width];
  89694. height = header[off_height];
  89695. for (mip = 0; mip < mipmapCount; ++mip) {
  89696. if (lodIndex === -1 || lodIndex === mip) {
  89697. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  89698. var i = (lodIndex === -1) ? mip : 0;
  89699. if (!info.isCompressed && info.isFourCC) {
  89700. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  89701. dataLength = width * height * 4;
  89702. var floatArray = null;
  89703. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  89704. if (bpp === 128) {
  89705. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  89706. if (sphericalPolynomialFaces && i == 0) {
  89707. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  89708. }
  89709. }
  89710. else if (bpp === 64) {
  89711. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  89712. if (sphericalPolynomialFaces && i == 0) {
  89713. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  89714. }
  89715. }
  89716. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  89717. }
  89718. else {
  89719. if (bpp === 128) {
  89720. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  89721. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  89722. if (sphericalPolynomialFaces && i == 0) {
  89723. sphericalPolynomialFaces.push(floatArray);
  89724. }
  89725. }
  89726. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  89727. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  89728. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  89729. if (sphericalPolynomialFaces && i == 0) {
  89730. sphericalPolynomialFaces.push(floatArray);
  89731. }
  89732. }
  89733. else { // 64
  89734. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  89735. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  89736. if (sphericalPolynomialFaces && i == 0) {
  89737. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  89738. }
  89739. }
  89740. }
  89741. if (floatArray) {
  89742. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  89743. }
  89744. }
  89745. else if (info.isRGB) {
  89746. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  89747. if (bpp === 24) {
  89748. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  89749. dataLength = width * height * 3;
  89750. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  89751. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  89752. }
  89753. else { // 32
  89754. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  89755. dataLength = width * height * 4;
  89756. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  89757. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  89758. }
  89759. }
  89760. else if (info.isLuminance) {
  89761. var unpackAlignment = engine._getUnpackAlignement();
  89762. var unpaddedRowSize = width;
  89763. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  89764. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  89765. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  89766. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  89767. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  89768. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  89769. }
  89770. else {
  89771. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  89772. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  89773. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  89774. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  89775. }
  89776. }
  89777. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  89778. width *= 0.5;
  89779. height *= 0.5;
  89780. width = Math.max(1.0, width);
  89781. height = Math.max(1.0, height);
  89782. }
  89783. if (currentFace !== undefined) {
  89784. // Loading a single face
  89785. break;
  89786. }
  89787. }
  89788. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  89789. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  89790. size: header[off_width],
  89791. right: sphericalPolynomialFaces[0],
  89792. left: sphericalPolynomialFaces[1],
  89793. up: sphericalPolynomialFaces[2],
  89794. down: sphericalPolynomialFaces[3],
  89795. front: sphericalPolynomialFaces[4],
  89796. back: sphericalPolynomialFaces[5],
  89797. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  89798. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  89799. gammaSpace: false,
  89800. });
  89801. }
  89802. else {
  89803. info.sphericalPolynomial = undefined;
  89804. }
  89805. };
  89806. DDSTools.StoreLODInAlphaChannel = false;
  89807. return DDSTools;
  89808. }());
  89809. BABYLON.DDSTools = DDSTools;
  89810. })(BABYLON || (BABYLON = {}));
  89811. //# sourceMappingURL=babylon.dds.js.map
  89812. var BABYLON;
  89813. (function (BABYLON) {
  89814. /**
  89815. * Implementation of the DDS Texture Loader.
  89816. */
  89817. var DDSTextureLoader = /** @class */ (function () {
  89818. function DDSTextureLoader() {
  89819. /**
  89820. * Defines wether the loader supports cascade loading the different faces.
  89821. */
  89822. this.supportCascades = true;
  89823. }
  89824. /**
  89825. * This returns if the loader support the current file information.
  89826. * @param extension defines the file extension of the file being loaded
  89827. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89828. * @param fallback defines the fallback internal texture if any
  89829. * @param isBase64 defines whether the texture is encoded as a base64
  89830. * @param isBuffer defines whether the texture data are stored as a buffer
  89831. * @returns true if the loader can load the specified file
  89832. */
  89833. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  89834. return extension.indexOf(".dds") === 0;
  89835. };
  89836. /**
  89837. * Transform the url before loading if required.
  89838. * @param rootUrl the url of the texture
  89839. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89840. * @returns the transformed texture
  89841. */
  89842. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  89843. return rootUrl;
  89844. };
  89845. /**
  89846. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  89847. * @param rootUrl the url of the texture
  89848. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89849. * @returns the fallback texture
  89850. */
  89851. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  89852. return null;
  89853. };
  89854. /**
  89855. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  89856. * @param data contains the texture data
  89857. * @param texture defines the BabylonJS internal texture
  89858. * @param createPolynomials will be true if polynomials have been requested
  89859. * @param onLoad defines the callback to trigger once the texture is ready
  89860. * @param onError defines the callback to trigger in case of error
  89861. */
  89862. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  89863. var engine = texture.getEngine();
  89864. var info;
  89865. var loadMipmap = false;
  89866. if (Array.isArray(imgs)) {
  89867. for (var index = 0; index < imgs.length; index++) {
  89868. var data_1 = imgs[index];
  89869. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  89870. texture.width = info.width;
  89871. texture.height = info.height;
  89872. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  89873. engine._unpackFlipY(info.isCompressed);
  89874. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  89875. if (!info.isFourCC && info.mipmapCount === 1) {
  89876. engine.generateMipMapsForCubemap(texture);
  89877. }
  89878. }
  89879. }
  89880. else {
  89881. var data = imgs;
  89882. info = BABYLON.DDSTools.GetDDSInfo(data);
  89883. texture.width = info.width;
  89884. texture.height = info.height;
  89885. if (createPolynomials) {
  89886. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  89887. }
  89888. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  89889. engine._unpackFlipY(info.isCompressed);
  89890. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  89891. if (!info.isFourCC && info.mipmapCount === 1) {
  89892. engine.generateMipMapsForCubemap(texture);
  89893. }
  89894. }
  89895. engine._setCubeMapTextureParams(loadMipmap);
  89896. texture.isReady = true;
  89897. if (onLoad) {
  89898. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  89899. }
  89900. };
  89901. /**
  89902. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  89903. * @param data contains the texture data
  89904. * @param texture defines the BabylonJS internal texture
  89905. * @param callback defines the method to call once ready to upload
  89906. */
  89907. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  89908. var info = BABYLON.DDSTools.GetDDSInfo(data);
  89909. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  89910. callback(info.width, info.height, loadMipmap, info.isFourCC, function () {
  89911. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  89912. });
  89913. };
  89914. return DDSTextureLoader;
  89915. }());
  89916. // Register the loader.
  89917. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  89918. })(BABYLON || (BABYLON = {}));
  89919. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  89920. var BABYLON;
  89921. (function (BABYLON) {
  89922. /*
  89923. * Based on jsTGALoader - Javascript loader for TGA file
  89924. * By Vincent Thibault
  89925. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  89926. */
  89927. var TGATools = /** @class */ (function () {
  89928. function TGATools() {
  89929. }
  89930. TGATools.GetTGAHeader = function (data) {
  89931. var offset = 0;
  89932. var header = {
  89933. id_length: data[offset++],
  89934. colormap_type: data[offset++],
  89935. image_type: data[offset++],
  89936. colormap_index: data[offset++] | data[offset++] << 8,
  89937. colormap_length: data[offset++] | data[offset++] << 8,
  89938. colormap_size: data[offset++],
  89939. origin: [
  89940. data[offset++] | data[offset++] << 8,
  89941. data[offset++] | data[offset++] << 8
  89942. ],
  89943. width: data[offset++] | data[offset++] << 8,
  89944. height: data[offset++] | data[offset++] << 8,
  89945. pixel_size: data[offset++],
  89946. flags: data[offset++]
  89947. };
  89948. return header;
  89949. };
  89950. /**
  89951. * Uploads TGA content to a Babylon Texture
  89952. * @hidden
  89953. */
  89954. TGATools.UploadContent = function (texture, data) {
  89955. // Not enough data to contain header ?
  89956. if (data.length < 19) {
  89957. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  89958. return;
  89959. }
  89960. // Read Header
  89961. var offset = 18;
  89962. var header = TGATools.GetTGAHeader(data);
  89963. // Assume it's a valid Targa file.
  89964. if (header.id_length + offset > data.length) {
  89965. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  89966. return;
  89967. }
  89968. // Skip not needed data
  89969. offset += header.id_length;
  89970. var use_rle = false;
  89971. var use_pal = false;
  89972. var use_grey = false;
  89973. // Get some informations.
  89974. switch (header.image_type) {
  89975. case TGATools._TYPE_RLE_INDEXED:
  89976. use_rle = true;
  89977. case TGATools._TYPE_INDEXED:
  89978. use_pal = true;
  89979. break;
  89980. case TGATools._TYPE_RLE_RGB:
  89981. use_rle = true;
  89982. case TGATools._TYPE_RGB:
  89983. // use_rgb = true;
  89984. break;
  89985. case TGATools._TYPE_RLE_GREY:
  89986. use_rle = true;
  89987. case TGATools._TYPE_GREY:
  89988. use_grey = true;
  89989. break;
  89990. }
  89991. var pixel_data;
  89992. // var numAlphaBits = header.flags & 0xf;
  89993. var pixel_size = header.pixel_size >> 3;
  89994. var pixel_total = header.width * header.height * pixel_size;
  89995. // Read palettes
  89996. var palettes;
  89997. if (use_pal) {
  89998. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  89999. }
  90000. // Read LRE
  90001. if (use_rle) {
  90002. pixel_data = new Uint8Array(pixel_total);
  90003. var c, count, i;
  90004. var localOffset = 0;
  90005. var pixels = new Uint8Array(pixel_size);
  90006. while (offset < pixel_total && localOffset < pixel_total) {
  90007. c = data[offset++];
  90008. count = (c & 0x7f) + 1;
  90009. // RLE pixels
  90010. if (c & 0x80) {
  90011. // Bind pixel tmp array
  90012. for (i = 0; i < pixel_size; ++i) {
  90013. pixels[i] = data[offset++];
  90014. }
  90015. // Copy pixel array
  90016. for (i = 0; i < count; ++i) {
  90017. pixel_data.set(pixels, localOffset + i * pixel_size);
  90018. }
  90019. localOffset += pixel_size * count;
  90020. }
  90021. // Raw pixels
  90022. else {
  90023. count *= pixel_size;
  90024. for (i = 0; i < count; ++i) {
  90025. pixel_data[localOffset + i] = data[offset++];
  90026. }
  90027. localOffset += count;
  90028. }
  90029. }
  90030. }
  90031. // RAW Pixels
  90032. else {
  90033. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  90034. }
  90035. // Load to texture
  90036. var x_start, y_start, x_step, y_step, y_end, x_end;
  90037. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  90038. default:
  90039. case TGATools._ORIGIN_UL:
  90040. x_start = 0;
  90041. x_step = 1;
  90042. x_end = header.width;
  90043. y_start = 0;
  90044. y_step = 1;
  90045. y_end = header.height;
  90046. break;
  90047. case TGATools._ORIGIN_BL:
  90048. x_start = 0;
  90049. x_step = 1;
  90050. x_end = header.width;
  90051. y_start = header.height - 1;
  90052. y_step = -1;
  90053. y_end = -1;
  90054. break;
  90055. case TGATools._ORIGIN_UR:
  90056. x_start = header.width - 1;
  90057. x_step = -1;
  90058. x_end = -1;
  90059. y_start = 0;
  90060. y_step = 1;
  90061. y_end = header.height;
  90062. break;
  90063. case TGATools._ORIGIN_BR:
  90064. x_start = header.width - 1;
  90065. x_step = -1;
  90066. x_end = -1;
  90067. y_start = header.height - 1;
  90068. y_step = -1;
  90069. y_end = -1;
  90070. break;
  90071. }
  90072. // Load the specify method
  90073. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  90074. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  90075. var engine = texture.getEngine();
  90076. engine._uploadDataToTextureDirectly(texture, imageData);
  90077. };
  90078. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  90079. var image = pixel_data, colormap = palettes;
  90080. var width = header.width, height = header.height;
  90081. var color, i = 0, x, y;
  90082. var imageData = new Uint8Array(width * height * 4);
  90083. for (y = y_start; y !== y_end; y += y_step) {
  90084. for (x = x_start; x !== x_end; x += x_step, i++) {
  90085. color = image[i];
  90086. imageData[(x + width * y) * 4 + 3] = 255;
  90087. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  90088. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  90089. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  90090. }
  90091. }
  90092. return imageData;
  90093. };
  90094. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  90095. var image = pixel_data;
  90096. var width = header.width, height = header.height;
  90097. var color, i = 0, x, y;
  90098. var imageData = new Uint8Array(width * height * 4);
  90099. for (y = y_start; y !== y_end; y += y_step) {
  90100. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  90101. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  90102. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  90103. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  90104. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  90105. imageData[(x + width * y) * 4 + 0] = r;
  90106. imageData[(x + width * y) * 4 + 1] = g;
  90107. imageData[(x + width * y) * 4 + 2] = b;
  90108. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  90109. }
  90110. }
  90111. return imageData;
  90112. };
  90113. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  90114. var image = pixel_data;
  90115. var width = header.width, height = header.height;
  90116. var i = 0, x, y;
  90117. var imageData = new Uint8Array(width * height * 4);
  90118. for (y = y_start; y !== y_end; y += y_step) {
  90119. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  90120. imageData[(x + width * y) * 4 + 3] = 255;
  90121. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  90122. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  90123. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  90124. }
  90125. }
  90126. return imageData;
  90127. };
  90128. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  90129. var image = pixel_data;
  90130. var width = header.width, height = header.height;
  90131. var i = 0, x, y;
  90132. var imageData = new Uint8Array(width * height * 4);
  90133. for (y = y_start; y !== y_end; y += y_step) {
  90134. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  90135. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  90136. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  90137. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  90138. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  90139. }
  90140. }
  90141. return imageData;
  90142. };
  90143. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  90144. var image = pixel_data;
  90145. var width = header.width, height = header.height;
  90146. var color, i = 0, x, y;
  90147. var imageData = new Uint8Array(width * height * 4);
  90148. for (y = y_start; y !== y_end; y += y_step) {
  90149. for (x = x_start; x !== x_end; x += x_step, i++) {
  90150. color = image[i];
  90151. imageData[(x + width * y) * 4 + 0] = color;
  90152. imageData[(x + width * y) * 4 + 1] = color;
  90153. imageData[(x + width * y) * 4 + 2] = color;
  90154. imageData[(x + width * y) * 4 + 3] = 255;
  90155. }
  90156. }
  90157. return imageData;
  90158. };
  90159. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  90160. var image = pixel_data;
  90161. var width = header.width, height = header.height;
  90162. var i = 0, x, y;
  90163. var imageData = new Uint8Array(width * height * 4);
  90164. for (y = y_start; y !== y_end; y += y_step) {
  90165. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  90166. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  90167. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  90168. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  90169. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  90170. }
  90171. }
  90172. return imageData;
  90173. };
  90174. //private static _TYPE_NO_DATA = 0;
  90175. TGATools._TYPE_INDEXED = 1;
  90176. TGATools._TYPE_RGB = 2;
  90177. TGATools._TYPE_GREY = 3;
  90178. TGATools._TYPE_RLE_INDEXED = 9;
  90179. TGATools._TYPE_RLE_RGB = 10;
  90180. TGATools._TYPE_RLE_GREY = 11;
  90181. TGATools._ORIGIN_MASK = 0x30;
  90182. TGATools._ORIGIN_SHIFT = 0x04;
  90183. TGATools._ORIGIN_BL = 0x00;
  90184. TGATools._ORIGIN_BR = 0x01;
  90185. TGATools._ORIGIN_UL = 0x02;
  90186. TGATools._ORIGIN_UR = 0x03;
  90187. return TGATools;
  90188. }());
  90189. BABYLON.TGATools = TGATools;
  90190. })(BABYLON || (BABYLON = {}));
  90191. //# sourceMappingURL=babylon.tga.js.map
  90192. var BABYLON;
  90193. (function (BABYLON) {
  90194. /**
  90195. * Implementation of the TGA Texture Loader.
  90196. */
  90197. var TGATextureLoader = /** @class */ (function () {
  90198. function TGATextureLoader() {
  90199. /**
  90200. * Defines wether the loader supports cascade loading the different faces.
  90201. */
  90202. this.supportCascades = false;
  90203. }
  90204. /**
  90205. * This returns if the loader support the current file information.
  90206. * @param extension defines the file extension of the file being loaded
  90207. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90208. * @param fallback defines the fallback internal texture if any
  90209. * @param isBase64 defines whether the texture is encoded as a base64
  90210. * @param isBuffer defines whether the texture data are stored as a buffer
  90211. * @returns true if the loader can load the specified file
  90212. */
  90213. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  90214. return extension.indexOf(".tga") === 0;
  90215. };
  90216. /**
  90217. * Transform the url before loading if required.
  90218. * @param rootUrl the url of the texture
  90219. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90220. * @returns the transformed texture
  90221. */
  90222. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  90223. return rootUrl;
  90224. };
  90225. /**
  90226. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  90227. * @param rootUrl the url of the texture
  90228. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90229. * @returns the fallback texture
  90230. */
  90231. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  90232. return null;
  90233. };
  90234. /**
  90235. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  90236. * @param data contains the texture data
  90237. * @param texture defines the BabylonJS internal texture
  90238. * @param createPolynomials will be true if polynomials have been requested
  90239. * @param onLoad defines the callback to trigger once the texture is ready
  90240. * @param onError defines the callback to trigger in case of error
  90241. */
  90242. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  90243. throw ".env not supported in Cube.";
  90244. };
  90245. /**
  90246. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  90247. * @param data contains the texture data
  90248. * @param texture defines the BabylonJS internal texture
  90249. * @param callback defines the method to call once ready to upload
  90250. */
  90251. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  90252. var uintData = new Uint8Array(data);
  90253. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  90254. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  90255. BABYLON.TGATools.UploadContent(texture, uintData);
  90256. });
  90257. };
  90258. return TGATextureLoader;
  90259. }());
  90260. // Register the loader.
  90261. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  90262. })(BABYLON || (BABYLON = {}));
  90263. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  90264. var BABYLON;
  90265. (function (BABYLON) {
  90266. /**
  90267. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  90268. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  90269. */
  90270. var KhronosTextureContainer = /** @class */ (function () {
  90271. /**
  90272. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  90273. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  90274. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  90275. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  90276. */
  90277. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  90278. this.arrayBuffer = arrayBuffer;
  90279. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  90280. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  90281. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  90282. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  90283. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  90284. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  90285. BABYLON.Tools.Error("texture missing KTX identifier");
  90286. return;
  90287. }
  90288. // load the reset of the header in native 32 bit int
  90289. var header = new Int32Array(this.arrayBuffer, 12, 13);
  90290. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  90291. var oppositeEndianess = header[0] === 0x01020304;
  90292. // read all the header elements in order they exist in the file, without modification (sans endainness)
  90293. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  90294. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  90295. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  90296. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  90297. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  90298. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  90299. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  90300. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  90301. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  90302. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  90303. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  90304. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  90305. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  90306. if (this.glType !== 0) {
  90307. BABYLON.Tools.Error("only compressed formats currently supported");
  90308. return;
  90309. }
  90310. else {
  90311. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  90312. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  90313. }
  90314. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  90315. BABYLON.Tools.Error("only 2D textures currently supported");
  90316. return;
  90317. }
  90318. if (this.numberOfArrayElements !== 0) {
  90319. BABYLON.Tools.Error("texture arrays not currently supported");
  90320. return;
  90321. }
  90322. if (this.numberOfFaces !== facesExpected) {
  90323. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  90324. return;
  90325. }
  90326. // we now have a completely validated file, so could use existence of loadType as success
  90327. // would need to make this more elaborate & adjust checks above to support more than one load type
  90328. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  90329. }
  90330. // not as fast hardware based, but will probably never need to use
  90331. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  90332. return ((val & 0xFF) << 24)
  90333. | ((val & 0xFF00) << 8)
  90334. | ((val >> 8) & 0xFF00)
  90335. | ((val >> 24) & 0xFF);
  90336. };
  90337. /**
  90338. * Uploads KTX content to a Babylon Texture.
  90339. * It is assumed that the texture has already been created & is currently bound
  90340. * @hidden
  90341. */
  90342. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  90343. switch (this.loadType) {
  90344. case KhronosTextureContainer.COMPRESSED_2D:
  90345. this._upload2DCompressedLevels(texture, loadMipmaps);
  90346. break;
  90347. case KhronosTextureContainer.TEX_2D:
  90348. case KhronosTextureContainer.COMPRESSED_3D:
  90349. case KhronosTextureContainer.TEX_3D:
  90350. }
  90351. };
  90352. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  90353. // initialize width & height for level 1
  90354. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  90355. var width = this.pixelWidth;
  90356. var height = this.pixelHeight;
  90357. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  90358. for (var level = 0; level < mipmapCount; level++) {
  90359. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  90360. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  90361. for (var face = 0; face < this.numberOfFaces; face++) {
  90362. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  90363. var engine = texture.getEngine();
  90364. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  90365. dataOffset += imageSize; // add size of the image for the next face/mipmap
  90366. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  90367. }
  90368. width = Math.max(1.0, width * 0.5);
  90369. height = Math.max(1.0, height * 0.5);
  90370. }
  90371. };
  90372. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  90373. // load types
  90374. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  90375. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  90376. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  90377. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  90378. return KhronosTextureContainer;
  90379. }());
  90380. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  90381. })(BABYLON || (BABYLON = {}));
  90382. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  90383. var BABYLON;
  90384. (function (BABYLON) {
  90385. /**
  90386. * Implementation of the KTX Texture Loader.
  90387. */
  90388. var KTXTextureLoader = /** @class */ (function () {
  90389. function KTXTextureLoader() {
  90390. /**
  90391. * Defines wether the loader supports cascade loading the different faces.
  90392. */
  90393. this.supportCascades = false;
  90394. }
  90395. /**
  90396. * This returns if the loader support the current file information.
  90397. * @param extension defines the file extension of the file being loaded
  90398. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90399. * @param fallback defines the fallback internal texture if any
  90400. * @param isBase64 defines whether the texture is encoded as a base64
  90401. * @param isBuffer defines whether the texture data are stored as a buffer
  90402. * @returns true if the loader can load the specified file
  90403. */
  90404. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  90405. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  90406. return true;
  90407. }
  90408. return false;
  90409. };
  90410. /**
  90411. * Transform the url before loading if required.
  90412. * @param rootUrl the url of the texture
  90413. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90414. * @returns the transformed texture
  90415. */
  90416. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  90417. var lastDot = rootUrl.lastIndexOf('.');
  90418. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  90419. };
  90420. /**
  90421. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  90422. * @param rootUrl the url of the texture
  90423. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90424. * @returns the fallback texture
  90425. */
  90426. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  90427. // remove the format appended to the rootUrl in the original createCubeTexture call.
  90428. var exp = new RegExp("" + textureFormatInUse + "$");
  90429. return rootUrl.replace(exp, "");
  90430. };
  90431. /**
  90432. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  90433. * @param data contains the texture data
  90434. * @param texture defines the BabylonJS internal texture
  90435. * @param createPolynomials will be true if polynomials have been requested
  90436. * @param onLoad defines the callback to trigger once the texture is ready
  90437. * @param onError defines the callback to trigger in case of error
  90438. */
  90439. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  90440. if (Array.isArray(data)) {
  90441. return;
  90442. }
  90443. var engine = texture.getEngine();
  90444. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  90445. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  90446. engine._unpackFlipY(true);
  90447. ktx.uploadLevels(texture, texture.generateMipMaps);
  90448. texture.width = ktx.pixelWidth;
  90449. texture.height = ktx.pixelHeight;
  90450. engine._setCubeMapTextureParams(loadMipmap);
  90451. texture.isReady = true;
  90452. };
  90453. /**
  90454. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  90455. * @param data contains the texture data
  90456. * @param texture defines the BabylonJS internal texture
  90457. * @param callback defines the method to call once ready to upload
  90458. */
  90459. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  90460. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  90461. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  90462. ktx.uploadLevels(texture, texture.generateMipMaps);
  90463. });
  90464. };
  90465. return KTXTextureLoader;
  90466. }());
  90467. // Register the loader.
  90468. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  90469. })(BABYLON || (BABYLON = {}));
  90470. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  90471. var BABYLON;
  90472. (function (BABYLON) {
  90473. /**
  90474. * Sets of helpers addressing the serialization and deserialization of environment texture
  90475. * stored in a BabylonJS env file.
  90476. * Those files are usually stored as .env files.
  90477. */
  90478. var EnvironmentTextureTools = /** @class */ (function () {
  90479. function EnvironmentTextureTools() {
  90480. }
  90481. /**
  90482. * Gets the environment info from an env file.
  90483. * @param data The array buffer containing the .env bytes.
  90484. * @returns the environment file info (the json header) if successfully parsed.
  90485. */
  90486. EnvironmentTextureTools.GetEnvInfo = function (data) {
  90487. var dataView = new DataView(data);
  90488. var pos = 0;
  90489. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  90490. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  90491. BABYLON.Tools.Error('Not a babylon environment map');
  90492. return null;
  90493. }
  90494. }
  90495. // Read json manifest - collect characters up to null terminator
  90496. var manifestString = '';
  90497. var charCode = 0x00;
  90498. while ((charCode = dataView.getUint8(pos++))) {
  90499. manifestString += String.fromCharCode(charCode);
  90500. }
  90501. var manifest = JSON.parse(manifestString);
  90502. if (manifest.specular) {
  90503. // Extend the header with the position of the payload.
  90504. manifest.specular.specularDataPosition = pos;
  90505. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  90506. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  90507. }
  90508. return manifest;
  90509. };
  90510. /**
  90511. * Creates an environment texture from a loaded cube texture.
  90512. * @param texture defines the cube texture to convert in env file
  90513. * @return a promise containing the environment data if succesfull.
  90514. */
  90515. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  90516. var _this = this;
  90517. var internalTexture = texture.getInternalTexture();
  90518. if (!internalTexture) {
  90519. return Promise.reject("The cube texture is invalid.");
  90520. }
  90521. if (!texture._prefiltered) {
  90522. return Promise.reject("The cube texture is invalid (not prefiltered).");
  90523. }
  90524. var engine = internalTexture.getEngine();
  90525. if (engine && engine.premultipliedAlpha) {
  90526. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  90527. }
  90528. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  90529. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  90530. }
  90531. var canvas = engine.getRenderingCanvas();
  90532. if (!canvas) {
  90533. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  90534. }
  90535. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  90536. if (!engine.getCaps().textureFloatRender) {
  90537. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  90538. if (!engine.getCaps().textureHalfFloatRender) {
  90539. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  90540. }
  90541. }
  90542. var cubeWidth = internalTexture.width;
  90543. var hostingScene = new BABYLON.Scene(engine);
  90544. var specularTextures = {};
  90545. var promises = [];
  90546. // Read and collect all mipmaps data from the cube.
  90547. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  90548. mipmapsCount = Math.round(mipmapsCount);
  90549. var _loop_1 = function (i) {
  90550. var faceWidth = Math.pow(2, mipmapsCount - i);
  90551. var _loop_2 = function (face) {
  90552. var data = texture.readPixels(face, i);
  90553. // Creates a temp texture with the face data.
  90554. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  90555. // And rgbdEncode them.
  90556. var promise = new Promise(function (resolve, reject) {
  90557. 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);
  90558. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  90559. rgbdPostProcess.onApply = function (effect) {
  90560. effect._bindTexture("textureSampler", tempTexture);
  90561. };
  90562. // As the process needs to happen on the main canvas, keep track of the current size
  90563. var currentW = engine.getRenderWidth();
  90564. var currentH = engine.getRenderHeight();
  90565. // Set the desired size for the texture
  90566. engine.setSize(faceWidth, faceWidth);
  90567. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  90568. // Reading datas from WebGL
  90569. BABYLON.Tools.ToBlob(canvas, function (blob) {
  90570. var fileReader = new FileReader();
  90571. fileReader.onload = function (event) {
  90572. var arrayBuffer = event.target.result;
  90573. specularTextures[i * 6 + face] = arrayBuffer;
  90574. resolve();
  90575. };
  90576. fileReader.readAsArrayBuffer(blob);
  90577. });
  90578. // Reapply the previous canvas size
  90579. engine.setSize(currentW, currentH);
  90580. });
  90581. });
  90582. promises.push(promise);
  90583. };
  90584. // All faces of the cube.
  90585. for (var face = 0; face < 6; face++) {
  90586. _loop_2(face);
  90587. }
  90588. };
  90589. for (var i = 0; i <= mipmapsCount; i++) {
  90590. _loop_1(i);
  90591. }
  90592. // Once all the textures haves been collected as RGBD stored in PNGs
  90593. return Promise.all(promises).then(function () {
  90594. // We can delete the hosting scene keeping track of all the creation objects
  90595. hostingScene.dispose();
  90596. // Creates the json header for the env texture
  90597. var info = {
  90598. version: 1,
  90599. width: cubeWidth,
  90600. irradiance: _this._CreateEnvTextureIrradiance(texture),
  90601. specular: {
  90602. mipmaps: [],
  90603. lodGenerationScale: texture.lodGenerationScale
  90604. }
  90605. };
  90606. // Sets the specular image data information
  90607. var position = 0;
  90608. for (var i = 0; i <= mipmapsCount; i++) {
  90609. for (var face = 0; face < 6; face++) {
  90610. var byteLength = specularTextures[i * 6 + face].byteLength;
  90611. info.specular.mipmaps.push({
  90612. length: byteLength,
  90613. position: position
  90614. });
  90615. position += byteLength;
  90616. }
  90617. }
  90618. // Encode the JSON as an array buffer
  90619. var infoString = JSON.stringify(info);
  90620. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  90621. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  90622. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  90623. infoView[i] = infoString.charCodeAt(i);
  90624. }
  90625. // Ends up with a null terminator for easier parsing
  90626. infoView[infoString.length] = 0x00;
  90627. // Computes the final required size and creates the storage
  90628. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  90629. var finalBuffer = new ArrayBuffer(totalSize);
  90630. var finalBufferView = new Uint8Array(finalBuffer);
  90631. var dataView = new DataView(finalBuffer);
  90632. // Copy the magic bytes identifying the file in
  90633. var pos = 0;
  90634. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  90635. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  90636. }
  90637. // Add the json info
  90638. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  90639. pos += infoBuffer.byteLength;
  90640. // Finally inserts the texture data
  90641. for (var i = 0; i <= mipmapsCount; i++) {
  90642. for (var face = 0; face < 6; face++) {
  90643. var dataBuffer = specularTextures[i * 6 + face];
  90644. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  90645. pos += dataBuffer.byteLength;
  90646. }
  90647. }
  90648. // Voila
  90649. return finalBuffer;
  90650. });
  90651. };
  90652. /**
  90653. * Creates a JSON representation of the spherical data.
  90654. * @param texture defines the texture containing the polynomials
  90655. * @return the JSON representation of the spherical info
  90656. */
  90657. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  90658. var polynmials = texture.sphericalPolynomial;
  90659. if (polynmials == null) {
  90660. return null;
  90661. }
  90662. return {
  90663. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  90664. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  90665. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  90666. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  90667. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  90668. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  90669. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  90670. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  90671. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  90672. };
  90673. };
  90674. /**
  90675. * Uploads the texture info contained in the env file to the GPU.
  90676. * @param texture defines the internal texture to upload to
  90677. * @param arrayBuffer defines the buffer cotaining the data to load
  90678. * @param info defines the texture info retrieved through the GetEnvInfo method
  90679. * @returns a promise
  90680. */
  90681. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  90682. if (info.version !== 1) {
  90683. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  90684. }
  90685. var specularInfo = info.specular;
  90686. if (!specularInfo) {
  90687. // Nothing else parsed so far
  90688. return Promise.resolve();
  90689. }
  90690. // Double checks the enclosed info
  90691. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  90692. mipmapsCount = Math.round(mipmapsCount) + 1;
  90693. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  90694. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  90695. }
  90696. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  90697. var imageData = new Array(mipmapsCount);
  90698. for (var i = 0; i < mipmapsCount; i++) {
  90699. imageData[i] = new Array(6);
  90700. for (var face = 0; face < 6; face++) {
  90701. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  90702. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  90703. }
  90704. }
  90705. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  90706. };
  90707. /**
  90708. * Uploads the levels of image data to the GPU.
  90709. * @param texture defines the internal texture to upload to
  90710. * @param imageData defines the array buffer views of image data [mipmap][face]
  90711. * @returns a promise
  90712. */
  90713. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  90714. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  90715. throw new Error("Texture size must be a power of two");
  90716. }
  90717. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  90718. // Gets everything ready.
  90719. var engine = texture.getEngine();
  90720. var expandTexture = false;
  90721. var generateNonLODTextures = false;
  90722. var rgbdPostProcess = null;
  90723. var cubeRtt = null;
  90724. var lodTextures = null;
  90725. var caps = engine.getCaps();
  90726. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  90727. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  90728. texture.generateMipMaps = true;
  90729. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  90730. // Add extra process if texture lod is not supported
  90731. if (!caps.textureLOD) {
  90732. expandTexture = false;
  90733. generateNonLODTextures = true;
  90734. lodTextures = {};
  90735. }
  90736. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  90737. else if (engine.webGLVersion < 2) {
  90738. expandTexture = false;
  90739. }
  90740. // If half float available we can uncompress the texture
  90741. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  90742. expandTexture = true;
  90743. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  90744. }
  90745. // If full float available we can uncompress the texture
  90746. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  90747. expandTexture = true;
  90748. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  90749. }
  90750. // Expand the texture if possible
  90751. if (expandTexture) {
  90752. // Simply run through the decode PP
  90753. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  90754. texture._isRGBD = false;
  90755. texture.invertY = false;
  90756. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  90757. generateDepthBuffer: false,
  90758. generateMipMaps: true,
  90759. generateStencilBuffer: false,
  90760. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  90761. type: texture.type,
  90762. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  90763. });
  90764. }
  90765. else {
  90766. texture._isRGBD = true;
  90767. texture.invertY = true;
  90768. // In case of missing support, applies the same patch than DDS files.
  90769. if (generateNonLODTextures) {
  90770. var mipSlices = 3;
  90771. var scale = texture._lodGenerationScale;
  90772. var offset = texture._lodGenerationOffset;
  90773. for (var i = 0; i < mipSlices; i++) {
  90774. //compute LOD from even spacing in smoothness (matching shader calculation)
  90775. var smoothness = i / (mipSlices - 1);
  90776. var roughness = 1 - smoothness;
  90777. var minLODIndex = offset; // roughness = 0
  90778. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  90779. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  90780. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  90781. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  90782. glTextureFromLod.isCube = true;
  90783. glTextureFromLod.invertY = true;
  90784. glTextureFromLod.generateMipMaps = false;
  90785. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  90786. // Wrap in a base texture for easy binding.
  90787. var lodTexture = new BABYLON.BaseTexture(null);
  90788. lodTexture.isCube = true;
  90789. lodTexture._texture = glTextureFromLod;
  90790. lodTextures[mipmapIndex] = lodTexture;
  90791. switch (i) {
  90792. case 0:
  90793. texture._lodTextureLow = lodTexture;
  90794. break;
  90795. case 1:
  90796. texture._lodTextureMid = lodTexture;
  90797. break;
  90798. case 2:
  90799. texture._lodTextureHigh = lodTexture;
  90800. break;
  90801. }
  90802. }
  90803. }
  90804. }
  90805. var promises = [];
  90806. var _loop_3 = function (i) {
  90807. var _loop_4 = function (face) {
  90808. // Constructs an image element from image data
  90809. var bytes = imageData[i][face];
  90810. var blob = new Blob([bytes], { type: 'image/png' });
  90811. var url = URL.createObjectURL(blob);
  90812. var image = new Image();
  90813. image.src = url;
  90814. // Enqueue promise to upload to the texture.
  90815. var promise = new Promise(function (resolve, reject) {
  90816. image.onload = function () {
  90817. if (expandTexture) {
  90818. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  90819. reject(message);
  90820. }, image);
  90821. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  90822. // Uncompress the data to a RTT
  90823. rgbdPostProcess.onApply = function (effect) {
  90824. effect._bindTexture("textureSampler", tempTexture_1);
  90825. effect.setFloat2("scale", 1, 1);
  90826. };
  90827. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  90828. // Cleanup
  90829. engine.restoreDefaultFramebuffer();
  90830. tempTexture_1.dispose();
  90831. window.URL.revokeObjectURL(url);
  90832. resolve();
  90833. });
  90834. }
  90835. else {
  90836. engine._uploadImageToTexture(texture, image, face, i);
  90837. // Upload the face to the non lod texture support
  90838. if (generateNonLODTextures) {
  90839. var lodTexture = lodTextures[i];
  90840. if (lodTexture) {
  90841. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  90842. }
  90843. }
  90844. resolve();
  90845. }
  90846. };
  90847. image.onerror = function (error) {
  90848. reject(error);
  90849. };
  90850. });
  90851. promises.push(promise);
  90852. };
  90853. // All faces
  90854. for (var face = 0; face < 6; face++) {
  90855. _loop_4(face);
  90856. }
  90857. };
  90858. // All mipmaps up to provided number of images
  90859. for (var i = 0; i < imageData.length; i++) {
  90860. _loop_3(i);
  90861. }
  90862. // Fill remaining mipmaps with black textures.
  90863. if (imageData.length < mipmapsCount) {
  90864. var data = void 0;
  90865. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  90866. var dataLength = size * size * 4;
  90867. switch (texture.type) {
  90868. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  90869. data = new Uint8Array(dataLength);
  90870. break;
  90871. }
  90872. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  90873. data = new Uint16Array(dataLength);
  90874. break;
  90875. }
  90876. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  90877. data = new Float32Array(dataLength);
  90878. break;
  90879. }
  90880. }
  90881. for (var i = imageData.length; i < mipmapsCount; i++) {
  90882. for (var face = 0; face < 6; face++) {
  90883. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  90884. }
  90885. }
  90886. }
  90887. // Once all done, finishes the cleanup and return
  90888. return Promise.all(promises).then(function () {
  90889. // Release temp RTT.
  90890. if (cubeRtt) {
  90891. engine._releaseFramebufferObjects(cubeRtt);
  90892. cubeRtt._swapAndDie(texture);
  90893. }
  90894. // Release temp Post Process.
  90895. if (rgbdPostProcess) {
  90896. rgbdPostProcess.dispose();
  90897. }
  90898. // Flag internal texture as ready in case they are in use.
  90899. if (generateNonLODTextures) {
  90900. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  90901. texture._lodTextureHigh._texture.isReady = true;
  90902. }
  90903. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  90904. texture._lodTextureMid._texture.isReady = true;
  90905. }
  90906. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  90907. texture._lodTextureLow._texture.isReady = true;
  90908. }
  90909. }
  90910. });
  90911. };
  90912. /**
  90913. * Uploads spherical polynomials information to the texture.
  90914. * @param texture defines the texture we are trying to upload the information to
  90915. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  90916. */
  90917. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  90918. if (info.version !== 1) {
  90919. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  90920. }
  90921. var irradianceInfo = info.irradiance;
  90922. if (!irradianceInfo) {
  90923. return;
  90924. }
  90925. var sp = new BABYLON.SphericalPolynomial();
  90926. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  90927. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  90928. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  90929. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  90930. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  90931. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  90932. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  90933. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  90934. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  90935. texture._sphericalPolynomial = sp;
  90936. };
  90937. /**
  90938. * Magic number identifying the env file.
  90939. */
  90940. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  90941. return EnvironmentTextureTools;
  90942. }());
  90943. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  90944. })(BABYLON || (BABYLON = {}));
  90945. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  90946. var BABYLON;
  90947. (function (BABYLON) {
  90948. /**
  90949. * Implementation of the ENV Texture Loader.
  90950. */
  90951. var ENVTextureLoader = /** @class */ (function () {
  90952. function ENVTextureLoader() {
  90953. /**
  90954. * Defines wether the loader supports cascade loading the different faces.
  90955. */
  90956. this.supportCascades = false;
  90957. }
  90958. /**
  90959. * This returns if the loader support the current file information.
  90960. * @param extension defines the file extension of the file being loaded
  90961. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90962. * @param fallback defines the fallback internal texture if any
  90963. * @param isBase64 defines whether the texture is encoded as a base64
  90964. * @param isBuffer defines whether the texture data are stored as a buffer
  90965. * @returns true if the loader can load the specified file
  90966. */
  90967. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  90968. return extension.indexOf(".env") === 0;
  90969. };
  90970. /**
  90971. * Transform the url before loading if required.
  90972. * @param rootUrl the url of the texture
  90973. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90974. * @returns the transformed texture
  90975. */
  90976. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  90977. return rootUrl;
  90978. };
  90979. /**
  90980. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  90981. * @param rootUrl the url of the texture
  90982. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90983. * @returns the fallback texture
  90984. */
  90985. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  90986. return null;
  90987. };
  90988. /**
  90989. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  90990. * @param data contains the texture data
  90991. * @param texture defines the BabylonJS internal texture
  90992. * @param createPolynomials will be true if polynomials have been requested
  90993. * @param onLoad defines the callback to trigger once the texture is ready
  90994. * @param onError defines the callback to trigger in case of error
  90995. */
  90996. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  90997. if (Array.isArray(data)) {
  90998. return;
  90999. }
  91000. data = data;
  91001. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  91002. if (info) {
  91003. texture.width = info.width;
  91004. texture.height = info.width;
  91005. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  91006. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  91007. texture.isReady = true;
  91008. if (onLoad) {
  91009. onLoad();
  91010. }
  91011. });
  91012. }
  91013. else if (onError) {
  91014. onError("Can not parse the environment file", null);
  91015. }
  91016. };
  91017. /**
  91018. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  91019. * @param data contains the texture data
  91020. * @param texture defines the BabylonJS internal texture
  91021. * @param callback defines the method to call once ready to upload
  91022. */
  91023. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  91024. throw ".env not supported in 2d.";
  91025. };
  91026. return ENVTextureLoader;
  91027. }());
  91028. // Register the loader.
  91029. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  91030. })(BABYLON || (BABYLON = {}));
  91031. //# sourceMappingURL=babylon.envTextureLoader.js.map
  91032. var BABYLON;
  91033. (function (BABYLON) {
  91034. /**
  91035. * Renders a layer on top of an existing scene
  91036. */
  91037. var UtilityLayerRenderer = /** @class */ (function () {
  91038. /**
  91039. * Instantiates a UtilityLayerRenderer
  91040. * @param originalScene the original scene that will be rendered on top of
  91041. */
  91042. function UtilityLayerRenderer(
  91043. /** the original scene that will be rendered on top of */
  91044. originalScene) {
  91045. var _this = this;
  91046. this.originalScene = originalScene;
  91047. this._pointerCaptures = {};
  91048. this._lastPointerEvents = {};
  91049. /**
  91050. * If the utility layer should automatically be rendered on top of existing scene
  91051. */
  91052. this.shouldRender = true;
  91053. /**
  91054. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  91055. */
  91056. this.onlyCheckPointerDownEvents = true;
  91057. /**
  91058. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  91059. */
  91060. this.processAllEvents = false;
  91061. /**
  91062. * Observable raised when the pointer move from the utility layer scene to the main scene
  91063. */
  91064. this.onPointerOutObservable = new BABYLON.Observable();
  91065. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  91066. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  91067. this.utilityLayerScene._allowPostProcessClear = false;
  91068. originalScene.getEngine().scenes.pop();
  91069. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  91070. this.utilityLayerScene.detachControl();
  91071. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  91072. if (!_this.processAllEvents) {
  91073. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  91074. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  91075. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  91076. return;
  91077. }
  91078. }
  91079. var pointerEvent = (prePointerInfo.event);
  91080. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  91081. _this._pointerCaptures[pointerEvent.pointerId] = false;
  91082. return;
  91083. }
  91084. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  91085. if (!prePointerInfo.ray && utilityScenePick) {
  91086. prePointerInfo.ray = utilityScenePick.ray;
  91087. }
  91088. // always fire the prepointer oversvable
  91089. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  91090. // allow every non pointer down event to flow to the utility layer
  91091. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  91092. if (!prePointerInfo.skipOnPointerObservable) {
  91093. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  91094. }
  91095. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  91096. _this._pointerCaptures[pointerEvent.pointerId] = false;
  91097. }
  91098. return;
  91099. }
  91100. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  91101. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  91102. if (utilityScenePick && utilityScenePick.hit) {
  91103. if (!prePointerInfo.skipOnPointerObservable) {
  91104. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  91105. }
  91106. prePointerInfo.skipOnPointerObservable = true;
  91107. }
  91108. }
  91109. else {
  91110. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  91111. var pointerEvent_1 = (prePointerInfo.event);
  91112. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  91113. if (originalScenePick && utilityScenePick) {
  91114. // No pick in utility scene
  91115. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  91116. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  91117. // We touched an utility mesh present in the main scene
  91118. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  91119. prePointerInfo.skipOnPointerObservable = true;
  91120. }
  91121. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  91122. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  91123. }
  91124. }
  91125. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  91126. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  91127. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  91128. // If a previous utility layer set this, do not unset this
  91129. if (!prePointerInfo.skipOnPointerObservable) {
  91130. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  91131. }
  91132. }
  91133. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  91134. // We have a pick in both scenes but main is closer than utility
  91135. // We touched an utility mesh present in the main scene
  91136. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  91137. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  91138. prePointerInfo.skipOnPointerObservable = true;
  91139. }
  91140. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  91141. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  91142. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  91143. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  91144. }
  91145. }
  91146. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  91147. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  91148. }
  91149. }
  91150. }
  91151. });
  91152. // Render directly on top of existing scene without clearing
  91153. this.utilityLayerScene.autoClear = false;
  91154. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  91155. if (_this.shouldRender) {
  91156. _this.render();
  91157. }
  91158. });
  91159. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  91160. _this.dispose();
  91161. });
  91162. this._updateCamera();
  91163. }
  91164. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  91165. /**
  91166. * A shared utility layer that can be used to overlay objects into a scene (Depth map of the previous scene is cleared before drawing on top of it)
  91167. */
  91168. get: function () {
  91169. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  91170. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  91171. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  91172. UtilityLayerRenderer._DefaultUtilityLayer = null;
  91173. });
  91174. }
  91175. return UtilityLayerRenderer._DefaultUtilityLayer;
  91176. },
  91177. enumerable: true,
  91178. configurable: true
  91179. });
  91180. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  91181. /**
  91182. * A shared utility layer that can be used to embed objects into a scene (Depth map of the previous scene is not cleared before drawing on top of it)
  91183. */
  91184. get: function () {
  91185. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  91186. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  91187. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  91188. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  91189. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  91190. });
  91191. }
  91192. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  91193. },
  91194. enumerable: true,
  91195. configurable: true
  91196. });
  91197. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  91198. if (!prePointerInfo.skipOnPointerObservable) {
  91199. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  91200. this._lastPointerEvents[pointerEvent.pointerId] = parseInt(pointerEvent.pointerType);
  91201. }
  91202. };
  91203. /**
  91204. * Renders the utility layers scene on top of the original scene
  91205. */
  91206. UtilityLayerRenderer.prototype.render = function () {
  91207. this._updateCamera();
  91208. if (this.utilityLayerScene.activeCamera) {
  91209. // Set the camera's scene to utility layers scene
  91210. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  91211. var camera = this.utilityLayerScene.activeCamera;
  91212. camera._scene = this.utilityLayerScene;
  91213. if (camera.leftCamera) {
  91214. camera.leftCamera._scene = this.utilityLayerScene;
  91215. }
  91216. if (camera.rightCamera) {
  91217. camera.rightCamera._scene = this.utilityLayerScene;
  91218. }
  91219. this.utilityLayerScene.render(false);
  91220. // Reset camera's scene back to original
  91221. camera._scene = oldScene;
  91222. if (camera.leftCamera) {
  91223. camera.leftCamera._scene = oldScene;
  91224. }
  91225. if (camera.rightCamera) {
  91226. camera.rightCamera._scene = oldScene;
  91227. }
  91228. }
  91229. };
  91230. /**
  91231. * Disposes of the renderer
  91232. */
  91233. UtilityLayerRenderer.prototype.dispose = function () {
  91234. this.onPointerOutObservable.clear();
  91235. if (this._afterRenderObserver) {
  91236. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  91237. }
  91238. if (this._sceneDisposeObserver) {
  91239. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  91240. }
  91241. if (this._originalPointerObserver) {
  91242. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  91243. }
  91244. this.utilityLayerScene.dispose();
  91245. };
  91246. UtilityLayerRenderer.prototype._updateCamera = function () {
  91247. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  91248. };
  91249. UtilityLayerRenderer._DefaultUtilityLayer = null;
  91250. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  91251. return UtilityLayerRenderer;
  91252. }());
  91253. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  91254. })(BABYLON || (BABYLON = {}));
  91255. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  91256. //# sourceMappingURL=babylon.behavior.js.map
  91257. var BABYLON;
  91258. (function (BABYLON) {
  91259. /**
  91260. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  91261. */
  91262. var PointerDragBehavior = /** @class */ (function () {
  91263. /**
  91264. * Creates a pointer drag behavior that can be attached to a mesh
  91265. * @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)
  91266. */
  91267. function PointerDragBehavior(options) {
  91268. /**
  91269. * The maximum tolerated angle between the drag plane and dragging pointer rays to trigger pointer events. Set to 0 to allow any angle (default: 0)
  91270. */
  91271. this.maxDragAngle = 0;
  91272. /**
  91273. * @hidden
  91274. */
  91275. this._useAlternatePickedPointAboveMaxDragAngle = false;
  91276. /**
  91277. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  91278. */
  91279. this.currentDraggingPointerID = -1;
  91280. /**
  91281. * If the behavior is currently in a dragging state
  91282. */
  91283. this.dragging = false;
  91284. /**
  91285. * 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)
  91286. */
  91287. this.dragDeltaRatio = 0.2;
  91288. /**
  91289. * If the drag plane orientation should be updated during the dragging (Default: true)
  91290. */
  91291. this.updateDragPlane = true;
  91292. // Debug mode will display drag planes to help visualize behavior
  91293. this._debugMode = false;
  91294. this._moving = false;
  91295. /**
  91296. * Fires each time the attached mesh is dragged with the pointer
  91297. * * delta between last drag position and current drag position in world space
  91298. * * dragDistance along the drag axis
  91299. * * dragPlaneNormal normal of the current drag plane used during the drag
  91300. * * dragPlanePoint in world space where the drag intersects the drag plane
  91301. */
  91302. this.onDragObservable = new BABYLON.Observable();
  91303. /**
  91304. * Fires each time a drag begins (eg. mouse down on mesh)
  91305. */
  91306. this.onDragStartObservable = new BABYLON.Observable();
  91307. /**
  91308. * Fires each time a drag ends (eg. mouse release after drag)
  91309. */
  91310. this.onDragEndObservable = new BABYLON.Observable();
  91311. /**
  91312. * If the attached mesh should be moved when dragged
  91313. */
  91314. this.moveAttached = true;
  91315. /**
  91316. * If the drag behavior will react to drag events (Default: true)
  91317. */
  91318. this.enabled = true;
  91319. /**
  91320. * If camera controls should be detached during the drag
  91321. */
  91322. this.detachCameraControls = true;
  91323. /**
  91324. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  91325. */
  91326. this.useObjectOrienationForDragging = true;
  91327. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  91328. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  91329. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  91330. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  91331. this._attachedElement = null;
  91332. this._startDragRay = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  91333. this._lastPointerRay = {};
  91334. this._dragDelta = new BABYLON.Vector3();
  91335. // Variables to avoid instantiation in the below method
  91336. this._pointA = new BABYLON.Vector3(0, 0, 0);
  91337. this._pointB = new BABYLON.Vector3(0, 0, 0);
  91338. this._pointC = new BABYLON.Vector3(0, 0, 0);
  91339. this._lineA = new BABYLON.Vector3(0, 0, 0);
  91340. this._lineB = new BABYLON.Vector3(0, 0, 0);
  91341. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  91342. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  91343. this._options = options ? options : {};
  91344. var optionCount = 0;
  91345. if (this._options.dragAxis) {
  91346. optionCount++;
  91347. }
  91348. if (this._options.dragPlaneNormal) {
  91349. optionCount++;
  91350. }
  91351. if (optionCount > 1) {
  91352. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  91353. }
  91354. }
  91355. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  91356. /**
  91357. * The name of the behavior
  91358. */
  91359. get: function () {
  91360. return "PointerDrag";
  91361. },
  91362. enumerable: true,
  91363. configurable: true
  91364. });
  91365. /**
  91366. * Initializes the behavior
  91367. */
  91368. PointerDragBehavior.prototype.init = function () { };
  91369. /**
  91370. * Attaches the drag behavior the passed in mesh
  91371. * @param ownerNode The mesh that will be dragged around once attached
  91372. */
  91373. PointerDragBehavior.prototype.attach = function (ownerNode) {
  91374. var _this = this;
  91375. this._scene = ownerNode.getScene();
  91376. this._attachedNode = ownerNode;
  91377. // Initialize drag plane to not interfere with existing scene
  91378. if (!PointerDragBehavior._planeScene) {
  91379. if (this._debugMode) {
  91380. PointerDragBehavior._planeScene = this._scene;
  91381. }
  91382. else {
  91383. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  91384. PointerDragBehavior._planeScene.detachControl();
  91385. this._scene.getEngine().scenes.pop();
  91386. this._scene.onDisposeObservable.addOnce(function () {
  91387. PointerDragBehavior._planeScene.dispose();
  91388. PointerDragBehavior._planeScene = null;
  91389. });
  91390. }
  91391. }
  91392. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  91393. // State of the drag
  91394. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  91395. var pickPredicate = function (m) {
  91396. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  91397. };
  91398. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  91399. if (!_this.enabled) {
  91400. return;
  91401. }
  91402. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  91403. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  91404. _this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  91405. }
  91406. }
  91407. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  91408. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  91409. _this.releaseDrag();
  91410. }
  91411. }
  91412. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  91413. var pointerId = pointerInfo.event.pointerId;
  91414. // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag()
  91415. if (!_this._lastPointerRay[pointerId]) {
  91416. _this._lastPointerRay[pointerId] = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  91417. }
  91418. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  91419. _this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin);
  91420. _this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction);
  91421. if (_this.currentDraggingPointerID == pointerId && _this.dragging) {
  91422. _this._moveDrag(pointerInfo.pickInfo.ray);
  91423. }
  91424. }
  91425. }
  91426. });
  91427. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  91428. if (_this._moving && _this.moveAttached) {
  91429. // Slowly move mesh to avoid jitter
  91430. _this._targetPosition.subtractToRef(_this._attachedNode.absolutePosition, _this._tmpVector);
  91431. _this._tmpVector.scaleInPlace(_this.dragDeltaRatio);
  91432. _this._attachedNode.getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  91433. _this._attachedNode.setAbsolutePosition(_this._tmpVector);
  91434. }
  91435. });
  91436. };
  91437. PointerDragBehavior.prototype.releaseDrag = function () {
  91438. this.dragging = false;
  91439. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  91440. this.currentDraggingPointerID = -1;
  91441. this._moving = false;
  91442. // Reattach camera controls
  91443. if (this.detachCameraControls && this._attachedElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  91444. this._scene.activeCamera.attachControl(this._attachedElement, true);
  91445. }
  91446. };
  91447. /**
  91448. * Simulates the start of a pointer drag event on the behavior
  91449. * @param pointerId pointerID of the pointer that should be simulated (Default: 1 for mouse pointer)
  91450. * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh)
  91451. * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position)
  91452. */
  91453. PointerDragBehavior.prototype.startDrag = function (pointerId, fromRay, startPickedPoint) {
  91454. if (pointerId === void 0) { pointerId = 1; }
  91455. this._startDrag(pointerId, fromRay, startPickedPoint);
  91456. if (this._lastPointerRay[pointerId]) {
  91457. // if there was a last pointer ray drag the object there
  91458. this._moveDrag(this._lastPointerRay[pointerId]);
  91459. }
  91460. };
  91461. PointerDragBehavior.prototype._startDrag = function (pointerId, fromRay, startPickedPoint) {
  91462. if (pointerId === void 0) { pointerId = 1; }
  91463. if (!this._scene.activeCamera || this.dragging || !this._attachedNode) {
  91464. return;
  91465. }
  91466. // Create start ray from the camera to the object
  91467. if (fromRay) {
  91468. this._startDragRay.direction.copyFrom(fromRay.direction);
  91469. this._startDragRay.origin.copyFrom(fromRay.origin);
  91470. }
  91471. else {
  91472. this._startDragRay.origin.copyFrom(this._scene.activeCamera.position);
  91473. this._attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector);
  91474. this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction);
  91475. }
  91476. this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector);
  91477. var pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay);
  91478. if (pickedPoint) {
  91479. this.dragging = true;
  91480. this.currentDraggingPointerID = 1;
  91481. this.lastDragPosition.copyFrom(pickedPoint);
  91482. this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID });
  91483. this._targetPosition.copyFrom(this._attachedNode.absolutePosition);
  91484. // Detatch camera controls
  91485. if (this.detachCameraControls && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  91486. if (this._scene.activeCamera.inputs.attachedElement) {
  91487. this._attachedElement = this._scene.activeCamera.inputs.attachedElement;
  91488. this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement);
  91489. }
  91490. else {
  91491. this._attachedElement = null;
  91492. }
  91493. }
  91494. }
  91495. };
  91496. PointerDragBehavior.prototype._moveDrag = function (ray) {
  91497. this._moving = true;
  91498. var pickedPoint = this._pickWithRayOnDragPlane(ray);
  91499. if (pickedPoint) {
  91500. if (this.updateDragPlane) {
  91501. this._updateDragPlanePosition(ray, pickedPoint);
  91502. }
  91503. var dragLength = 0;
  91504. // depending on the drag mode option drag accordingly
  91505. if (this._options.dragAxis) {
  91506. // Convert local drag axis to world
  91507. BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis);
  91508. // Project delta drag from the drag plane onto the drag axis
  91509. pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);
  91510. dragLength = BABYLON.Vector3.Dot(this._tmpVector, this._worldDragAxis);
  91511. this._worldDragAxis.scaleToRef(dragLength, this._dragDelta);
  91512. }
  91513. else {
  91514. dragLength = this._dragDelta.length();
  91515. pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta);
  91516. }
  91517. this._targetPosition.addInPlace(this._dragDelta);
  91518. this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: this._dragDelta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID });
  91519. this.lastDragPosition.copyFrom(pickedPoint);
  91520. }
  91521. };
  91522. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  91523. var _this = this;
  91524. if (!ray) {
  91525. return null;
  91526. }
  91527. // Calculate angle between plane normal and ray
  91528. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  91529. // Correct if ray is casted from oposite side
  91530. if (angle > Math.PI / 2) {
  91531. angle = Math.PI - angle;
  91532. }
  91533. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  91534. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  91535. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  91536. // Invert ray direction along the towards object axis
  91537. this._tmpVector.copyFrom(ray.direction);
  91538. this._attachedNode.absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  91539. this._alternatePickedPoint.normalize();
  91540. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  91541. this._tmpVector.addInPlace(this._alternatePickedPoint);
  91542. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  91543. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  91544. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  91545. this._alternatePickedPoint.addInPlace(this._tmpVector);
  91546. this._alternatePickedPoint.addInPlace(this._attachedNode.absolutePosition);
  91547. return this._alternatePickedPoint;
  91548. }
  91549. else {
  91550. return null;
  91551. }
  91552. }
  91553. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  91554. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  91555. return pickResult.pickedPoint;
  91556. }
  91557. else {
  91558. return null;
  91559. }
  91560. };
  91561. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  91562. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  91563. this._pointA.copyFrom(dragPlanePosition);
  91564. if (this._options.dragAxis) {
  91565. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  91566. // Calculate plane normal in direction of camera but perpendicular to drag axis
  91567. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  91568. ray.origin.subtractToRef(this._pointA, this._pointC);
  91569. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  91570. // Get perpendicular line from direction to camera and drag axis
  91571. this._pointB.subtractToRef(this._pointA, this._lineA);
  91572. this._pointC.subtractToRef(this._pointA, this._lineB);
  91573. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  91574. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  91575. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  91576. this._lookAt.normalize();
  91577. this._dragPlane.position.copyFrom(this._pointA);
  91578. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  91579. this._dragPlane.lookAt(this._lookAt);
  91580. }
  91581. else if (this._options.dragPlaneNormal) {
  91582. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  91583. this._dragPlane.position.copyFrom(this._pointA);
  91584. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  91585. this._dragPlane.lookAt(this._lookAt);
  91586. }
  91587. else {
  91588. this._dragPlane.position.copyFrom(this._pointA);
  91589. this._dragPlane.lookAt(ray.origin);
  91590. }
  91591. this._dragPlane.computeWorldMatrix(true);
  91592. };
  91593. /**
  91594. * Detaches the behavior from the mesh
  91595. */
  91596. PointerDragBehavior.prototype.detach = function () {
  91597. if (this._pointerObserver) {
  91598. this._scene.onPointerObservable.remove(this._pointerObserver);
  91599. }
  91600. if (this._beforeRenderObserver) {
  91601. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  91602. }
  91603. };
  91604. return PointerDragBehavior;
  91605. }());
  91606. BABYLON.PointerDragBehavior = PointerDragBehavior;
  91607. })(BABYLON || (BABYLON = {}));
  91608. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  91609. var BABYLON;
  91610. (function (BABYLON) {
  91611. /**
  91612. * A behavior that when attached to a mesh will allow the mesh to be scaled
  91613. */
  91614. var MultiPointerScaleBehavior = /** @class */ (function () {
  91615. function MultiPointerScaleBehavior() {
  91616. this._startDistance = 0;
  91617. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  91618. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  91619. this._sceneRenderObserver = null;
  91620. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  91621. this._dragBehaviorA.moveAttached = false;
  91622. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  91623. this._dragBehaviorB.moveAttached = false;
  91624. }
  91625. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  91626. /**
  91627. * The name of the behavior
  91628. */
  91629. get: function () {
  91630. return "MultiPointerScale";
  91631. },
  91632. enumerable: true,
  91633. configurable: true
  91634. });
  91635. /**
  91636. * Initializes the behavior
  91637. */
  91638. MultiPointerScaleBehavior.prototype.init = function () { };
  91639. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  91640. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  91641. };
  91642. /**
  91643. * Attaches the scale behavior the passed in mesh
  91644. * @param ownerNode The mesh that will be scaled around once attached
  91645. */
  91646. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  91647. var _this = this;
  91648. this._ownerNode = ownerNode;
  91649. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  91650. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  91651. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  91652. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  91653. _this._dragBehaviorA.releaseDrag();
  91654. }
  91655. else {
  91656. _this._initialScale.copyFrom(ownerNode.scaling);
  91657. _this._startDistance = _this._getCurrentDistance();
  91658. }
  91659. }
  91660. });
  91661. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  91662. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  91663. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  91664. _this._dragBehaviorB.releaseDrag();
  91665. }
  91666. else {
  91667. _this._initialScale.copyFrom(ownerNode.scaling);
  91668. _this._startDistance = _this._getCurrentDistance();
  91669. }
  91670. }
  91671. });
  91672. // Once both drag behaviors are active scale based on the distance between the two pointers
  91673. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  91674. behavior.onDragObservable.add(function () {
  91675. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  91676. var ratio = _this._getCurrentDistance() / _this._startDistance;
  91677. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  91678. }
  91679. });
  91680. });
  91681. ownerNode.addBehavior(this._dragBehaviorA);
  91682. ownerNode.addBehavior(this._dragBehaviorB);
  91683. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  91684. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  91685. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  91686. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  91687. if (change.length() > 0.01) {
  91688. ownerNode.scaling.addInPlace(change);
  91689. }
  91690. }
  91691. });
  91692. };
  91693. /**
  91694. * Detaches the behavior from the mesh
  91695. */
  91696. MultiPointerScaleBehavior.prototype.detach = function () {
  91697. var _this = this;
  91698. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  91699. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  91700. behavior.onDragStartObservable.clear();
  91701. behavior.onDragObservable.clear();
  91702. _this._ownerNode.removeBehavior(behavior);
  91703. });
  91704. };
  91705. return MultiPointerScaleBehavior;
  91706. }());
  91707. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  91708. })(BABYLON || (BABYLON = {}));
  91709. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  91710. var BABYLON;
  91711. (function (BABYLON) {
  91712. /**
  91713. * 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
  91714. */
  91715. var SixDofDragBehavior = /** @class */ (function () {
  91716. function SixDofDragBehavior() {
  91717. this._sceneRenderObserver = null;
  91718. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  91719. this._moving = false;
  91720. this._startingOrientation = new BABYLON.Quaternion();
  91721. /**
  91722. * How much faster the object should move when the controller is moving towards it. This is useful to bring objects that are far away from the user to them faster. Set this to 0 to avoid any speed increase. (Default: 3)
  91723. */
  91724. this.zDragFactor = 3;
  91725. /**
  91726. * If the behavior is currently in a dragging state
  91727. */
  91728. this.dragging = false;
  91729. /**
  91730. * 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)
  91731. */
  91732. this.dragDeltaRatio = 0.2;
  91733. /**
  91734. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  91735. */
  91736. this.currentDraggingPointerID = -1;
  91737. /**
  91738. * If camera controls should be detached during the drag
  91739. */
  91740. this.detachCameraControls = true;
  91741. }
  91742. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  91743. /**
  91744. * The name of the behavior
  91745. */
  91746. get: function () {
  91747. return "SixDofDrag";
  91748. },
  91749. enumerable: true,
  91750. configurable: true
  91751. });
  91752. /**
  91753. * Initializes the behavior
  91754. */
  91755. SixDofDragBehavior.prototype.init = function () { };
  91756. /**
  91757. * Attaches the scale behavior the passed in mesh
  91758. * @param ownerNode The mesh that will be scaled around once attached
  91759. */
  91760. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  91761. var _this = this;
  91762. this._ownerNode = ownerNode;
  91763. this._scene = this._ownerNode.getScene();
  91764. if (!SixDofDragBehavior._virtualScene) {
  91765. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  91766. this._scene.getEngine().scenes.pop();
  91767. }
  91768. var pickedMesh = null;
  91769. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  91770. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  91771. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  91772. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  91773. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  91774. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  91775. var pickPredicate = function (m) {
  91776. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  91777. };
  91778. var attachedElement = null;
  91779. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  91780. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  91781. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  91782. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  91783. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  91784. }
  91785. pickedMesh = _this._ownerNode;
  91786. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  91787. // Set position and orientation of the controller
  91788. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  91789. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  91790. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  91791. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  91792. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  91793. if (!pickedMesh.rotationQuaternion) {
  91794. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  91795. }
  91796. var oldParent = pickedMesh.parent;
  91797. pickedMesh.setParent(null);
  91798. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  91799. pickedMesh.setParent(oldParent);
  91800. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  91801. // Update state
  91802. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  91803. _this.dragging = true;
  91804. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  91805. // Detatch camera controls
  91806. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  91807. if (_this._scene.activeCamera.inputs.attachedElement) {
  91808. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  91809. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  91810. }
  91811. else {
  91812. attachedElement = null;
  91813. }
  91814. }
  91815. }
  91816. }
  91817. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  91818. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  91819. _this.dragging = false;
  91820. _this._moving = false;
  91821. _this.currentDraggingPointerID = -1;
  91822. pickedMesh = null;
  91823. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  91824. // Reattach camera controls
  91825. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  91826. _this._scene.activeCamera.attachControl(attachedElement, true);
  91827. }
  91828. }
  91829. }
  91830. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  91831. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  91832. var zDragFactor = _this.zDragFactor;
  91833. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  91834. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  91835. zDragFactor = 0;
  91836. }
  91837. // Calculate controller drag distance in controller space
  91838. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  91839. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  91840. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  91841. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  91842. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  91843. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  91844. if (_this._virtualDragMesh.position.z < 0) {
  91845. _this._virtualDragMesh.position.z = 0;
  91846. }
  91847. // Update the controller position
  91848. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  91849. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  91850. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  91851. // Move the virtualObjectsPosition into the picked mesh's space if needed
  91852. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  91853. if (pickedMesh.parent) {
  91854. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  91855. }
  91856. if (!_this._moving) {
  91857. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  91858. }
  91859. _this._moving = true;
  91860. }
  91861. }
  91862. });
  91863. var tmpQuaternion = new BABYLON.Quaternion();
  91864. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  91865. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  91866. if (_this.dragging && _this._moving && pickedMesh) {
  91867. // Slowly move mesh to avoid jitter
  91868. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  91869. // Get change in rotation
  91870. tmpQuaternion.copyFrom(_this._startingOrientation);
  91871. tmpQuaternion.x = -tmpQuaternion.x;
  91872. tmpQuaternion.y = -tmpQuaternion.y;
  91873. tmpQuaternion.z = -tmpQuaternion.z;
  91874. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  91875. // Convert change in rotation to only y axis rotation
  91876. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  91877. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  91878. // Slowly move mesh to avoid jitter
  91879. var oldParent = pickedMesh.parent;
  91880. pickedMesh.setParent(null);
  91881. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  91882. pickedMesh.setParent(oldParent);
  91883. }
  91884. });
  91885. };
  91886. /**
  91887. * Detaches the behavior from the mesh
  91888. */
  91889. SixDofDragBehavior.prototype.detach = function () {
  91890. if (this._scene) {
  91891. this._scene.onPointerObservable.remove(this._pointerObserver);
  91892. }
  91893. if (this._ownerNode) {
  91894. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  91895. }
  91896. if (this._virtualOriginMesh) {
  91897. this._virtualOriginMesh.dispose();
  91898. }
  91899. if (this._virtualDragMesh) {
  91900. this._virtualDragMesh.dispose();
  91901. }
  91902. };
  91903. return SixDofDragBehavior;
  91904. }());
  91905. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  91906. })(BABYLON || (BABYLON = {}));
  91907. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  91908. var BABYLON;
  91909. (function (BABYLON) {
  91910. /**
  91911. * @hidden
  91912. */
  91913. var FaceDirectionInfo = /** @class */ (function () {
  91914. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  91915. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  91916. if (diff === void 0) { diff = 0; }
  91917. if (ignore === void 0) { ignore = false; }
  91918. this.direction = direction;
  91919. this.rotatedDirection = rotatedDirection;
  91920. this.diff = diff;
  91921. this.ignore = ignore;
  91922. }
  91923. return FaceDirectionInfo;
  91924. }());
  91925. /**
  91926. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  91927. */
  91928. var AttachToBoxBehavior = /** @class */ (function () {
  91929. /**
  91930. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  91931. * @param ui The transform node that should be attched to the mesh
  91932. */
  91933. function AttachToBoxBehavior(ui) {
  91934. this.ui = ui;
  91935. /**
  91936. * The name of the behavior
  91937. */
  91938. this.name = "AttachToBoxBehavior";
  91939. /**
  91940. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  91941. */
  91942. this.distanceAwayFromFace = 0.15;
  91943. /**
  91944. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  91945. */
  91946. this.distanceAwayFromBottomOfFace = 0.15;
  91947. this._faceVectors = [new FaceDirectionInfo(BABYLON.Vector3.Up()), new FaceDirectionInfo(BABYLON.Vector3.Down()), new FaceDirectionInfo(BABYLON.Vector3.Left()), new FaceDirectionInfo(BABYLON.Vector3.Right()), new FaceDirectionInfo(BABYLON.Vector3.Forward()), new FaceDirectionInfo(BABYLON.Vector3.Forward().scaleInPlace(-1))];
  91948. this._tmpMatrix = new BABYLON.Matrix();
  91949. this._tmpVector = new BABYLON.Vector3();
  91950. this._zeroVector = BABYLON.Vector3.Zero();
  91951. this._lookAtTmpMatrix = new BABYLON.Matrix();
  91952. /* Does nothing */
  91953. }
  91954. /**
  91955. * Initializes the behavior
  91956. */
  91957. AttachToBoxBehavior.prototype.init = function () {
  91958. /* Does nothing */
  91959. };
  91960. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  91961. var _this = this;
  91962. // Go over each face and calculate the angle between the face's normal and targetDirection
  91963. this._faceVectors.forEach(function (v) {
  91964. if (!_this._target.rotationQuaternion) {
  91965. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  91966. }
  91967. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  91968. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  91969. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  91970. });
  91971. // Return the face information of the one with the normal closeset to target direction
  91972. return this._faceVectors.reduce(function (min, p) {
  91973. if (min.ignore) {
  91974. return p;
  91975. }
  91976. else if (p.ignore) {
  91977. return min;
  91978. }
  91979. else {
  91980. return min.diff < p.diff ? min : p;
  91981. }
  91982. }, this._faceVectors[0]);
  91983. };
  91984. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  91985. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  91986. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  91987. this._lookAtTmpMatrix.invert();
  91988. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  91989. };
  91990. /**
  91991. * Attaches the AttachToBoxBehavior to the passed in mesh
  91992. * @param target The mesh that the specified node will be attached to
  91993. */
  91994. AttachToBoxBehavior.prototype.attach = function (target) {
  91995. var _this = this;
  91996. this._target = target;
  91997. this._scene = this._target.getScene();
  91998. // Every frame, update the app bars position
  91999. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  92000. if (!_this._scene.activeCamera) {
  92001. return;
  92002. }
  92003. // Find the face closest to the cameras position
  92004. var cameraPos = _this._scene.activeCamera.position;
  92005. if (_this._scene.activeCamera.devicePosition) {
  92006. cameraPos = _this._scene.activeCamera.devicePosition;
  92007. }
  92008. var facing = _this._closestFace(cameraPos.subtract(target.position));
  92009. if (_this._scene.activeCamera.leftCamera) {
  92010. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  92011. }
  92012. else {
  92013. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  92014. }
  92015. // Get camera up direction
  92016. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  92017. // Ignore faces to not select a parrelel face for the up vector of the UI
  92018. _this._faceVectors.forEach(function (v) {
  92019. if (facing.direction.x && v.direction.x) {
  92020. v.ignore = true;
  92021. }
  92022. if (facing.direction.y && v.direction.y) {
  92023. v.ignore = true;
  92024. }
  92025. if (facing.direction.z && v.direction.z) {
  92026. v.ignore = true;
  92027. }
  92028. });
  92029. var facingUp = _this._closestFace(_this._tmpVector);
  92030. // Unignore faces
  92031. _this._faceVectors.forEach(function (v) {
  92032. v.ignore = false;
  92033. });
  92034. // Position the app bar on that face
  92035. _this.ui.position.copyFrom(target.position);
  92036. if (facing.direction.x) {
  92037. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  92038. _this.ui.position.addInPlace(_this._tmpVector);
  92039. }
  92040. if (facing.direction.y) {
  92041. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  92042. _this.ui.position.addInPlace(_this._tmpVector);
  92043. }
  92044. if (facing.direction.z) {
  92045. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  92046. _this.ui.position.addInPlace(_this._tmpVector);
  92047. }
  92048. // Rotate to be oriented properly to the camera
  92049. if (!_this.ui.rotationQuaternion) {
  92050. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  92051. }
  92052. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  92053. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  92054. // Place ui the correct distance from the bottom of the mesh
  92055. if (facingUp.direction.x) {
  92056. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  92057. }
  92058. if (facingUp.direction.y) {
  92059. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  92060. }
  92061. if (facingUp.direction.z) {
  92062. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  92063. }
  92064. _this.ui.position.addInPlace(_this._tmpVector);
  92065. });
  92066. };
  92067. /**
  92068. * Detaches the behavior from the mesh
  92069. */
  92070. AttachToBoxBehavior.prototype.detach = function () {
  92071. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  92072. };
  92073. return AttachToBoxBehavior;
  92074. }());
  92075. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  92076. })(BABYLON || (BABYLON = {}));
  92077. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  92078. var BABYLON;
  92079. (function (BABYLON) {
  92080. /**
  92081. * A behavior that when attached to a mesh will allow the mesh to fade in and out
  92082. */
  92083. var FadeInOutBehavior = /** @class */ (function () {
  92084. /**
  92085. * Instatiates the FadeInOutBehavior
  92086. */
  92087. function FadeInOutBehavior() {
  92088. var _this = this;
  92089. /**
  92090. * Time in milliseconds to delay before fading in (Default: 0)
  92091. */
  92092. this.delay = 0;
  92093. /**
  92094. * Time in milliseconds for the mesh to fade in (Default: 300)
  92095. */
  92096. this.fadeInTime = 300;
  92097. this._millisecondsPerFrame = 1000 / 60;
  92098. this._hovered = false;
  92099. this._hoverValue = 0;
  92100. this._ownerNode = null;
  92101. this._update = function () {
  92102. if (_this._ownerNode) {
  92103. _this._hoverValue += _this._hovered ? _this._millisecondsPerFrame : -_this._millisecondsPerFrame;
  92104. _this._setAllVisibility(_this._ownerNode, (_this._hoverValue - _this.delay) / _this.fadeInTime);
  92105. if (_this._ownerNode.visibility > 1) {
  92106. _this._setAllVisibility(_this._ownerNode, 1);
  92107. _this._hoverValue = _this.fadeInTime + _this.delay;
  92108. return;
  92109. }
  92110. else if (_this._ownerNode.visibility < 0) {
  92111. _this._setAllVisibility(_this._ownerNode, 0);
  92112. if (_this._hoverValue < 0) {
  92113. _this._hoverValue = 0;
  92114. return;
  92115. }
  92116. }
  92117. setTimeout(_this._update, _this._millisecondsPerFrame);
  92118. }
  92119. };
  92120. }
  92121. Object.defineProperty(FadeInOutBehavior.prototype, "name", {
  92122. /**
  92123. * The name of the behavior
  92124. */
  92125. get: function () {
  92126. return "FadeInOut";
  92127. },
  92128. enumerable: true,
  92129. configurable: true
  92130. });
  92131. /**
  92132. * Initializes the behavior
  92133. */
  92134. FadeInOutBehavior.prototype.init = function () {
  92135. };
  92136. /**
  92137. * Attaches the fade behavior on the passed in mesh
  92138. * @param ownerNode The mesh that will be faded in/out once attached
  92139. */
  92140. FadeInOutBehavior.prototype.attach = function (ownerNode) {
  92141. this._ownerNode = ownerNode;
  92142. this._setAllVisibility(this._ownerNode, 0);
  92143. };
  92144. /**
  92145. * Detaches the behavior from the mesh
  92146. */
  92147. FadeInOutBehavior.prototype.detach = function () {
  92148. this._ownerNode = null;
  92149. };
  92150. /**
  92151. * Triggers the mesh to begin fading in or out
  92152. * @param value if the object should fade in or out (true to fade in)
  92153. */
  92154. FadeInOutBehavior.prototype.fadeIn = function (value) {
  92155. this._hovered = value;
  92156. this._update();
  92157. };
  92158. FadeInOutBehavior.prototype._setAllVisibility = function (mesh, value) {
  92159. var _this = this;
  92160. mesh.visibility = value;
  92161. mesh.getChildMeshes().forEach(function (c) {
  92162. _this._setAllVisibility(c, value);
  92163. });
  92164. };
  92165. return FadeInOutBehavior;
  92166. }());
  92167. BABYLON.FadeInOutBehavior = FadeInOutBehavior;
  92168. })(BABYLON || (BABYLON = {}));
  92169. //# sourceMappingURL=babylon.fadeInOutBehavior.js.map
  92170. var BABYLON;
  92171. (function (BABYLON) {
  92172. /**
  92173. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  92174. */
  92175. var Gizmo = /** @class */ (function () {
  92176. /**
  92177. * Creates a gizmo
  92178. * @param gizmoLayer The utility layer the gizmo will be added to
  92179. */
  92180. function Gizmo(
  92181. /** The utility layer the gizmo will be added to */
  92182. gizmoLayer) {
  92183. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  92184. var _this = this;
  92185. this.gizmoLayer = gizmoLayer;
  92186. /**
  92187. * Ratio for the scale of the gizmo (Default: 1)
  92188. */
  92189. this.scaleRatio = 1;
  92190. this._tmpMatrix = new BABYLON.Matrix();
  92191. /**
  92192. * If a custom mesh has been set (Default: false)
  92193. */
  92194. this._customMeshSet = false;
  92195. /**
  92196. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  92197. */
  92198. this.updateGizmoRotationToMatchAttachedMesh = true;
  92199. /**
  92200. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  92201. */
  92202. this.updateGizmoPositionToMatchAttachedMesh = true;
  92203. /**
  92204. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  92205. */
  92206. this._updateScale = true;
  92207. this._interactionsEnabled = true;
  92208. this._tempVector = new BABYLON.Vector3();
  92209. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  92210. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  92211. _this._update();
  92212. });
  92213. this.attachedMesh = null;
  92214. }
  92215. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  92216. /**
  92217. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  92218. * * When set, interactions will be enabled
  92219. */
  92220. get: function () {
  92221. return this._attachedMesh;
  92222. },
  92223. set: function (value) {
  92224. this._attachedMesh = value;
  92225. this._rootMesh.setEnabled(value ? true : false);
  92226. this._attachedMeshChanged(value);
  92227. },
  92228. enumerable: true,
  92229. configurable: true
  92230. });
  92231. /**
  92232. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  92233. * @param mesh The mesh to replace the default mesh of the gizmo
  92234. */
  92235. Gizmo.prototype.setCustomMesh = function (mesh) {
  92236. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  92237. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  92238. }
  92239. this._rootMesh.getChildMeshes().forEach(function (c) {
  92240. c.dispose();
  92241. });
  92242. mesh.parent = this._rootMesh;
  92243. this._customMeshSet = true;
  92244. };
  92245. Gizmo.prototype._attachedMeshChanged = function (value) {
  92246. };
  92247. /**
  92248. * @hidden
  92249. * Updates the gizmo to match the attached mesh's position/rotation
  92250. */
  92251. Gizmo.prototype._update = function () {
  92252. if (this.attachedMesh) {
  92253. if (this.updateGizmoRotationToMatchAttachedMesh) {
  92254. if (!this._rootMesh.rotationQuaternion) {
  92255. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  92256. }
  92257. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  92258. this._tempVector.copyFrom(this.attachedMesh.scaling);
  92259. if (this.attachedMesh.scaling.x < 0) {
  92260. this.attachedMesh.scaling.x *= -1;
  92261. }
  92262. if (this.attachedMesh.scaling.y < 0) {
  92263. this.attachedMesh.scaling.y *= -1;
  92264. }
  92265. if (this.attachedMesh.scaling.z < 0) {
  92266. this.attachedMesh.scaling.z *= -1;
  92267. }
  92268. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  92269. this.attachedMesh.scaling.copyFrom(this._tempVector);
  92270. this.attachedMesh.computeWorldMatrix();
  92271. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  92272. }
  92273. else if (this._rootMesh.rotationQuaternion) {
  92274. this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);
  92275. }
  92276. if (this.updateGizmoPositionToMatchAttachedMesh) {
  92277. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  92278. }
  92279. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  92280. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;
  92281. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  92282. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  92283. }
  92284. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  92285. var dist = this._tempVector.length() * this.scaleRatio;
  92286. this._rootMesh.scaling.set(dist, dist, dist);
  92287. }
  92288. }
  92289. };
  92290. /**
  92291. * Disposes of the gizmo
  92292. */
  92293. Gizmo.prototype.dispose = function () {
  92294. this._rootMesh.dispose();
  92295. if (this._beforeRenderObserver) {
  92296. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  92297. }
  92298. };
  92299. return Gizmo;
  92300. }());
  92301. BABYLON.Gizmo = Gizmo;
  92302. })(BABYLON || (BABYLON = {}));
  92303. //# sourceMappingURL=babylon.gizmo.js.map
  92304. var BABYLON;
  92305. (function (BABYLON) {
  92306. /**
  92307. * Single axis drag gizmo
  92308. */
  92309. var AxisDragGizmo = /** @class */ (function (_super) {
  92310. __extends(AxisDragGizmo, _super);
  92311. /**
  92312. * Creates an AxisDragGizmo
  92313. * @param gizmoLayer The utility layer the gizmo will be added to
  92314. * @param dragAxis The axis which the gizmo will be able to drag on
  92315. * @param color The color of the gizmo
  92316. */
  92317. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  92318. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  92319. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  92320. var _this = _super.call(this, gizmoLayer) || this;
  92321. _this._pointerObserver = null;
  92322. /**
  92323. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  92324. */
  92325. _this.snapDistance = 0;
  92326. /**
  92327. * Event that fires each time the gizmo snaps to a new location.
  92328. * * snapDistance is the the change in distance
  92329. */
  92330. _this.onSnapObservable = new BABYLON.Observable();
  92331. // Create Material
  92332. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  92333. coloredMaterial.disableLighting = true;
  92334. coloredMaterial.emissiveColor = color;
  92335. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  92336. hoverMaterial.disableLighting = true;
  92337. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  92338. // Build mesh on root node
  92339. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  92340. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  92341. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  92342. arrowTail.color = coloredMaterial.emissiveColor;
  92343. arrow.addChild(arrowMesh);
  92344. arrow.addChild(arrowTail);
  92345. // Position arrow pointing in its drag axis
  92346. arrowMesh.scaling.scaleInPlace(0.05);
  92347. arrowMesh.material = coloredMaterial;
  92348. arrowMesh.rotation.x = Math.PI / 2;
  92349. arrowMesh.position.z += 0.3;
  92350. arrowTail.scaling.scaleInPlace(0.26);
  92351. arrowTail.rotation.x = Math.PI / 2;
  92352. arrowTail.material = coloredMaterial;
  92353. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  92354. arrow.scaling.scaleInPlace(1 / 3);
  92355. _this._rootMesh.addChild(arrow);
  92356. var currentSnapDragDistance = 0;
  92357. var tmpVector = new BABYLON.Vector3();
  92358. var tmpSnapEvent = { snapDistance: 0 };
  92359. // Add drag behavior to handle events when the gizmo is dragged
  92360. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  92361. _this.dragBehavior.moveAttached = false;
  92362. _this._rootMesh.addBehavior(_this.dragBehavior);
  92363. var localDelta = new BABYLON.Vector3();
  92364. var tmpMatrix = new BABYLON.Matrix();
  92365. _this.dragBehavior.onDragObservable.add(function (event) {
  92366. if (_this.attachedMesh) {
  92367. // Convert delta to local translation if it has a parent
  92368. if (_this.attachedMesh.parent) {
  92369. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  92370. tmpMatrix.setTranslationFromFloats(0, 0, 0);
  92371. BABYLON.Vector3.TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta);
  92372. }
  92373. else {
  92374. localDelta.copyFrom(event.delta);
  92375. }
  92376. // Snapping logic
  92377. if (_this.snapDistance == 0) {
  92378. _this.attachedMesh.position.addInPlace(localDelta);
  92379. }
  92380. else {
  92381. currentSnapDragDistance += event.dragDistance;
  92382. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  92383. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  92384. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  92385. localDelta.normalizeToRef(tmpVector);
  92386. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  92387. _this.attachedMesh.position.addInPlace(tmpVector);
  92388. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  92389. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  92390. }
  92391. }
  92392. }
  92393. });
  92394. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  92395. if (_this._customMeshSet) {
  92396. return;
  92397. }
  92398. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  92399. var material = isHovered ? hoverMaterial : coloredMaterial;
  92400. _this._rootMesh.getChildMeshes().forEach(function (m) {
  92401. m.material = material;
  92402. if (m.color) {
  92403. m.color = material.emissiveColor;
  92404. }
  92405. });
  92406. });
  92407. return _this;
  92408. }
  92409. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  92410. if (this.dragBehavior) {
  92411. this.dragBehavior.enabled = value ? true : false;
  92412. }
  92413. };
  92414. /**
  92415. * Disposes of the gizmo
  92416. */
  92417. AxisDragGizmo.prototype.dispose = function () {
  92418. this.onSnapObservable.clear();
  92419. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  92420. this.dragBehavior.detach();
  92421. _super.prototype.dispose.call(this);
  92422. };
  92423. return AxisDragGizmo;
  92424. }(BABYLON.Gizmo));
  92425. BABYLON.AxisDragGizmo = AxisDragGizmo;
  92426. })(BABYLON || (BABYLON = {}));
  92427. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  92428. var BABYLON;
  92429. (function (BABYLON) {
  92430. /**
  92431. * Single axis scale gizmo
  92432. */
  92433. var AxisScaleGizmo = /** @class */ (function (_super) {
  92434. __extends(AxisScaleGizmo, _super);
  92435. /**
  92436. * Creates an AxisScaleGizmo
  92437. * @param gizmoLayer The utility layer the gizmo will be added to
  92438. * @param dragAxis The axis which the gizmo will be able to scale on
  92439. * @param color The color of the gizmo
  92440. */
  92441. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  92442. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  92443. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  92444. var _this = _super.call(this, gizmoLayer) || this;
  92445. _this._pointerObserver = null;
  92446. /**
  92447. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  92448. */
  92449. _this.snapDistance = 0;
  92450. /**
  92451. * Event that fires each time the gizmo snaps to a new location.
  92452. * * snapDistance is the the change in distance
  92453. */
  92454. _this.onSnapObservable = new BABYLON.Observable();
  92455. /**
  92456. * If the scaling operation should be done on all axis (default: false)
  92457. */
  92458. _this.uniformScaling = false;
  92459. // Create Material
  92460. _this._coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  92461. _this._coloredMaterial.disableLighting = true;
  92462. _this._coloredMaterial.emissiveColor = color;
  92463. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  92464. hoverMaterial.disableLighting = true;
  92465. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  92466. // Build mesh on root node
  92467. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  92468. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  92469. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  92470. arrowTail.color = _this._coloredMaterial.emissiveColor;
  92471. arrow.addChild(arrowMesh);
  92472. arrow.addChild(arrowTail);
  92473. // Position arrow pointing in its drag axis
  92474. arrowMesh.scaling.scaleInPlace(0.1);
  92475. arrowMesh.material = _this._coloredMaterial;
  92476. arrowMesh.rotation.x = Math.PI / 2;
  92477. arrowMesh.position.z += 0.3;
  92478. arrowTail.scaling.scaleInPlace(0.26);
  92479. arrowTail.rotation.x = Math.PI / 2;
  92480. arrowTail.material = _this._coloredMaterial;
  92481. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  92482. _this._rootMesh.addChild(arrow);
  92483. arrow.scaling.scaleInPlace(1 / 3);
  92484. // Add drag behavior to handle events when the gizmo is dragged
  92485. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  92486. _this.dragBehavior.moveAttached = false;
  92487. _this._rootMesh.addBehavior(_this.dragBehavior);
  92488. var currentSnapDragDistance = 0;
  92489. var tmpVector = new BABYLON.Vector3();
  92490. var tmpSnapEvent = { snapDistance: 0 };
  92491. _this.dragBehavior.onDragObservable.add(function (event) {
  92492. if (_this.attachedMesh) {
  92493. // Snapping logic
  92494. var snapped = false;
  92495. var dragSteps = 0;
  92496. if (_this.uniformScaling) {
  92497. _this.attachedMesh.scaling.normalizeToRef(tmpVector);
  92498. if (tmpVector.y < 0) {
  92499. tmpVector.scaleInPlace(-1);
  92500. }
  92501. }
  92502. else {
  92503. tmpVector.copyFrom(dragAxis);
  92504. }
  92505. if (_this.snapDistance == 0) {
  92506. tmpVector.scaleToRef(event.dragDistance, tmpVector);
  92507. }
  92508. else {
  92509. currentSnapDragDistance += event.dragDistance;
  92510. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  92511. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  92512. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  92513. tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  92514. snapped = true;
  92515. }
  92516. else {
  92517. tmpVector.scaleInPlace(0);
  92518. }
  92519. }
  92520. _this.attachedMesh.scaling.addInPlace(tmpVector);
  92521. if (snapped) {
  92522. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  92523. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  92524. }
  92525. }
  92526. });
  92527. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  92528. if (_this._customMeshSet) {
  92529. return;
  92530. }
  92531. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  92532. var material = isHovered ? hoverMaterial : _this._coloredMaterial;
  92533. _this._rootMesh.getChildMeshes().forEach(function (m) {
  92534. m.material = material;
  92535. if (m.color) {
  92536. m.color = material.emissiveColor;
  92537. }
  92538. });
  92539. });
  92540. return _this;
  92541. }
  92542. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  92543. if (this.dragBehavior) {
  92544. this.dragBehavior.enabled = value ? true : false;
  92545. }
  92546. };
  92547. /**
  92548. * Disposes of the gizmo
  92549. */
  92550. AxisScaleGizmo.prototype.dispose = function () {
  92551. this.onSnapObservable.clear();
  92552. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  92553. this.dragBehavior.detach();
  92554. _super.prototype.dispose.call(this);
  92555. };
  92556. /**
  92557. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  92558. * @param mesh The mesh to replace the default mesh of the gizmo
  92559. * @param useGizmoMaterial If the gizmo's default material should be used (default: false)
  92560. */
  92561. AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) {
  92562. var _this = this;
  92563. if (useGizmoMaterial === void 0) { useGizmoMaterial = false; }
  92564. _super.prototype.setCustomMesh.call(this, mesh);
  92565. if (useGizmoMaterial) {
  92566. this._rootMesh.getChildMeshes().forEach(function (m) {
  92567. m.material = _this._coloredMaterial;
  92568. if (m.color) {
  92569. m.color = _this._coloredMaterial.emissiveColor;
  92570. }
  92571. });
  92572. this._customMeshSet = false;
  92573. }
  92574. };
  92575. return AxisScaleGizmo;
  92576. }(BABYLON.Gizmo));
  92577. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  92578. })(BABYLON || (BABYLON = {}));
  92579. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  92580. var BABYLON;
  92581. (function (BABYLON) {
  92582. /**
  92583. * Single plane rotation gizmo
  92584. */
  92585. var PlaneRotationGizmo = /** @class */ (function (_super) {
  92586. __extends(PlaneRotationGizmo, _super);
  92587. /**
  92588. * Creates a PlaneRotationGizmo
  92589. * @param gizmoLayer The utility layer the gizmo will be added to
  92590. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  92591. * @param color The color of the gizmo
  92592. */
  92593. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  92594. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  92595. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  92596. var _this = _super.call(this, gizmoLayer) || this;
  92597. _this._pointerObserver = null;
  92598. /**
  92599. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  92600. */
  92601. _this.snapDistance = 0;
  92602. /**
  92603. * Event that fires each time the gizmo snaps to a new location.
  92604. * * snapDistance is the the change in distance
  92605. */
  92606. _this.onSnapObservable = new BABYLON.Observable();
  92607. // Create Material
  92608. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  92609. coloredMaterial.disableLighting = true;
  92610. coloredMaterial.emissiveColor = color;
  92611. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  92612. hoverMaterial.disableLighting = true;
  92613. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  92614. // Build mesh on root node
  92615. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  92616. // Create circle out of lines
  92617. var tessellation = 20;
  92618. var radius = 0.8;
  92619. var points = new Array();
  92620. for (var i = 0; i < tessellation; i++) {
  92621. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  92622. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  92623. }
  92624. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  92625. rotationMesh.color = coloredMaterial.emissiveColor;
  92626. // Position arrow pointing in its drag axis
  92627. rotationMesh.scaling.scaleInPlace(0.26);
  92628. rotationMesh.material = coloredMaterial;
  92629. rotationMesh.rotation.x = Math.PI / 2;
  92630. parentMesh.addChild(rotationMesh);
  92631. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  92632. _this._rootMesh.addChild(parentMesh);
  92633. parentMesh.scaling.scaleInPlace(1 / 3);
  92634. // Add drag behavior to handle events when the gizmo is dragged
  92635. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  92636. _this.dragBehavior.moveAttached = false;
  92637. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  92638. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  92639. _this._rootMesh.addBehavior(_this.dragBehavior);
  92640. var lastDragPosition = new BABYLON.Vector3();
  92641. _this.dragBehavior.onDragStartObservable.add(function (e) {
  92642. if (_this.attachedMesh) {
  92643. lastDragPosition.copyFrom(e.dragPlanePoint);
  92644. }
  92645. });
  92646. var rotationMatrix = new BABYLON.Matrix();
  92647. var planeNormalTowardsCamera = new BABYLON.Vector3();
  92648. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  92649. var tmpSnapEvent = { snapDistance: 0 };
  92650. var currentSnapDragDistance = 0;
  92651. var tmpMatrix = new BABYLON.Matrix();
  92652. var tmpVector = new BABYLON.Vector3();
  92653. var amountToRotate = new BABYLON.Quaternion();
  92654. _this.dragBehavior.onDragObservable.add(function (event) {
  92655. if (_this.attachedMesh) {
  92656. if (!_this.attachedMesh.rotationQuaternion) {
  92657. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  92658. }
  92659. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  92660. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.absolutePosition).normalize();
  92661. var originalVector = lastDragPosition.subtract(_this.attachedMesh.absolutePosition).normalize();
  92662. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  92663. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  92664. var angle = Math.atan2(cross.length(), dot);
  92665. planeNormalTowardsCamera.copyFrom(planeNormal);
  92666. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  92667. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  92668. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  92669. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  92670. }
  92671. // Flip up vector depending on which side the camera is on
  92672. if (gizmoLayer.utilityLayerScene.activeCamera) {
  92673. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  92674. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  92675. planeNormalTowardsCamera.scaleInPlace(-1);
  92676. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  92677. }
  92678. }
  92679. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  92680. if (halfCircleSide)
  92681. angle = -angle;
  92682. // Snapping logic
  92683. var snapped = false;
  92684. if (_this.snapDistance != 0) {
  92685. currentSnapDragDistance += angle;
  92686. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  92687. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  92688. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  92689. angle = _this.snapDistance * dragSteps;
  92690. snapped = true;
  92691. }
  92692. else {
  92693. angle = 0;
  92694. }
  92695. }
  92696. // If the mesh has a parent, convert needed world rotation to local rotation
  92697. tmpMatrix.reset();
  92698. if (_this.attachedMesh.parent) {
  92699. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  92700. tmpMatrix.getRotationMatrixToRef(tmpMatrix);
  92701. BABYLON.Vector3.TransformCoordinatesToRef(planeNormalTowardsCamera, tmpMatrix, planeNormalTowardsCamera);
  92702. }
  92703. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  92704. var quaternionCoefficient = Math.sin(angle / 2);
  92705. amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  92706. // If the meshes local scale is inverted (eg. loaded gltf file parent with z scale of -1) the rotation needs to be inverted on the y axis
  92707. if (tmpMatrix.determinant() > 0) {
  92708. amountToRotate.toEulerAnglesToRef(tmpVector);
  92709. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);
  92710. }
  92711. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  92712. // Rotate selected mesh quaternion over fixed axis
  92713. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  92714. }
  92715. else {
  92716. // Rotate selected mesh quaternion over rotated axis
  92717. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  92718. }
  92719. lastDragPosition.copyFrom(event.dragPlanePoint);
  92720. if (snapped) {
  92721. tmpSnapEvent.snapDistance = angle;
  92722. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  92723. }
  92724. }
  92725. });
  92726. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  92727. if (_this._customMeshSet) {
  92728. return;
  92729. }
  92730. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  92731. var material = isHovered ? hoverMaterial : coloredMaterial;
  92732. _this._rootMesh.getChildMeshes().forEach(function (m) {
  92733. m.material = material;
  92734. if (m.color) {
  92735. m.color = material.emissiveColor;
  92736. }
  92737. });
  92738. });
  92739. return _this;
  92740. }
  92741. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  92742. if (this.dragBehavior) {
  92743. this.dragBehavior.enabled = value ? true : false;
  92744. }
  92745. };
  92746. /**
  92747. * Disposes of the gizmo
  92748. */
  92749. PlaneRotationGizmo.prototype.dispose = function () {
  92750. this.onSnapObservable.clear();
  92751. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  92752. this.dragBehavior.detach();
  92753. _super.prototype.dispose.call(this);
  92754. };
  92755. return PlaneRotationGizmo;
  92756. }(BABYLON.Gizmo));
  92757. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  92758. })(BABYLON || (BABYLON = {}));
  92759. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  92760. var BABYLON;
  92761. (function (BABYLON) {
  92762. /**
  92763. * Gizmo that enables dragging a mesh along 3 axis
  92764. */
  92765. var PositionGizmo = /** @class */ (function (_super) {
  92766. __extends(PositionGizmo, _super);
  92767. /**
  92768. * Creates a PositionGizmo
  92769. * @param gizmoLayer The utility layer the gizmo will be added to
  92770. */
  92771. function PositionGizmo(gizmoLayer) {
  92772. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  92773. var _this = _super.call(this, gizmoLayer) || this;
  92774. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  92775. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  92776. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  92777. _this.attachedMesh = null;
  92778. return _this;
  92779. }
  92780. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  92781. set: function (mesh) {
  92782. if (this.xGizmo) {
  92783. this.xGizmo.attachedMesh = mesh;
  92784. this.yGizmo.attachedMesh = mesh;
  92785. this.zGizmo.attachedMesh = mesh;
  92786. }
  92787. },
  92788. enumerable: true,
  92789. configurable: true
  92790. });
  92791. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  92792. get: function () {
  92793. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  92794. },
  92795. set: function (value) {
  92796. if (this.xGizmo) {
  92797. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92798. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92799. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92800. }
  92801. },
  92802. enumerable: true,
  92803. configurable: true
  92804. });
  92805. Object.defineProperty(PositionGizmo.prototype, "snapDistance", {
  92806. get: function () {
  92807. return this.xGizmo.snapDistance;
  92808. },
  92809. /**
  92810. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  92811. */
  92812. set: function (value) {
  92813. if (this.xGizmo) {
  92814. this.xGizmo.snapDistance = value;
  92815. this.yGizmo.snapDistance = value;
  92816. this.zGizmo.snapDistance = value;
  92817. }
  92818. },
  92819. enumerable: true,
  92820. configurable: true
  92821. });
  92822. Object.defineProperty(PositionGizmo.prototype, "scaleRatio", {
  92823. get: function () {
  92824. return this.xGizmo.scaleRatio;
  92825. },
  92826. /**
  92827. * Ratio for the scale of the gizmo (Default: 1)
  92828. */
  92829. set: function (value) {
  92830. if (this.xGizmo) {
  92831. this.xGizmo.scaleRatio = value;
  92832. this.yGizmo.scaleRatio = value;
  92833. this.zGizmo.scaleRatio = value;
  92834. }
  92835. },
  92836. enumerable: true,
  92837. configurable: true
  92838. });
  92839. /**
  92840. * Disposes of the gizmo
  92841. */
  92842. PositionGizmo.prototype.dispose = function () {
  92843. this.xGizmo.dispose();
  92844. this.yGizmo.dispose();
  92845. this.zGizmo.dispose();
  92846. };
  92847. /**
  92848. * CustomMeshes are not supported by this gizmo
  92849. * @param mesh The mesh to replace the default mesh of the gizmo
  92850. */
  92851. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  92852. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)");
  92853. };
  92854. return PositionGizmo;
  92855. }(BABYLON.Gizmo));
  92856. BABYLON.PositionGizmo = PositionGizmo;
  92857. })(BABYLON || (BABYLON = {}));
  92858. //# sourceMappingURL=babylon.positionGizmo.js.map
  92859. var BABYLON;
  92860. (function (BABYLON) {
  92861. /**
  92862. * Gizmo that enables rotating a mesh along 3 axis
  92863. */
  92864. var RotationGizmo = /** @class */ (function (_super) {
  92865. __extends(RotationGizmo, _super);
  92866. /**
  92867. * Creates a RotationGizmo
  92868. * @param gizmoLayer The utility layer the gizmo will be added to
  92869. */
  92870. function RotationGizmo(gizmoLayer) {
  92871. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  92872. var _this = _super.call(this, gizmoLayer) || this;
  92873. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  92874. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  92875. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  92876. _this.attachedMesh = null;
  92877. return _this;
  92878. }
  92879. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  92880. set: function (mesh) {
  92881. if (this.xGizmo) {
  92882. this.xGizmo.attachedMesh = mesh;
  92883. this.yGizmo.attachedMesh = mesh;
  92884. this.zGizmo.attachedMesh = mesh;
  92885. }
  92886. },
  92887. enumerable: true,
  92888. configurable: true
  92889. });
  92890. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  92891. get: function () {
  92892. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  92893. },
  92894. set: function (value) {
  92895. if (this.xGizmo) {
  92896. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92897. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92898. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92899. }
  92900. },
  92901. enumerable: true,
  92902. configurable: true
  92903. });
  92904. Object.defineProperty(RotationGizmo.prototype, "snapDistance", {
  92905. get: function () {
  92906. return this.xGizmo.snapDistance;
  92907. },
  92908. /**
  92909. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  92910. */
  92911. set: function (value) {
  92912. if (this.xGizmo) {
  92913. this.xGizmo.snapDistance = value;
  92914. this.yGizmo.snapDistance = value;
  92915. this.zGizmo.snapDistance = value;
  92916. }
  92917. },
  92918. enumerable: true,
  92919. configurable: true
  92920. });
  92921. Object.defineProperty(RotationGizmo.prototype, "scaleRatio", {
  92922. get: function () {
  92923. return this.xGizmo.scaleRatio;
  92924. },
  92925. /**
  92926. * Ratio for the scale of the gizmo (Default: 1)
  92927. */
  92928. set: function (value) {
  92929. if (this.xGizmo) {
  92930. this.xGizmo.scaleRatio = value;
  92931. this.yGizmo.scaleRatio = value;
  92932. this.zGizmo.scaleRatio = value;
  92933. }
  92934. },
  92935. enumerable: true,
  92936. configurable: true
  92937. });
  92938. /**
  92939. * Disposes of the gizmo
  92940. */
  92941. RotationGizmo.prototype.dispose = function () {
  92942. this.xGizmo.dispose();
  92943. this.yGizmo.dispose();
  92944. this.zGizmo.dispose();
  92945. };
  92946. /**
  92947. * CustomMeshes are not supported by this gizmo
  92948. * @param mesh The mesh to replace the default mesh of the gizmo
  92949. */
  92950. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  92951. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)");
  92952. };
  92953. return RotationGizmo;
  92954. }(BABYLON.Gizmo));
  92955. BABYLON.RotationGizmo = RotationGizmo;
  92956. })(BABYLON || (BABYLON = {}));
  92957. //# sourceMappingURL=babylon.rotationGizmo.js.map
  92958. var BABYLON;
  92959. (function (BABYLON) {
  92960. /**
  92961. * Gizmo that enables scaling a mesh along 3 axis
  92962. */
  92963. var ScaleGizmo = /** @class */ (function (_super) {
  92964. __extends(ScaleGizmo, _super);
  92965. /**
  92966. * Creates a ScaleGizmo
  92967. * @param gizmoLayer The utility layer the gizmo will be added to
  92968. */
  92969. function ScaleGizmo(gizmoLayer) {
  92970. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  92971. var _this = _super.call(this, gizmoLayer) || this;
  92972. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  92973. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  92974. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  92975. // Create uniform scale gizmo
  92976. _this._uniformGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Yellow().scale(0.5), gizmoLayer);
  92977. _this._uniformGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  92978. _this._uniformGizmo.uniformScaling = true;
  92979. var octahedron = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this._uniformGizmo.gizmoLayer.utilityLayerScene);
  92980. octahedron.scaling.scaleInPlace(0.007);
  92981. _this._uniformGizmo.setCustomMesh(octahedron, true);
  92982. _this.attachedMesh = null;
  92983. return _this;
  92984. }
  92985. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  92986. set: function (mesh) {
  92987. if (this.xGizmo) {
  92988. this.xGizmo.attachedMesh = mesh;
  92989. this.yGizmo.attachedMesh = mesh;
  92990. this.zGizmo.attachedMesh = mesh;
  92991. this._uniformGizmo.attachedMesh = mesh;
  92992. }
  92993. },
  92994. enumerable: true,
  92995. configurable: true
  92996. });
  92997. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  92998. get: function () {
  92999. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  93000. },
  93001. set: function (value) {
  93002. if (this.xGizmo) {
  93003. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  93004. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  93005. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  93006. }
  93007. },
  93008. enumerable: true,
  93009. configurable: true
  93010. });
  93011. Object.defineProperty(ScaleGizmo.prototype, "snapDistance", {
  93012. get: function () {
  93013. return this.xGizmo.snapDistance;
  93014. },
  93015. /**
  93016. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  93017. */
  93018. set: function (value) {
  93019. if (this.xGizmo) {
  93020. this.xGizmo.snapDistance = value;
  93021. this.yGizmo.snapDistance = value;
  93022. this.zGizmo.snapDistance = value;
  93023. this._uniformGizmo.snapDistance = value;
  93024. }
  93025. },
  93026. enumerable: true,
  93027. configurable: true
  93028. });
  93029. Object.defineProperty(ScaleGizmo.prototype, "scaleRatio", {
  93030. get: function () {
  93031. return this.xGizmo.scaleRatio;
  93032. },
  93033. /**
  93034. * Ratio for the scale of the gizmo (Default: 1)
  93035. */
  93036. set: function (value) {
  93037. if (this.xGizmo) {
  93038. this.xGizmo.scaleRatio = value;
  93039. this.yGizmo.scaleRatio = value;
  93040. this.zGizmo.scaleRatio = value;
  93041. this._uniformGizmo.scaleRatio = value;
  93042. }
  93043. },
  93044. enumerable: true,
  93045. configurable: true
  93046. });
  93047. /**
  93048. * Disposes of the gizmo
  93049. */
  93050. ScaleGizmo.prototype.dispose = function () {
  93051. this.xGizmo.dispose();
  93052. this.yGizmo.dispose();
  93053. this.zGizmo.dispose();
  93054. this._uniformGizmo.dispose();
  93055. };
  93056. return ScaleGizmo;
  93057. }(BABYLON.Gizmo));
  93058. BABYLON.ScaleGizmo = ScaleGizmo;
  93059. })(BABYLON || (BABYLON = {}));
  93060. //# sourceMappingURL=babylon.scaleGizmo.js.map
  93061. var BABYLON;
  93062. (function (BABYLON) {
  93063. /**
  93064. * Bounding box gizmo
  93065. */
  93066. var BoundingBoxGizmo = /** @class */ (function (_super) {
  93067. __extends(BoundingBoxGizmo, _super);
  93068. /**
  93069. * Creates an BoundingBoxGizmo
  93070. * @param gizmoLayer The utility layer the gizmo will be added to
  93071. * @param color The color of the gizmo
  93072. */
  93073. function BoundingBoxGizmo(color, gizmoLayer) {
  93074. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  93075. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  93076. var _this = _super.call(this, gizmoLayer) || this;
  93077. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  93078. _this._renderObserver = null;
  93079. _this._pointerObserver = null;
  93080. _this._scaleDragSpeed = 0.2;
  93081. _this._tmpQuaternion = new BABYLON.Quaternion();
  93082. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  93083. _this._tmpRotationMatrix = new BABYLON.Matrix();
  93084. /**
  93085. * If child meshes should be ignored when calculating the boudning box. This should be set to true to avoid perf hits with heavily nested meshes (Default: false)
  93086. */
  93087. _this.ignoreChildren = false;
  93088. /**
  93089. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  93090. */
  93091. _this.rotationSphereSize = 0.1;
  93092. /**
  93093. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  93094. */
  93095. _this.scaleBoxSize = 0.1;
  93096. /**
  93097. * 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)
  93098. */
  93099. _this.fixedDragMeshScreenSize = false;
  93100. /**
  93101. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  93102. */
  93103. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  93104. /**
  93105. * Fired when a rotation sphere or scale box is dragged
  93106. */
  93107. _this.onDragStartObservable = new BABYLON.Observable();
  93108. /**
  93109. * Fired when a scale box is dragged
  93110. */
  93111. _this.onScaleBoxDragObservable = new BABYLON.Observable();
  93112. /**
  93113. * Fired when a scale box drag is ended
  93114. */
  93115. _this.onScaleBoxDragEndObservable = new BABYLON.Observable();
  93116. /**
  93117. * Fired when a rotation sphere is dragged
  93118. */
  93119. _this.onRotationSphereDragObservable = new BABYLON.Observable();
  93120. /**
  93121. * Fired when a rotation sphere drag is ended
  93122. */
  93123. _this.onRotationSphereDragEndObservable = new BABYLON.Observable();
  93124. /**
  93125. * Relative bounding box pivot used when scaling the attached mesh. When null object with scale from the opposite corner. 0.5,0.5,0.5 for center and 0.5,0,0.5 for bottom (Default: null)
  93126. */
  93127. _this.scalePivot = null;
  93128. _this._existingMeshScale = new BABYLON.Vector3();
  93129. // Stores the state of the pivot cache (_oldPivotPoint, _pivotTranslation)
  93130. // store/remove pivot point should only be applied during their outermost calls
  93131. _this._pivotCached = 0;
  93132. _this._oldPivotPoint = new BABYLON.Vector3();
  93133. _this._pivotTranslation = new BABYLON.Vector3();
  93134. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  93135. _this._updateScale = false;
  93136. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  93137. // Create Materials
  93138. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  93139. coloredMaterial.disableLighting = true;
  93140. coloredMaterial.emissiveColor = color;
  93141. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  93142. hoverColoredMaterial.disableLighting = true;
  93143. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.3, 0.3, 0.3));
  93144. // Build bounding box out of lines
  93145. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  93146. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  93147. var lines = [];
  93148. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  93149. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  93150. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  93151. 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));
  93152. 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));
  93153. 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));
  93154. 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));
  93155. 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));
  93156. 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));
  93157. 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));
  93158. 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));
  93159. 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));
  93160. lines.forEach(function (l) {
  93161. l.color = color;
  93162. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  93163. l.isPickable = false;
  93164. _this._lineBoundingBox.addChild(l);
  93165. });
  93166. _this._rootMesh.addChild(_this._lineBoundingBox);
  93167. // Create rotation spheres
  93168. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  93169. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  93170. var _loop_1 = function (i_1) {
  93171. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  93172. sphere.rotationQuaternion = new BABYLON.Quaternion();
  93173. sphere.material = coloredMaterial;
  93174. // Drag behavior
  93175. _dragBehavior = new BABYLON.PointerDragBehavior({});
  93176. _dragBehavior.moveAttached = false;
  93177. _dragBehavior.updateDragPlane = false;
  93178. sphere.addBehavior(_dragBehavior);
  93179. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  93180. var totalTurnAmountOfDrag = 0;
  93181. _dragBehavior.onDragStartObservable.add(function (event) {
  93182. startingTurnDirection.copyFrom(sphere.forward);
  93183. totalTurnAmountOfDrag = 0;
  93184. });
  93185. _dragBehavior.onDragObservable.add(function (event) {
  93186. _this.onRotationSphereDragObservable.notifyObservers({});
  93187. if (_this.attachedMesh) {
  93188. _this._removeAndStorePivotPoint();
  93189. var worldDragDirection = startingTurnDirection;
  93190. // Project the world right on to the drag plane
  93191. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  93192. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  93193. // project drag delta on to the resulting drag axis and rotate based on that
  93194. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  93195. // Make rotation relative to size of mesh.
  93196. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  93197. // Rotate based on axis
  93198. if (!_this.attachedMesh.rotationQuaternion) {
  93199. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  93200. }
  93201. if (!_this._anchorMesh.rotationQuaternion) {
  93202. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  93203. }
  93204. // Do not allow the object to turn more than a full circle
  93205. totalTurnAmountOfDrag += projectDist;
  93206. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  93207. if (i_1 >= 8) {
  93208. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  93209. }
  93210. else if (i_1 >= 4) {
  93211. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  93212. }
  93213. else {
  93214. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  93215. }
  93216. // Rotate around center of bounding box
  93217. _this._anchorMesh.addChild(_this.attachedMesh);
  93218. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  93219. _this._anchorMesh.removeChild(_this.attachedMesh);
  93220. }
  93221. _this.updateBoundingBox();
  93222. _this._restorePivotPoint();
  93223. }
  93224. });
  93225. // Selection/deselection
  93226. _dragBehavior.onDragStartObservable.add(function () {
  93227. _this.onDragStartObservable.notifyObservers({});
  93228. _this._selectNode(sphere);
  93229. });
  93230. _dragBehavior.onDragEndObservable.add(function () {
  93231. _this.onRotationSphereDragEndObservable.notifyObservers({});
  93232. _this._selectNode(null);
  93233. });
  93234. this_1._rotateSpheresParent.addChild(sphere);
  93235. };
  93236. var this_1 = this, _dragBehavior;
  93237. for (var i_1 = 0; i_1 < 12; i_1++) {
  93238. _loop_1(i_1);
  93239. }
  93240. _this._rootMesh.addChild(_this._rotateSpheresParent);
  93241. // Create scale cubes
  93242. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  93243. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  93244. for (var i = 0; i < 2; i++) {
  93245. for (var j = 0; j < 2; j++) {
  93246. var _loop_2 = function () {
  93247. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  93248. box.material = coloredMaterial;
  93249. // Dragging logic
  93250. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  93251. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  93252. _dragBehavior.moveAttached = false;
  93253. box.addBehavior(_dragBehavior);
  93254. _dragBehavior.onDragObservable.add(function (event) {
  93255. _this.onScaleBoxDragObservable.notifyObservers({});
  93256. if (_this.attachedMesh) {
  93257. _this._removeAndStorePivotPoint();
  93258. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  93259. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  93260. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  93261. _this.updateBoundingBox();
  93262. if (_this.scalePivot) {
  93263. _this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(_this._tmpRotationMatrix);
  93264. // Move anchor to desired pivot point (Bottom left corner + dimension/2)
  93265. _this._boundingDimensions.scaleToRef(0.5, _this._tmpVector);
  93266. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  93267. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  93268. _this._boundingDimensions.multiplyToRef(_this.scalePivot, _this._tmpVector);
  93269. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  93270. _this._anchorMesh.position.addInPlace(_this._tmpVector);
  93271. }
  93272. else {
  93273. // Scale from the position of the opposite corner
  93274. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  93275. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  93276. }
  93277. _this._anchorMesh.addChild(_this.attachedMesh);
  93278. _this._anchorMesh.scaling.addInPlace(deltaScale);
  93279. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  93280. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  93281. }
  93282. _this._anchorMesh.removeChild(_this.attachedMesh);
  93283. _this._restorePivotPoint();
  93284. }
  93285. });
  93286. // Selection/deselection
  93287. _dragBehavior.onDragStartObservable.add(function () {
  93288. _this.onDragStartObservable.notifyObservers({});
  93289. _this._selectNode(box);
  93290. });
  93291. _dragBehavior.onDragEndObservable.add(function () {
  93292. _this.onScaleBoxDragEndObservable.notifyObservers({});
  93293. _this._selectNode(null);
  93294. });
  93295. this_2._scaleBoxesParent.addChild(box);
  93296. };
  93297. var this_2 = this, _dragBehavior;
  93298. for (var k = 0; k < 2; k++) {
  93299. _loop_2();
  93300. }
  93301. }
  93302. }
  93303. _this._rootMesh.addChild(_this._scaleBoxesParent);
  93304. // Hover color change
  93305. var pointerIds = new Array();
  93306. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  93307. if (!pointerIds[pointerInfo.event.pointerId]) {
  93308. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  93309. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  93310. pointerIds[pointerInfo.event.pointerId] = mesh;
  93311. mesh.material = hoverColoredMaterial;
  93312. }
  93313. });
  93314. }
  93315. else {
  93316. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  93317. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  93318. delete pointerIds[pointerInfo.event.pointerId];
  93319. }
  93320. }
  93321. });
  93322. // Update bounding box positions
  93323. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  93324. // Only update the bouding box if scaling has changed
  93325. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  93326. _this.updateBoundingBox();
  93327. }
  93328. });
  93329. _this.updateBoundingBox();
  93330. return _this;
  93331. }
  93332. BoundingBoxGizmo.prototype._removeAndStorePivotPoint = function () {
  93333. if (this.attachedMesh && this._pivotCached === 0) {
  93334. // Save old pivot and set pivot to 0,0,0
  93335. this.attachedMesh.getPivotPointToRef(this._oldPivotPoint);
  93336. if (this._oldPivotPoint.equalsToFloats(0, 0, 0)) {
  93337. return;
  93338. }
  93339. this.attachedMesh.setPivotMatrix(BABYLON.Matrix.IdentityReadOnly);
  93340. this._oldPivotPoint.subtractToRef(this.attachedMesh.getPivotPoint(), this._pivotTranslation);
  93341. this._tmpVector.copyFromFloats(1, 1, 1);
  93342. this._tmpVector.subtractInPlace(this.attachedMesh.scaling);
  93343. this._tmpVector.multiplyInPlace(this._pivotTranslation);
  93344. this.attachedMesh.position.addInPlace(this._tmpVector);
  93345. }
  93346. this._pivotCached++;
  93347. };
  93348. BoundingBoxGizmo.prototype._restorePivotPoint = function () {
  93349. if (this.attachedMesh && !this._oldPivotPoint.equalsToFloats(0, 0, 0) && this._pivotCached === 1) {
  93350. this.attachedMesh.setPivotPoint(this._oldPivotPoint);
  93351. this._tmpVector.copyFromFloats(1, 1, 1);
  93352. this._tmpVector.subtractInPlace(this.attachedMesh.scaling);
  93353. this._tmpVector.multiplyInPlace(this._pivotTranslation);
  93354. this.attachedMesh.position.subtractInPlace(this._tmpVector);
  93355. }
  93356. this._pivotCached--;
  93357. };
  93358. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  93359. if (value) {
  93360. // Reset anchor mesh to match attached mesh's scale
  93361. // This is needed to avoid invalid box/sphere position on first drag
  93362. this._removeAndStorePivotPoint();
  93363. this._anchorMesh.addChild(value);
  93364. this._anchorMesh.removeChild(value);
  93365. this._restorePivotPoint();
  93366. this.updateBoundingBox();
  93367. }
  93368. };
  93369. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  93370. this._rotateSpheresParent.getChildMeshes()
  93371. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  93372. m.isVisible = (!selectedMesh || m == selectedMesh);
  93373. });
  93374. };
  93375. BoundingBoxGizmo.prototype._recurseComputeWorld = function (node) {
  93376. var _this = this;
  93377. node.computeWorldMatrix(true);
  93378. if (!this.ignoreChildren) {
  93379. node.getDescendants().forEach(function (n) {
  93380. _this._recurseComputeWorld(n);
  93381. });
  93382. }
  93383. };
  93384. /**
  93385. * Updates the bounding box information for the Gizmo
  93386. */
  93387. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  93388. if (this.attachedMesh) {
  93389. this._removeAndStorePivotPoint();
  93390. this._update();
  93391. // Rotate based on axis
  93392. if (!this.attachedMesh.rotationQuaternion) {
  93393. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  93394. }
  93395. if (!this._anchorMesh.rotationQuaternion) {
  93396. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  93397. }
  93398. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  93399. // Store original position and reset mesh to origin before computing the bounding box
  93400. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  93401. this._tmpVector.copyFrom(this.attachedMesh.position);
  93402. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  93403. this.attachedMesh.position.set(0, 0, 0);
  93404. // Update bounding dimensions/positions
  93405. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren);
  93406. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  93407. // Update gizmo to match bounding box scaling and rotation
  93408. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  93409. this._lineBoundingBox.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  93410. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  93411. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  93412. this._lineBoundingBox.computeWorldMatrix();
  93413. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  93414. // restore position/rotation values
  93415. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  93416. this.attachedMesh.position.copyFrom(this._tmpVector);
  93417. this._recurseComputeWorld(this.attachedMesh);
  93418. }
  93419. // Update rotation sphere locations
  93420. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  93421. for (var i = 0; i < 3; i++) {
  93422. for (var j = 0; j < 2; j++) {
  93423. for (var k = 0; k < 2; k++) {
  93424. var index = ((i * 4) + (j * 2)) + k;
  93425. if (i == 0) {
  93426. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  93427. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  93428. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  93429. }
  93430. if (i == 1) {
  93431. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  93432. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  93433. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  93434. }
  93435. if (i == 2) {
  93436. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  93437. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  93438. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  93439. }
  93440. if (this.fixedDragMeshScreenSize) {
  93441. this._rootMesh.computeWorldMatrix();
  93442. this._rotateSpheresParent.computeWorldMatrix();
  93443. rotateSpheres[index].computeWorldMatrix();
  93444. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  93445. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  93446. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  93447. }
  93448. else {
  93449. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  93450. }
  93451. }
  93452. }
  93453. }
  93454. // Update scale box locations
  93455. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  93456. for (var i = 0; i < 2; i++) {
  93457. for (var j = 0; j < 2; j++) {
  93458. for (var k = 0; k < 2; k++) {
  93459. var index = ((i * 4) + (j * 2)) + k;
  93460. if (scaleBoxes[index]) {
  93461. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  93462. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  93463. if (this.fixedDragMeshScreenSize) {
  93464. this._rootMesh.computeWorldMatrix();
  93465. this._scaleBoxesParent.computeWorldMatrix();
  93466. scaleBoxes[index].computeWorldMatrix();
  93467. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  93468. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  93469. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  93470. }
  93471. else {
  93472. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  93473. }
  93474. }
  93475. }
  93476. }
  93477. }
  93478. if (this.attachedMesh) {
  93479. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  93480. this._restorePivotPoint();
  93481. }
  93482. };
  93483. /**
  93484. * Enables rotation on the specified axis and disables rotation on the others
  93485. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  93486. */
  93487. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  93488. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  93489. if (i < 4) {
  93490. m.setEnabled(axis.indexOf("x") != -1);
  93491. }
  93492. else if (i < 8) {
  93493. m.setEnabled(axis.indexOf("y") != -1);
  93494. }
  93495. else {
  93496. m.setEnabled(axis.indexOf("z") != -1);
  93497. }
  93498. });
  93499. };
  93500. /**
  93501. * Disposes of the gizmo
  93502. */
  93503. BoundingBoxGizmo.prototype.dispose = function () {
  93504. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  93505. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  93506. this._lineBoundingBox.dispose();
  93507. this._rotateSpheresParent.dispose();
  93508. this._scaleBoxesParent.dispose();
  93509. _super.prototype.dispose.call(this);
  93510. };
  93511. /**
  93512. * Makes a mesh not pickable and wraps the mesh inside of a bounding box mesh that is pickable. (This is useful to avoid picking within complex geometry)
  93513. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  93514. * @returns the bounding box mesh with the passed in mesh as a child
  93515. */
  93516. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  93517. var makeNotPickable = function (root) {
  93518. root.isPickable = false;
  93519. root.getChildMeshes().forEach(function (c) {
  93520. makeNotPickable(c);
  93521. });
  93522. };
  93523. makeNotPickable(mesh);
  93524. // Reset position to get boudning box from origin with no rotation
  93525. if (!mesh.rotationQuaternion) {
  93526. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  93527. }
  93528. var oldPos = mesh.position.clone();
  93529. var oldRot = mesh.rotationQuaternion.clone();
  93530. mesh.rotationQuaternion.set(0, 0, 0, 1);
  93531. mesh.position.set(0, 0, 0);
  93532. // Update bounding dimensions/positions
  93533. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  93534. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  93535. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  93536. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  93537. // Restore original positions
  93538. mesh.addChild(box);
  93539. mesh.rotationQuaternion.copyFrom(oldRot);
  93540. mesh.position.copyFrom(oldPos);
  93541. // Reverse parenting
  93542. mesh.removeChild(box);
  93543. box.addChild(mesh);
  93544. box.visibility = 0;
  93545. return box;
  93546. };
  93547. /**
  93548. * CustomMeshes are not supported by this gizmo
  93549. * @param mesh The mesh to replace the default mesh of the gizmo
  93550. */
  93551. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  93552. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  93553. };
  93554. return BoundingBoxGizmo;
  93555. }(BABYLON.Gizmo));
  93556. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  93557. })(BABYLON || (BABYLON = {}));
  93558. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  93559. var BABYLON;
  93560. (function (BABYLON) {
  93561. /**
  93562. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  93563. */
  93564. var GizmoManager = /** @class */ (function () {
  93565. /**
  93566. * Instatiates a gizmo manager
  93567. * @param scene the scene to overlay the gizmos on top of
  93568. */
  93569. function GizmoManager(scene) {
  93570. var _this = this;
  93571. this.scene = scene;
  93572. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  93573. this._pointerObserver = null;
  93574. this._attachedMesh = null;
  93575. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  93576. this._dragBehavior = new BABYLON.SixDofDragBehavior();
  93577. /**
  93578. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  93579. */
  93580. this.attachableMeshes = null;
  93581. /**
  93582. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  93583. */
  93584. this.usePointerToAttachGizmos = true;
  93585. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  93586. // Instatiate/dispose gizmos based on pointer actions
  93587. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  93588. if (!_this.usePointerToAttachGizmos) {
  93589. return;
  93590. }
  93591. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  93592. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  93593. var node = pointerInfo.pickInfo.pickedMesh;
  93594. if (_this.attachableMeshes == null) {
  93595. // Attach to the most parent node
  93596. while (node && node.parent != null) {
  93597. node = node.parent;
  93598. }
  93599. }
  93600. else {
  93601. // Attach to the parent node that is an attachableMesh
  93602. var found = false;
  93603. _this.attachableMeshes.forEach(function (mesh) {
  93604. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  93605. node = mesh;
  93606. found = true;
  93607. }
  93608. });
  93609. if (!found) {
  93610. node = null;
  93611. }
  93612. }
  93613. if (node instanceof BABYLON.AbstractMesh) {
  93614. _this.attachToMesh(node);
  93615. }
  93616. else {
  93617. _this.attachToMesh(null);
  93618. }
  93619. }
  93620. else {
  93621. _this.attachToMesh(null);
  93622. }
  93623. }
  93624. });
  93625. }
  93626. /**
  93627. * Attaches a set of gizmos to the specified mesh
  93628. * @param mesh The mesh the gizmo's should be attached to
  93629. */
  93630. GizmoManager.prototype.attachToMesh = function (mesh) {
  93631. if (this._attachedMesh) {
  93632. this._attachedMesh.removeBehavior(this._dragBehavior);
  93633. }
  93634. this._attachedMesh = mesh;
  93635. for (var key in this.gizmos) {
  93636. var gizmo = (this.gizmos[key]);
  93637. if (gizmo && this._gizmosEnabled[key]) {
  93638. gizmo.attachedMesh = mesh;
  93639. }
  93640. }
  93641. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  93642. this._attachedMesh.addBehavior(this._dragBehavior);
  93643. }
  93644. };
  93645. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  93646. get: function () {
  93647. return this._gizmosEnabled.positionGizmo;
  93648. },
  93649. /**
  93650. * If the position gizmo is enabled
  93651. */
  93652. set: function (value) {
  93653. if (value) {
  93654. if (!this.gizmos.positionGizmo) {
  93655. this.gizmos.positionGizmo = new BABYLON.PositionGizmo();
  93656. this.gizmos.positionGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  93657. }
  93658. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  93659. }
  93660. else if (this.gizmos.positionGizmo) {
  93661. this.gizmos.positionGizmo.attachedMesh = null;
  93662. }
  93663. this._gizmosEnabled.positionGizmo = value;
  93664. },
  93665. enumerable: true,
  93666. configurable: true
  93667. });
  93668. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  93669. get: function () {
  93670. return this._gizmosEnabled.rotationGizmo;
  93671. },
  93672. /**
  93673. * If the rotation gizmo is enabled
  93674. */
  93675. set: function (value) {
  93676. if (value) {
  93677. if (!this.gizmos.rotationGizmo) {
  93678. this.gizmos.rotationGizmo = new BABYLON.RotationGizmo();
  93679. this.gizmos.rotationGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  93680. }
  93681. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  93682. }
  93683. else if (this.gizmos.rotationGizmo) {
  93684. this.gizmos.rotationGizmo.attachedMesh = null;
  93685. }
  93686. this._gizmosEnabled.rotationGizmo = value;
  93687. },
  93688. enumerable: true,
  93689. configurable: true
  93690. });
  93691. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  93692. get: function () {
  93693. return this._gizmosEnabled.scaleGizmo;
  93694. },
  93695. /**
  93696. * If the scale gizmo is enabled
  93697. */
  93698. set: function (value) {
  93699. if (value) {
  93700. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo();
  93701. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  93702. }
  93703. else if (this.gizmos.scaleGizmo) {
  93704. this.gizmos.scaleGizmo.attachedMesh = null;
  93705. }
  93706. this._gizmosEnabled.scaleGizmo = value;
  93707. },
  93708. enumerable: true,
  93709. configurable: true
  93710. });
  93711. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  93712. get: function () {
  93713. return this._gizmosEnabled.boundingBoxGizmo;
  93714. },
  93715. /**
  93716. * If the boundingBox gizmo is enabled
  93717. */
  93718. set: function (value) {
  93719. if (value) {
  93720. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor);
  93721. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  93722. if (this._attachedMesh) {
  93723. this._attachedMesh.removeBehavior(this._dragBehavior);
  93724. this._attachedMesh.addBehavior(this._dragBehavior);
  93725. }
  93726. }
  93727. else if (this.gizmos.boundingBoxGizmo) {
  93728. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  93729. }
  93730. this._gizmosEnabled.boundingBoxGizmo = value;
  93731. },
  93732. enumerable: true,
  93733. configurable: true
  93734. });
  93735. /**
  93736. * Disposes of the gizmo manager
  93737. */
  93738. GizmoManager.prototype.dispose = function () {
  93739. this.scene.onPointerObservable.remove(this._pointerObserver);
  93740. for (var key in this.gizmos) {
  93741. var gizmo = (this.gizmos[key]);
  93742. if (gizmo) {
  93743. gizmo.dispose();
  93744. }
  93745. }
  93746. this._dragBehavior.detach();
  93747. };
  93748. return GizmoManager;
  93749. }());
  93750. BABYLON.GizmoManager = GizmoManager;
  93751. })(BABYLON || (BABYLON = {}));
  93752. //# sourceMappingURL=babylon.gizmoManager.js.map
  93753. var BABYLON;
  93754. (function (BABYLON) {
  93755. /**
  93756. * Defines a target to use with MorphTargetManager
  93757. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  93758. */
  93759. var MorphTarget = /** @class */ (function () {
  93760. /**
  93761. * Creates a new MorphTarget
  93762. * @param name defines the name of the target
  93763. * @param influence defines the influence to use
  93764. */
  93765. function MorphTarget(
  93766. /** defines the name of the target */
  93767. name, influence, scene) {
  93768. if (influence === void 0) { influence = 0; }
  93769. if (scene === void 0) { scene = null; }
  93770. this.name = name;
  93771. /**
  93772. * Gets or sets the list of animations
  93773. */
  93774. this.animations = new Array();
  93775. this._positions = null;
  93776. this._normals = null;
  93777. this._tangents = null;
  93778. /**
  93779. * Observable raised when the influence changes
  93780. */
  93781. this.onInfluenceChanged = new BABYLON.Observable();
  93782. this._animationPropertiesOverride = null;
  93783. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  93784. this.influence = influence;
  93785. }
  93786. Object.defineProperty(MorphTarget.prototype, "influence", {
  93787. /**
  93788. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  93789. */
  93790. get: function () {
  93791. return this._influence;
  93792. },
  93793. set: function (influence) {
  93794. if (this._influence === influence) {
  93795. return;
  93796. }
  93797. var previous = this._influence;
  93798. this._influence = influence;
  93799. if (this.onInfluenceChanged.hasObservers) {
  93800. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  93801. }
  93802. },
  93803. enumerable: true,
  93804. configurable: true
  93805. });
  93806. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  93807. /**
  93808. * Gets or sets the animation properties override
  93809. */
  93810. get: function () {
  93811. if (!this._animationPropertiesOverride && this._scene) {
  93812. return this._scene.animationPropertiesOverride;
  93813. }
  93814. return this._animationPropertiesOverride;
  93815. },
  93816. set: function (value) {
  93817. this._animationPropertiesOverride = value;
  93818. },
  93819. enumerable: true,
  93820. configurable: true
  93821. });
  93822. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  93823. /**
  93824. * Gets a boolean defining if the target contains position data
  93825. */
  93826. get: function () {
  93827. return !!this._positions;
  93828. },
  93829. enumerable: true,
  93830. configurable: true
  93831. });
  93832. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  93833. /**
  93834. * Gets a boolean defining if the target contains normal data
  93835. */
  93836. get: function () {
  93837. return !!this._normals;
  93838. },
  93839. enumerable: true,
  93840. configurable: true
  93841. });
  93842. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  93843. /**
  93844. * Gets a boolean defining if the target contains tangent data
  93845. */
  93846. get: function () {
  93847. return !!this._tangents;
  93848. },
  93849. enumerable: true,
  93850. configurable: true
  93851. });
  93852. /**
  93853. * Affects position data to this target
  93854. * @param data defines the position data to use
  93855. */
  93856. MorphTarget.prototype.setPositions = function (data) {
  93857. this._positions = data;
  93858. };
  93859. /**
  93860. * Gets the position data stored in this target
  93861. * @returns a FloatArray containing the position data (or null if not present)
  93862. */
  93863. MorphTarget.prototype.getPositions = function () {
  93864. return this._positions;
  93865. };
  93866. /**
  93867. * Affects normal data to this target
  93868. * @param data defines the normal data to use
  93869. */
  93870. MorphTarget.prototype.setNormals = function (data) {
  93871. this._normals = data;
  93872. };
  93873. /**
  93874. * Gets the normal data stored in this target
  93875. * @returns a FloatArray containing the normal data (or null if not present)
  93876. */
  93877. MorphTarget.prototype.getNormals = function () {
  93878. return this._normals;
  93879. };
  93880. /**
  93881. * Affects tangent data to this target
  93882. * @param data defines the tangent data to use
  93883. */
  93884. MorphTarget.prototype.setTangents = function (data) {
  93885. this._tangents = data;
  93886. };
  93887. /**
  93888. * Gets the tangent data stored in this target
  93889. * @returns a FloatArray containing the tangent data (or null if not present)
  93890. */
  93891. MorphTarget.prototype.getTangents = function () {
  93892. return this._tangents;
  93893. };
  93894. /**
  93895. * Serializes the current target into a Serialization object
  93896. * @returns the serialized object
  93897. */
  93898. MorphTarget.prototype.serialize = function () {
  93899. var serializationObject = {};
  93900. serializationObject.name = this.name;
  93901. serializationObject.influence = this.influence;
  93902. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  93903. if (this.hasNormals) {
  93904. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  93905. }
  93906. if (this.hasTangents) {
  93907. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  93908. }
  93909. // Animations
  93910. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  93911. return serializationObject;
  93912. };
  93913. // Statics
  93914. /**
  93915. * Creates a new target from serialized data
  93916. * @param serializationObject defines the serialized data to use
  93917. * @returns a new MorphTarget
  93918. */
  93919. MorphTarget.Parse = function (serializationObject) {
  93920. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  93921. result.setPositions(serializationObject.positions);
  93922. if (serializationObject.normals) {
  93923. result.setNormals(serializationObject.normals);
  93924. }
  93925. if (serializationObject.tangents) {
  93926. result.setTangents(serializationObject.tangents);
  93927. }
  93928. // Animations
  93929. if (serializationObject.animations) {
  93930. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  93931. var parsedAnimation = serializationObject.animations[animationIndex];
  93932. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  93933. }
  93934. }
  93935. return result;
  93936. };
  93937. /**
  93938. * Creates a MorphTarget from mesh data
  93939. * @param mesh defines the source mesh
  93940. * @param name defines the name to use for the new target
  93941. * @param influence defines the influence to attach to the target
  93942. * @returns a new MorphTarget
  93943. */
  93944. MorphTarget.FromMesh = function (mesh, name, influence) {
  93945. if (!name) {
  93946. name = mesh.name;
  93947. }
  93948. var result = new MorphTarget(name, influence, mesh.getScene());
  93949. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  93950. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  93951. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  93952. }
  93953. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  93954. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  93955. }
  93956. return result;
  93957. };
  93958. return MorphTarget;
  93959. }());
  93960. BABYLON.MorphTarget = MorphTarget;
  93961. })(BABYLON || (BABYLON = {}));
  93962. //# sourceMappingURL=babylon.morphTarget.js.map
  93963. var BABYLON;
  93964. (function (BABYLON) {
  93965. /**
  93966. * This class is used to deform meshes using morphing between different targets
  93967. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  93968. */
  93969. var MorphTargetManager = /** @class */ (function () {
  93970. /**
  93971. * Creates a new MorphTargetManager
  93972. * @param scene defines the current scene
  93973. */
  93974. function MorphTargetManager(scene) {
  93975. if (scene === void 0) { scene = null; }
  93976. this._targets = new Array();
  93977. this._targetObservable = new Array();
  93978. this._activeTargets = new BABYLON.SmartArray(16);
  93979. this._supportsNormals = false;
  93980. this._supportsTangents = false;
  93981. this._vertexCount = 0;
  93982. this._uniqueId = 0;
  93983. this._tempInfluences = new Array();
  93984. if (!scene) {
  93985. scene = BABYLON.Engine.LastCreatedScene;
  93986. }
  93987. this._scene = scene;
  93988. if (this._scene) {
  93989. this._scene.morphTargetManagers.push(this);
  93990. this._uniqueId = this._scene.getUniqueId();
  93991. }
  93992. }
  93993. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  93994. /**
  93995. * Gets the unique ID of this manager
  93996. */
  93997. get: function () {
  93998. return this._uniqueId;
  93999. },
  94000. enumerable: true,
  94001. configurable: true
  94002. });
  94003. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  94004. /**
  94005. * Gets the number of vertices handled by this manager
  94006. */
  94007. get: function () {
  94008. return this._vertexCount;
  94009. },
  94010. enumerable: true,
  94011. configurable: true
  94012. });
  94013. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  94014. /**
  94015. * Gets a boolean indicating if this manager supports morphing of normals
  94016. */
  94017. get: function () {
  94018. return this._supportsNormals;
  94019. },
  94020. enumerable: true,
  94021. configurable: true
  94022. });
  94023. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  94024. /**
  94025. * Gets a boolean indicating if this manager supports morphing of tangents
  94026. */
  94027. get: function () {
  94028. return this._supportsTangents;
  94029. },
  94030. enumerable: true,
  94031. configurable: true
  94032. });
  94033. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  94034. /**
  94035. * Gets the number of targets stored in this manager
  94036. */
  94037. get: function () {
  94038. return this._targets.length;
  94039. },
  94040. enumerable: true,
  94041. configurable: true
  94042. });
  94043. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  94044. /**
  94045. * Gets the number of influencers (ie. the number of targets with influences > 0)
  94046. */
  94047. get: function () {
  94048. return this._activeTargets.length;
  94049. },
  94050. enumerable: true,
  94051. configurable: true
  94052. });
  94053. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  94054. /**
  94055. * Gets the list of influences (one per target)
  94056. */
  94057. get: function () {
  94058. return this._influences;
  94059. },
  94060. enumerable: true,
  94061. configurable: true
  94062. });
  94063. /**
  94064. * Gets the active target at specified index. An active target is a target with an influence > 0
  94065. * @param index defines the index to check
  94066. * @returns the requested target
  94067. */
  94068. MorphTargetManager.prototype.getActiveTarget = function (index) {
  94069. return this._activeTargets.data[index];
  94070. };
  94071. /**
  94072. * Gets the target at specified index
  94073. * @param index defines the index to check
  94074. * @returns the requested target
  94075. */
  94076. MorphTargetManager.prototype.getTarget = function (index) {
  94077. return this._targets[index];
  94078. };
  94079. /**
  94080. * Add a new target to this manager
  94081. * @param target defines the target to add
  94082. */
  94083. MorphTargetManager.prototype.addTarget = function (target) {
  94084. var _this = this;
  94085. this._targets.push(target);
  94086. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  94087. _this._syncActiveTargets(needUpdate);
  94088. }));
  94089. this._syncActiveTargets(true);
  94090. };
  94091. /**
  94092. * Removes a target from the manager
  94093. * @param target defines the target to remove
  94094. */
  94095. MorphTargetManager.prototype.removeTarget = function (target) {
  94096. var index = this._targets.indexOf(target);
  94097. if (index >= 0) {
  94098. this._targets.splice(index, 1);
  94099. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  94100. this._syncActiveTargets(true);
  94101. }
  94102. };
  94103. /**
  94104. * Serializes the current manager into a Serialization object
  94105. * @returns the serialized object
  94106. */
  94107. MorphTargetManager.prototype.serialize = function () {
  94108. var serializationObject = {};
  94109. serializationObject.id = this.uniqueId;
  94110. serializationObject.targets = [];
  94111. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  94112. var target = _a[_i];
  94113. serializationObject.targets.push(target.serialize());
  94114. }
  94115. return serializationObject;
  94116. };
  94117. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  94118. var influenceCount = 0;
  94119. this._activeTargets.reset();
  94120. this._supportsNormals = true;
  94121. this._supportsTangents = true;
  94122. this._vertexCount = 0;
  94123. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  94124. var target = _a[_i];
  94125. this._activeTargets.push(target);
  94126. this._tempInfluences[influenceCount++] = target.influence;
  94127. var positions = target.getPositions();
  94128. if (positions) {
  94129. this._supportsNormals = this._supportsNormals && target.hasNormals;
  94130. this._supportsTangents = this._supportsTangents && target.hasTangents;
  94131. var vertexCount = positions.length / 3;
  94132. if (this._vertexCount === 0) {
  94133. this._vertexCount = vertexCount;
  94134. }
  94135. else if (this._vertexCount !== vertexCount) {
  94136. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  94137. return;
  94138. }
  94139. }
  94140. }
  94141. if (!this._influences || this._influences.length !== influenceCount) {
  94142. this._influences = new Float32Array(influenceCount);
  94143. }
  94144. for (var index = 0; index < influenceCount; index++) {
  94145. this._influences[index] = this._tempInfluences[index];
  94146. }
  94147. if (needUpdate) {
  94148. this.synchronize();
  94149. }
  94150. };
  94151. /**
  94152. * Syncrhonize the targets with all the meshes using this morph target manager
  94153. */
  94154. MorphTargetManager.prototype.synchronize = function () {
  94155. if (!this._scene) {
  94156. return;
  94157. }
  94158. // Flag meshes as dirty to resync with the active targets
  94159. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  94160. var mesh = _a[_i];
  94161. if (mesh.morphTargetManager === this) {
  94162. mesh._syncGeometryWithMorphTargetManager();
  94163. }
  94164. }
  94165. };
  94166. // Statics
  94167. /**
  94168. * Creates a new MorphTargetManager from serialized data
  94169. * @param serializationObject defines the serialized data
  94170. * @param scene defines the hosting scene
  94171. * @returns the new MorphTargetManager
  94172. */
  94173. MorphTargetManager.Parse = function (serializationObject, scene) {
  94174. var result = new MorphTargetManager(scene);
  94175. result._uniqueId = serializationObject.id;
  94176. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  94177. var targetData = _a[_i];
  94178. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  94179. }
  94180. return result;
  94181. };
  94182. return MorphTargetManager;
  94183. }());
  94184. BABYLON.MorphTargetManager = MorphTargetManager;
  94185. })(BABYLON || (BABYLON = {}));
  94186. //# sourceMappingURL=babylon.morphTargetManager.js.map
  94187. var BABYLON;
  94188. (function (BABYLON) {
  94189. var Octree = /** @class */ (function () {
  94190. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  94191. if (maxDepth === void 0) { maxDepth = 2; }
  94192. this.maxDepth = maxDepth;
  94193. this.dynamicContent = new Array();
  94194. this._maxBlockCapacity = maxBlockCapacity || 64;
  94195. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  94196. this._creationFunc = creationFunc;
  94197. }
  94198. // Methods
  94199. Octree.prototype.update = function (worldMin, worldMax, entries) {
  94200. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  94201. };
  94202. Octree.prototype.addMesh = function (entry) {
  94203. for (var index = 0; index < this.blocks.length; index++) {
  94204. var block = this.blocks[index];
  94205. block.addEntry(entry);
  94206. }
  94207. };
  94208. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  94209. this._selectionContent.reset();
  94210. for (var index = 0; index < this.blocks.length; index++) {
  94211. var block = this.blocks[index];
  94212. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  94213. }
  94214. if (allowDuplicate) {
  94215. this._selectionContent.concat(this.dynamicContent);
  94216. }
  94217. else {
  94218. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  94219. }
  94220. return this._selectionContent;
  94221. };
  94222. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  94223. this._selectionContent.reset();
  94224. for (var index = 0; index < this.blocks.length; index++) {
  94225. var block = this.blocks[index];
  94226. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  94227. }
  94228. if (allowDuplicate) {
  94229. this._selectionContent.concat(this.dynamicContent);
  94230. }
  94231. else {
  94232. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  94233. }
  94234. return this._selectionContent;
  94235. };
  94236. Octree.prototype.intersectsRay = function (ray) {
  94237. this._selectionContent.reset();
  94238. for (var index = 0; index < this.blocks.length; index++) {
  94239. var block = this.blocks[index];
  94240. block.intersectsRay(ray, this._selectionContent);
  94241. }
  94242. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  94243. return this._selectionContent;
  94244. };
  94245. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  94246. target.blocks = new Array();
  94247. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  94248. // Segmenting space
  94249. for (var x = 0; x < 2; x++) {
  94250. for (var y = 0; y < 2; y++) {
  94251. for (var z = 0; z < 2; z++) {
  94252. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  94253. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  94254. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  94255. block.addEntries(entries);
  94256. target.blocks.push(block);
  94257. }
  94258. }
  94259. }
  94260. };
  94261. Octree.CreationFuncForMeshes = function (entry, block) {
  94262. var boundingInfo = entry.getBoundingInfo();
  94263. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  94264. block.entries.push(entry);
  94265. }
  94266. };
  94267. Octree.CreationFuncForSubMeshes = function (entry, block) {
  94268. var boundingInfo = entry.getBoundingInfo();
  94269. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  94270. block.entries.push(entry);
  94271. }
  94272. };
  94273. return Octree;
  94274. }());
  94275. BABYLON.Octree = Octree;
  94276. })(BABYLON || (BABYLON = {}));
  94277. //# sourceMappingURL=babylon.octree.js.map
  94278. var BABYLON;
  94279. (function (BABYLON) {
  94280. var OctreeBlock = /** @class */ (function () {
  94281. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  94282. this.entries = new Array();
  94283. this._boundingVectors = new Array();
  94284. this._capacity = capacity;
  94285. this._depth = depth;
  94286. this._maxDepth = maxDepth;
  94287. this._creationFunc = creationFunc;
  94288. this._minPoint = minPoint;
  94289. this._maxPoint = maxPoint;
  94290. this._boundingVectors.push(minPoint.clone());
  94291. this._boundingVectors.push(maxPoint.clone());
  94292. this._boundingVectors.push(minPoint.clone());
  94293. this._boundingVectors[2].x = maxPoint.x;
  94294. this._boundingVectors.push(minPoint.clone());
  94295. this._boundingVectors[3].y = maxPoint.y;
  94296. this._boundingVectors.push(minPoint.clone());
  94297. this._boundingVectors[4].z = maxPoint.z;
  94298. this._boundingVectors.push(maxPoint.clone());
  94299. this._boundingVectors[5].z = minPoint.z;
  94300. this._boundingVectors.push(maxPoint.clone());
  94301. this._boundingVectors[6].x = minPoint.x;
  94302. this._boundingVectors.push(maxPoint.clone());
  94303. this._boundingVectors[7].y = minPoint.y;
  94304. }
  94305. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  94306. // Property
  94307. get: function () {
  94308. return this._capacity;
  94309. },
  94310. enumerable: true,
  94311. configurable: true
  94312. });
  94313. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  94314. get: function () {
  94315. return this._minPoint;
  94316. },
  94317. enumerable: true,
  94318. configurable: true
  94319. });
  94320. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  94321. get: function () {
  94322. return this._maxPoint;
  94323. },
  94324. enumerable: true,
  94325. configurable: true
  94326. });
  94327. // Methods
  94328. OctreeBlock.prototype.addEntry = function (entry) {
  94329. if (this.blocks) {
  94330. for (var index = 0; index < this.blocks.length; index++) {
  94331. var block = this.blocks[index];
  94332. block.addEntry(entry);
  94333. }
  94334. return;
  94335. }
  94336. this._creationFunc(entry, this);
  94337. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  94338. this.createInnerBlocks();
  94339. }
  94340. };
  94341. OctreeBlock.prototype.addEntries = function (entries) {
  94342. for (var index = 0; index < entries.length; index++) {
  94343. var mesh = entries[index];
  94344. this.addEntry(mesh);
  94345. }
  94346. };
  94347. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  94348. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  94349. if (this.blocks) {
  94350. for (var index = 0; index < this.blocks.length; index++) {
  94351. var block = this.blocks[index];
  94352. block.select(frustumPlanes, selection, allowDuplicate);
  94353. }
  94354. return;
  94355. }
  94356. if (allowDuplicate) {
  94357. selection.concat(this.entries);
  94358. }
  94359. else {
  94360. selection.concatWithNoDuplicate(this.entries);
  94361. }
  94362. }
  94363. };
  94364. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  94365. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  94366. if (this.blocks) {
  94367. for (var index = 0; index < this.blocks.length; index++) {
  94368. var block = this.blocks[index];
  94369. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  94370. }
  94371. return;
  94372. }
  94373. if (allowDuplicate) {
  94374. selection.concat(this.entries);
  94375. }
  94376. else {
  94377. selection.concatWithNoDuplicate(this.entries);
  94378. }
  94379. }
  94380. };
  94381. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  94382. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  94383. if (this.blocks) {
  94384. for (var index = 0; index < this.blocks.length; index++) {
  94385. var block = this.blocks[index];
  94386. block.intersectsRay(ray, selection);
  94387. }
  94388. return;
  94389. }
  94390. selection.concatWithNoDuplicate(this.entries);
  94391. }
  94392. };
  94393. OctreeBlock.prototype.createInnerBlocks = function () {
  94394. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  94395. };
  94396. return OctreeBlock;
  94397. }());
  94398. BABYLON.OctreeBlock = OctreeBlock;
  94399. })(BABYLON || (BABYLON = {}));
  94400. //# sourceMappingURL=babylon.octreeBlock.js.map
  94401. var BABYLON;
  94402. (function (BABYLON) {
  94403. /**
  94404. * Postprocess used to generate anaglyphic rendering
  94405. */
  94406. var AnaglyphPostProcess = /** @class */ (function (_super) {
  94407. __extends(AnaglyphPostProcess, _super);
  94408. /**
  94409. * Creates a new AnaglyphPostProcess
  94410. * @param name defines postprocess name
  94411. * @param options defines creation options or target ratio scale
  94412. * @param rigCameras defines cameras using this postprocess
  94413. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  94414. * @param engine defines hosting engine
  94415. * @param reusable defines if the postprocess will be reused multiple times per frame
  94416. */
  94417. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  94418. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  94419. _this._passedProcess = rigCameras[0]._rigPostProcess;
  94420. _this.onApplyObservable.add(function (effect) {
  94421. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  94422. });
  94423. return _this;
  94424. }
  94425. return AnaglyphPostProcess;
  94426. }(BABYLON.PostProcess));
  94427. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  94428. })(BABYLON || (BABYLON = {}));
  94429. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  94430. var BABYLON;
  94431. (function (BABYLON) {
  94432. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  94433. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  94434. });
  94435. /**
  94436. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  94437. */
  94438. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  94439. __extends(AnaglyphArcRotateCamera, _super);
  94440. /**
  94441. * Creates a new AnaglyphArcRotateCamera
  94442. * @param name defines camera name
  94443. * @param alpha defines alpha angle (in radians)
  94444. * @param beta defines beta angle (in radians)
  94445. * @param radius defines radius
  94446. * @param target defines camera target
  94447. * @param interaxialDistance defines distance between each color axis
  94448. * @param scene defines the hosting scene
  94449. */
  94450. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  94451. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  94452. _this.interaxialDistance = interaxialDistance;
  94453. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  94454. return _this;
  94455. }
  94456. /**
  94457. * Gets camera class name
  94458. * @returns AnaglyphArcRotateCamera
  94459. */
  94460. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  94461. return "AnaglyphArcRotateCamera";
  94462. };
  94463. return AnaglyphArcRotateCamera;
  94464. }(BABYLON.ArcRotateCamera));
  94465. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  94466. })(BABYLON || (BABYLON = {}));
  94467. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  94468. var BABYLON;
  94469. (function (BABYLON) {
  94470. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  94471. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  94472. });
  94473. /**
  94474. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  94475. */
  94476. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  94477. __extends(AnaglyphFreeCamera, _super);
  94478. /**
  94479. * Creates a new AnaglyphFreeCamera
  94480. * @param name defines camera name
  94481. * @param position defines initial position
  94482. * @param interaxialDistance defines distance between each color axis
  94483. * @param scene defines the hosting scene
  94484. */
  94485. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  94486. var _this = _super.call(this, name, position, scene) || this;
  94487. _this.interaxialDistance = interaxialDistance;
  94488. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  94489. return _this;
  94490. }
  94491. /**
  94492. * Gets camera class name
  94493. * @returns AnaglyphFreeCamera
  94494. */
  94495. AnaglyphFreeCamera.prototype.getClassName = function () {
  94496. return "AnaglyphFreeCamera";
  94497. };
  94498. return AnaglyphFreeCamera;
  94499. }(BABYLON.FreeCamera));
  94500. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  94501. })(BABYLON || (BABYLON = {}));
  94502. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  94503. var BABYLON;
  94504. (function (BABYLON) {
  94505. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  94506. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  94507. });
  94508. /**
  94509. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  94510. */
  94511. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  94512. __extends(AnaglyphGamepadCamera, _super);
  94513. /**
  94514. * Creates a new AnaglyphGamepadCamera
  94515. * @param name defines camera name
  94516. * @param position defines initial position
  94517. * @param interaxialDistance defines distance between each color axis
  94518. * @param scene defines the hosting scene
  94519. */
  94520. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  94521. var _this = _super.call(this, name, position, scene) || this;
  94522. _this.interaxialDistance = interaxialDistance;
  94523. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  94524. return _this;
  94525. }
  94526. /**
  94527. * Gets camera class name
  94528. * @returns AnaglyphGamepadCamera
  94529. */
  94530. AnaglyphGamepadCamera.prototype.getClassName = function () {
  94531. return "AnaglyphGamepadCamera";
  94532. };
  94533. return AnaglyphGamepadCamera;
  94534. }(BABYLON.GamepadCamera));
  94535. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  94536. })(BABYLON || (BABYLON = {}));
  94537. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  94538. var BABYLON;
  94539. (function (BABYLON) {
  94540. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  94541. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  94542. });
  94543. /**
  94544. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  94545. */
  94546. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  94547. __extends(AnaglyphUniversalCamera, _super);
  94548. /**
  94549. * Creates a new AnaglyphUniversalCamera
  94550. * @param name defines camera name
  94551. * @param position defines initial position
  94552. * @param interaxialDistance defines distance between each color axis
  94553. * @param scene defines the hosting scene
  94554. */
  94555. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  94556. var _this = _super.call(this, name, position, scene) || this;
  94557. _this.interaxialDistance = interaxialDistance;
  94558. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  94559. return _this;
  94560. }
  94561. /**
  94562. * Gets camera class name
  94563. * @returns AnaglyphUniversalCamera
  94564. */
  94565. AnaglyphUniversalCamera.prototype.getClassName = function () {
  94566. return "AnaglyphUniversalCamera";
  94567. };
  94568. return AnaglyphUniversalCamera;
  94569. }(BABYLON.UniversalCamera));
  94570. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  94571. })(BABYLON || (BABYLON = {}));
  94572. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  94573. var BABYLON;
  94574. (function (BABYLON) {
  94575. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  94576. __extends(StereoscopicInterlacePostProcess, _super);
  94577. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  94578. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  94579. _this._passedProcess = rigCameras[0]._rigPostProcess;
  94580. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  94581. _this.onSizeChangedObservable.add(function () {
  94582. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  94583. });
  94584. _this.onApplyObservable.add(function (effect) {
  94585. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  94586. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  94587. });
  94588. return _this;
  94589. }
  94590. return StereoscopicInterlacePostProcess;
  94591. }(BABYLON.PostProcess));
  94592. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  94593. })(BABYLON || (BABYLON = {}));
  94594. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  94595. var BABYLON;
  94596. (function (BABYLON) {
  94597. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  94598. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  94599. });
  94600. /**
  94601. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  94602. */
  94603. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  94604. __extends(StereoscopicArcRotateCamera, _super);
  94605. /**
  94606. * Creates a new StereoscopicArcRotateCamera
  94607. * @param name defines camera name
  94608. * @param alpha defines alpha angle (in radians)
  94609. * @param beta defines beta angle (in radians)
  94610. * @param radius defines radius
  94611. * @param target defines camera target
  94612. * @param interaxialDistance defines distance between each color axis
  94613. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  94614. * @param scene defines the hosting scene
  94615. */
  94616. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  94617. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  94618. _this.interaxialDistance = interaxialDistance;
  94619. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  94620. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  94621. return _this;
  94622. }
  94623. /**
  94624. * Gets camera class name
  94625. * @returns StereoscopicArcRotateCamera
  94626. */
  94627. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  94628. return "StereoscopicArcRotateCamera";
  94629. };
  94630. return StereoscopicArcRotateCamera;
  94631. }(BABYLON.ArcRotateCamera));
  94632. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  94633. })(BABYLON || (BABYLON = {}));
  94634. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  94635. var BABYLON;
  94636. (function (BABYLON) {
  94637. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  94638. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  94639. });
  94640. /**
  94641. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  94642. */
  94643. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  94644. __extends(StereoscopicFreeCamera, _super);
  94645. /**
  94646. * Creates a new StereoscopicFreeCamera
  94647. * @param name defines camera name
  94648. * @param position defines initial position
  94649. * @param interaxialDistance defines distance between each color axis
  94650. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  94651. * @param scene defines the hosting scene
  94652. */
  94653. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  94654. var _this = _super.call(this, name, position, scene) || this;
  94655. _this.interaxialDistance = interaxialDistance;
  94656. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  94657. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  94658. return _this;
  94659. }
  94660. /**
  94661. * Gets camera class name
  94662. * @returns StereoscopicFreeCamera
  94663. */
  94664. StereoscopicFreeCamera.prototype.getClassName = function () {
  94665. return "StereoscopicFreeCamera";
  94666. };
  94667. return StereoscopicFreeCamera;
  94668. }(BABYLON.FreeCamera));
  94669. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  94670. })(BABYLON || (BABYLON = {}));
  94671. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  94672. var BABYLON;
  94673. (function (BABYLON) {
  94674. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  94675. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  94676. });
  94677. /**
  94678. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  94679. */
  94680. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  94681. __extends(StereoscopicGamepadCamera, _super);
  94682. /**
  94683. * Creates a new StereoscopicGamepadCamera
  94684. * @param name defines camera name
  94685. * @param position defines initial position
  94686. * @param interaxialDistance defines distance between each color axis
  94687. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  94688. * @param scene defines the hosting scene
  94689. */
  94690. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  94691. var _this = _super.call(this, name, position, scene) || this;
  94692. _this.interaxialDistance = interaxialDistance;
  94693. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  94694. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  94695. return _this;
  94696. }
  94697. /**
  94698. * Gets camera class name
  94699. * @returns StereoscopicGamepadCamera
  94700. */
  94701. StereoscopicGamepadCamera.prototype.getClassName = function () {
  94702. return "StereoscopicGamepadCamera";
  94703. };
  94704. return StereoscopicGamepadCamera;
  94705. }(BABYLON.GamepadCamera));
  94706. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  94707. })(BABYLON || (BABYLON = {}));
  94708. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  94709. var BABYLON;
  94710. (function (BABYLON) {
  94711. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  94712. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  94713. });
  94714. /**
  94715. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  94716. */
  94717. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  94718. __extends(StereoscopicUniversalCamera, _super);
  94719. /**
  94720. * Creates a new StereoscopicUniversalCamera
  94721. * @param name defines camera name
  94722. * @param position defines initial position
  94723. * @param interaxialDistance defines distance between each color axis
  94724. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  94725. * @param scene defines the hosting scene
  94726. */
  94727. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  94728. var _this = _super.call(this, name, position, scene) || this;
  94729. _this.interaxialDistance = interaxialDistance;
  94730. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  94731. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  94732. return _this;
  94733. }
  94734. /**
  94735. * Gets camera class name
  94736. * @returns StereoscopicUniversalCamera
  94737. */
  94738. StereoscopicUniversalCamera.prototype.getClassName = function () {
  94739. return "StereoscopicUniversalCamera";
  94740. };
  94741. return StereoscopicUniversalCamera;
  94742. }(BABYLON.UniversalCamera));
  94743. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  94744. })(BABYLON || (BABYLON = {}));
  94745. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  94746. var BABYLON;
  94747. (function (BABYLON) {
  94748. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  94749. __extends(VRDistortionCorrectionPostProcess, _super);
  94750. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  94751. var _this = _super.call(this, name, "vrDistortionCorrection", [
  94752. 'LensCenter',
  94753. 'Scale',
  94754. 'ScaleIn',
  94755. 'HmdWarpParam'
  94756. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  94757. _this._isRightEye = isRightEye;
  94758. _this._distortionFactors = vrMetrics.distortionK;
  94759. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  94760. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  94761. _this.adaptScaleToCurrentViewport = true;
  94762. _this.onSizeChangedObservable.add(function () {
  94763. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  94764. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  94765. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  94766. });
  94767. _this.onApplyObservable.add(function (effect) {
  94768. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  94769. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  94770. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  94771. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  94772. });
  94773. return _this;
  94774. }
  94775. return VRDistortionCorrectionPostProcess;
  94776. }(BABYLON.PostProcess));
  94777. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  94778. })(BABYLON || (BABYLON = {}));
  94779. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  94780. var BABYLON;
  94781. (function (BABYLON) {
  94782. /**
  94783. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  94784. * Screen rotation is taken into account.
  94785. */
  94786. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  94787. function FreeCameraDeviceOrientationInput() {
  94788. var _this = this;
  94789. this._screenOrientationAngle = 0;
  94790. this._screenQuaternion = new BABYLON.Quaternion();
  94791. this._alpha = 0;
  94792. this._beta = 0;
  94793. this._gamma = 0;
  94794. this._orientationChanged = function () {
  94795. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  94796. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  94797. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  94798. };
  94799. this._deviceOrientation = function (evt) {
  94800. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  94801. _this._beta = evt.beta !== null ? evt.beta : 0;
  94802. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  94803. };
  94804. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  94805. this._orientationChanged();
  94806. }
  94807. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  94808. get: function () {
  94809. return this._camera;
  94810. },
  94811. set: function (camera) {
  94812. this._camera = camera;
  94813. if (this._camera != null && !this._camera.rotationQuaternion) {
  94814. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  94815. }
  94816. },
  94817. enumerable: true,
  94818. configurable: true
  94819. });
  94820. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  94821. window.addEventListener("orientationchange", this._orientationChanged);
  94822. window.addEventListener("deviceorientation", this._deviceOrientation);
  94823. //In certain cases, the attach control is called AFTER orientation was changed,
  94824. //So this is needed.
  94825. this._orientationChanged();
  94826. };
  94827. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  94828. window.removeEventListener("orientationchange", this._orientationChanged);
  94829. window.removeEventListener("deviceorientation", this._deviceOrientation);
  94830. };
  94831. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  94832. //if no device orientation provided, don't update the rotation.
  94833. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  94834. if (!this._alpha)
  94835. return;
  94836. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  94837. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  94838. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  94839. //Mirror on XY Plane
  94840. this._camera.rotationQuaternion.z *= -1;
  94841. this._camera.rotationQuaternion.w *= -1;
  94842. };
  94843. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  94844. return "FreeCameraDeviceOrientationInput";
  94845. };
  94846. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  94847. return "deviceOrientation";
  94848. };
  94849. return FreeCameraDeviceOrientationInput;
  94850. }());
  94851. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  94852. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  94853. })(BABYLON || (BABYLON = {}));
  94854. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  94855. var BABYLON;
  94856. (function (BABYLON) {
  94857. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  94858. function ArcRotateCameraVRDeviceOrientationInput() {
  94859. this.alphaCorrection = 1;
  94860. this.betaCorrection = 1;
  94861. this.gammaCorrection = 1;
  94862. this._alpha = 0;
  94863. this._gamma = 0;
  94864. this._dirty = false;
  94865. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  94866. }
  94867. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  94868. this.camera.attachControl(element, noPreventDefault);
  94869. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  94870. };
  94871. /** @hidden */
  94872. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  94873. if (evt.alpha !== null) {
  94874. this._alpha = +evt.alpha | 0;
  94875. }
  94876. if (evt.gamma !== null) {
  94877. this._gamma = +evt.gamma | 0;
  94878. }
  94879. this._dirty = true;
  94880. };
  94881. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  94882. if (this._dirty) {
  94883. this._dirty = false;
  94884. if (this._gamma < 0) {
  94885. this._gamma = 180 + this._gamma;
  94886. }
  94887. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  94888. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  94889. }
  94890. };
  94891. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  94892. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  94893. };
  94894. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  94895. return "ArcRotateCameraVRDeviceOrientationInput";
  94896. };
  94897. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  94898. return "VRDeviceOrientation";
  94899. };
  94900. return ArcRotateCameraVRDeviceOrientationInput;
  94901. }());
  94902. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  94903. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  94904. })(BABYLON || (BABYLON = {}));
  94905. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  94906. var BABYLON;
  94907. (function (BABYLON) {
  94908. var VRCameraMetrics = /** @class */ (function () {
  94909. function VRCameraMetrics() {
  94910. this.compensateDistortion = true;
  94911. }
  94912. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  94913. get: function () {
  94914. return this.hResolution / (2 * this.vResolution);
  94915. },
  94916. enumerable: true,
  94917. configurable: true
  94918. });
  94919. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  94920. get: function () {
  94921. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  94922. },
  94923. enumerable: true,
  94924. configurable: true
  94925. });
  94926. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  94927. get: function () {
  94928. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  94929. var h = (4 * meters) / this.hScreenSize;
  94930. return BABYLON.Matrix.Translation(h, 0, 0);
  94931. },
  94932. enumerable: true,
  94933. configurable: true
  94934. });
  94935. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  94936. get: function () {
  94937. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  94938. var h = (4 * meters) / this.hScreenSize;
  94939. return BABYLON.Matrix.Translation(-h, 0, 0);
  94940. },
  94941. enumerable: true,
  94942. configurable: true
  94943. });
  94944. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  94945. get: function () {
  94946. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  94947. },
  94948. enumerable: true,
  94949. configurable: true
  94950. });
  94951. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  94952. get: function () {
  94953. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  94954. },
  94955. enumerable: true,
  94956. configurable: true
  94957. });
  94958. VRCameraMetrics.GetDefault = function () {
  94959. var result = new VRCameraMetrics();
  94960. result.hResolution = 1280;
  94961. result.vResolution = 800;
  94962. result.hScreenSize = 0.149759993;
  94963. result.vScreenSize = 0.0935999975;
  94964. result.vScreenCenter = 0.0467999987;
  94965. result.eyeToScreenDistance = 0.0410000011;
  94966. result.lensSeparationDistance = 0.0635000020;
  94967. result.interpupillaryDistance = 0.0640000030;
  94968. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  94969. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  94970. result.postProcessScaleFactor = 1.714605507808412;
  94971. result.lensCenterOffset = 0.151976421;
  94972. return result;
  94973. };
  94974. return VRCameraMetrics;
  94975. }());
  94976. BABYLON.VRCameraMetrics = VRCameraMetrics;
  94977. })(BABYLON || (BABYLON = {}));
  94978. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  94979. var BABYLON;
  94980. (function (BABYLON) {
  94981. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  94982. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  94983. });
  94984. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  94985. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  94986. });
  94987. /**
  94988. * This represents a WebVR camera.
  94989. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  94990. * @example http://doc.babylonjs.com/how_to/webvr_camera
  94991. */
  94992. var WebVRFreeCamera = /** @class */ (function (_super) {
  94993. __extends(WebVRFreeCamera, _super);
  94994. /**
  94995. * Instantiates a WebVRFreeCamera.
  94996. * @param name The name of the WebVRFreeCamera
  94997. * @param position The starting anchor position for the camera
  94998. * @param scene The scene the camera belongs to
  94999. * @param webVROptions a set of customizable options for the webVRCamera
  95000. */
  95001. function WebVRFreeCamera(name, position, scene, webVROptions) {
  95002. if (webVROptions === void 0) { webVROptions = {}; }
  95003. var _this = _super.call(this, name, position, scene) || this;
  95004. _this.webVROptions = webVROptions;
  95005. /**
  95006. * @hidden
  95007. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  95008. */
  95009. _this._vrDevice = null;
  95010. /**
  95011. * The rawPose of the vrDevice.
  95012. */
  95013. _this.rawPose = null;
  95014. _this._specsVersion = "1.1";
  95015. _this._attached = false;
  95016. _this._descendants = [];
  95017. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  95018. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  95019. /** @hidden */
  95020. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  95021. _this._standingMatrix = null;
  95022. /**
  95023. * Represents device position in babylon space.
  95024. */
  95025. _this.devicePosition = BABYLON.Vector3.Zero();
  95026. /**
  95027. * Represents device rotation in babylon space.
  95028. */
  95029. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  95030. /**
  95031. * The scale of the device to be used when translating from device space to babylon space.
  95032. */
  95033. _this.deviceScaleFactor = 1;
  95034. _this._deviceToWorld = BABYLON.Matrix.Identity();
  95035. _this._worldToDevice = BABYLON.Matrix.Identity();
  95036. /**
  95037. * References to the webVR controllers for the vrDevice.
  95038. */
  95039. _this.controllers = [];
  95040. /**
  95041. * Emits an event when a controller is attached.
  95042. */
  95043. _this.onControllersAttachedObservable = new BABYLON.Observable();
  95044. /**
  95045. * Emits an event when a controller's mesh has been loaded;
  95046. */
  95047. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  95048. /**
  95049. * Emits an event when the HMD's pose has been updated.
  95050. */
  95051. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  95052. _this._poseSet = false;
  95053. /**
  95054. * If the rig cameras be used as parent instead of this camera.
  95055. */
  95056. _this.rigParenting = true;
  95057. _this._defaultHeight = undefined;
  95058. _this._htmlElementAttached = null;
  95059. _this._detachIfAttached = function () {
  95060. var vrDisplay = _this.getEngine().getVRDevice();
  95061. if (vrDisplay && !vrDisplay.isPresenting && _this._htmlElementAttached) {
  95062. _this.detachControl(_this._htmlElementAttached);
  95063. }
  95064. };
  95065. _this._workingVector = BABYLON.Vector3.Zero();
  95066. _this._oneVector = BABYLON.Vector3.One();
  95067. _this._workingMatrix = BABYLON.Matrix.Identity();
  95068. _this._tmpMatrix = new BABYLON.Matrix();
  95069. _this._cache.position = BABYLON.Vector3.Zero();
  95070. if (webVROptions.defaultHeight) {
  95071. _this._defaultHeight = webVROptions.defaultHeight;
  95072. _this.position.y = _this._defaultHeight;
  95073. }
  95074. _this.minZ = 0.1;
  95075. //legacy support - the compensation boolean was removed.
  95076. if (arguments.length === 5) {
  95077. _this.webVROptions = arguments[4];
  95078. }
  95079. // default webVR options
  95080. if (_this.webVROptions.trackPosition == undefined) {
  95081. _this.webVROptions.trackPosition = true;
  95082. }
  95083. if (_this.webVROptions.controllerMeshes == undefined) {
  95084. _this.webVROptions.controllerMeshes = true;
  95085. }
  95086. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  95087. _this.webVROptions.defaultLightingOnControllers = true;
  95088. }
  95089. _this.rotationQuaternion = new BABYLON.Quaternion();
  95090. if (_this.webVROptions && _this.webVROptions.positionScale) {
  95091. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  95092. }
  95093. //enable VR
  95094. var engine = _this.getEngine();
  95095. _this._onVREnabled = function (success) { if (success) {
  95096. _this.initControllers();
  95097. } };
  95098. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  95099. engine.initWebVR().add(function (event) {
  95100. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  95101. return;
  95102. }
  95103. _this._vrDevice = event.vrDisplay;
  95104. //reset the rig parameters.
  95105. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  95106. if (_this._attached) {
  95107. _this.getEngine().enableVR();
  95108. }
  95109. });
  95110. if (typeof (VRFrameData) !== "undefined")
  95111. _this._frameData = new VRFrameData();
  95112. /**
  95113. * The idea behind the following lines:
  95114. * objects that have the camera as parent should actually have the rig cameras as a parent.
  95115. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  95116. * the second will not show it correctly.
  95117. *
  95118. * To solve this - each object that has the camera as parent will be added to a protected array.
  95119. * When the rig camera renders, it will take this array and set all of those to be its children.
  95120. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  95121. * Amazing!
  95122. */
  95123. scene.onBeforeCameraRenderObservable.add(function (camera) {
  95124. if (camera.parent === _this && _this.rigParenting) {
  95125. _this._descendants = _this.getDescendants(true, function (n) {
  95126. // don't take the cameras or the controllers!
  95127. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  95128. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  95129. return !isController && !isRigCamera;
  95130. });
  95131. _this._descendants.forEach(function (node) {
  95132. node.parent = camera;
  95133. });
  95134. }
  95135. });
  95136. scene.onAfterCameraRenderObservable.add(function (camera) {
  95137. if (camera.parent === _this && _this.rigParenting) {
  95138. _this._descendants.forEach(function (node) {
  95139. node.parent = _this;
  95140. });
  95141. }
  95142. });
  95143. return _this;
  95144. }
  95145. /**
  95146. * Gets the device distance from the ground in meters.
  95147. * @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.
  95148. */
  95149. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  95150. if (this._standingMatrix) {
  95151. // Add standing matrix offset to get real offset from ground in room
  95152. this._standingMatrix.getTranslationToRef(this._workingVector);
  95153. return this._deviceRoomPosition.y + this._workingVector.y;
  95154. }
  95155. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  95156. return this._defaultHeight || 0;
  95157. };
  95158. /**
  95159. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  95160. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  95161. */
  95162. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  95163. var _this = this;
  95164. if (callback === void 0) { callback = function (bool) { }; }
  95165. // Use standing matrix if available
  95166. this.getEngine().initWebVRAsync().then(function (result) {
  95167. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  95168. callback(false);
  95169. }
  95170. else {
  95171. _this._standingMatrix = new BABYLON.Matrix();
  95172. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  95173. if (!_this.getScene().useRightHandedSystem) {
  95174. [2, 6, 8, 9, 14].forEach(function (num) {
  95175. if (_this._standingMatrix) {
  95176. _this._standingMatrix.m[num] *= -1;
  95177. }
  95178. });
  95179. }
  95180. callback(true);
  95181. }
  95182. });
  95183. };
  95184. /**
  95185. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  95186. * @returns A promise with a boolean set to if the standing matrix is supported.
  95187. */
  95188. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  95189. var _this = this;
  95190. return new Promise(function (res, rej) {
  95191. _this.useStandingMatrix(function (supported) {
  95192. res(supported);
  95193. });
  95194. });
  95195. };
  95196. /**
  95197. * Disposes the camera
  95198. */
  95199. WebVRFreeCamera.prototype.dispose = function () {
  95200. this._detachIfAttached();
  95201. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  95202. _super.prototype.dispose.call(this);
  95203. };
  95204. /**
  95205. * Gets a vrController by name.
  95206. * @param name The name of the controller to retreive
  95207. * @returns the controller matching the name specified or null if not found
  95208. */
  95209. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  95210. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  95211. var gp = _a[_i];
  95212. if (gp.hand === name) {
  95213. return gp;
  95214. }
  95215. }
  95216. return null;
  95217. };
  95218. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  95219. /**
  95220. * The controller corrisponding to the users left hand.
  95221. */
  95222. get: function () {
  95223. if (!this._leftController) {
  95224. this._leftController = this.getControllerByName("left");
  95225. }
  95226. return this._leftController;
  95227. },
  95228. enumerable: true,
  95229. configurable: true
  95230. });
  95231. ;
  95232. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  95233. /**
  95234. * The controller corrisponding to the users right hand.
  95235. */
  95236. get: function () {
  95237. if (!this._rightController) {
  95238. this._rightController = this.getControllerByName("right");
  95239. }
  95240. return this._rightController;
  95241. },
  95242. enumerable: true,
  95243. configurable: true
  95244. });
  95245. ;
  95246. /**
  95247. * Casts a ray forward from the vrCamera's gaze.
  95248. * @param length Length of the ray (default: 100)
  95249. * @returns the ray corrisponding to the gaze
  95250. */
  95251. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  95252. if (length === void 0) { length = 100; }
  95253. if (this.leftCamera) {
  95254. // Use left eye to avoid computation to compute center on every call
  95255. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  95256. }
  95257. else {
  95258. return _super.prototype.getForwardRay.call(this, length);
  95259. }
  95260. };
  95261. /**
  95262. * @hidden
  95263. * Updates the camera based on device's frame data
  95264. */
  95265. WebVRFreeCamera.prototype._checkInputs = function () {
  95266. if (this._vrDevice && this._vrDevice.isPresenting) {
  95267. this._vrDevice.getFrameData(this._frameData);
  95268. this.updateFromDevice(this._frameData.pose);
  95269. }
  95270. _super.prototype._checkInputs.call(this);
  95271. };
  95272. /**
  95273. * Updates the poseControlled values based on the input device pose.
  95274. * @param poseData Pose coming from the device
  95275. */
  95276. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  95277. if (poseData && poseData.orientation) {
  95278. this.rawPose = poseData;
  95279. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  95280. if (this.getScene().useRightHandedSystem) {
  95281. this._deviceRoomRotationQuaternion.z *= -1;
  95282. this._deviceRoomRotationQuaternion.w *= -1;
  95283. }
  95284. if (this.webVROptions.trackPosition && this.rawPose.position) {
  95285. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  95286. if (this.getScene().useRightHandedSystem) {
  95287. this._deviceRoomPosition.z *= -1;
  95288. }
  95289. }
  95290. this._poseSet = true;
  95291. }
  95292. };
  95293. /**
  95294. * WebVR's attach control will start broadcasting frames to the device.
  95295. * Note that in certain browsers (chrome for example) this function must be called
  95296. * within a user-interaction callback. Example:
  95297. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  95298. *
  95299. * @param element html element to attach the vrDevice to
  95300. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  95301. */
  95302. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  95303. _super.prototype.attachControl.call(this, element, noPreventDefault);
  95304. this._attached = true;
  95305. this._htmlElementAttached = element;
  95306. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  95307. if (this._vrDevice) {
  95308. this.getEngine().enableVR();
  95309. }
  95310. window.addEventListener('vrdisplaypresentchange', this._detachIfAttached);
  95311. };
  95312. /**
  95313. * Detaches the camera from the html element and disables VR
  95314. *
  95315. * @param element html element to detach from
  95316. */
  95317. WebVRFreeCamera.prototype.detachControl = function (element) {
  95318. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  95319. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  95320. _super.prototype.detachControl.call(this, element);
  95321. this._attached = false;
  95322. this.getEngine().disableVR();
  95323. window.removeEventListener('vrdisplaypresentchange', this._detachIfAttached);
  95324. };
  95325. /**
  95326. * @returns the name of this class
  95327. */
  95328. WebVRFreeCamera.prototype.getClassName = function () {
  95329. return "WebVRFreeCamera";
  95330. };
  95331. /**
  95332. * Calls resetPose on the vrDisplay
  95333. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  95334. */
  95335. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  95336. //uses the vrDisplay's "resetPose()".
  95337. //pitch and roll won't be affected.
  95338. this._vrDevice.resetPose();
  95339. };
  95340. /**
  95341. * @hidden
  95342. * Updates the rig cameras (left and right eye)
  95343. */
  95344. WebVRFreeCamera.prototype._updateRigCameras = function () {
  95345. var camLeft = this._rigCameras[0];
  95346. var camRight = this._rigCameras[1];
  95347. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  95348. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  95349. camLeft.position.copyFrom(this._deviceRoomPosition);
  95350. camRight.position.copyFrom(this._deviceRoomPosition);
  95351. };
  95352. /**
  95353. * @hidden
  95354. * Updates the cached values of the camera
  95355. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  95356. */
  95357. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  95358. var _this = this;
  95359. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  95360. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  95361. if (!this.updateCacheCalled) {
  95362. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  95363. this.updateCacheCalled = true;
  95364. this.update();
  95365. }
  95366. // Set working vector to the device position in room space rotated by the new rotation
  95367. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  95368. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  95369. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  95370. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  95371. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  95372. // Add translation from anchor position
  95373. this._deviceToWorld.getTranslationToRef(this._workingVector);
  95374. this._workingVector.addInPlace(this.position);
  95375. this._workingVector.subtractInPlace(this._cache.position);
  95376. this._deviceToWorld.setTranslation(this._workingVector);
  95377. // Set an inverted matrix to be used when updating the camera
  95378. this._deviceToWorld.invertToRef(this._worldToDevice);
  95379. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  95380. this.controllers.forEach(function (controller) {
  95381. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  95382. controller.update();
  95383. });
  95384. }
  95385. if (!ignoreParentClass) {
  95386. _super.prototype._updateCache.call(this);
  95387. }
  95388. this.updateCacheCalled = false;
  95389. };
  95390. /**
  95391. * Updates the current device position and rotation in the babylon world
  95392. */
  95393. WebVRFreeCamera.prototype.update = function () {
  95394. // Get current device position in babylon world
  95395. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  95396. // Get current device rotation in babylon world
  95397. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  95398. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  95399. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  95400. if (this._poseSet) {
  95401. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  95402. }
  95403. _super.prototype.update.call(this);
  95404. };
  95405. /**
  95406. * @hidden
  95407. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  95408. * @returns an identity matrix
  95409. */
  95410. WebVRFreeCamera.prototype._getViewMatrix = function () {
  95411. return BABYLON.Matrix.Identity();
  95412. };
  95413. /**
  95414. * This function is called by the two RIG cameras.
  95415. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  95416. */
  95417. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  95418. var _this = this;
  95419. // Update the parent camera prior to using a child camera to avoid desynchronization
  95420. var parentCamera = this._cameraRigParams["parentCamera"];
  95421. parentCamera._updateCache();
  95422. //WebVR 1.1
  95423. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  95424. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  95425. if (!this.getScene().useRightHandedSystem) {
  95426. [2, 6, 8, 9, 14].forEach(function (num) {
  95427. _this._webvrViewMatrix.m[num] *= -1;
  95428. });
  95429. }
  95430. // update the camera rotation matrix
  95431. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  95432. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  95433. // Computing target and final matrix
  95434. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  95435. // should the view matrix be updated with scale and position offset?
  95436. if (parentCamera.deviceScaleFactor !== 1) {
  95437. this._webvrViewMatrix.invert();
  95438. // scale the position, if set
  95439. if (parentCamera.deviceScaleFactor) {
  95440. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  95441. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  95442. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  95443. }
  95444. this._webvrViewMatrix.invert();
  95445. }
  95446. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  95447. // Remove translation from 6dof headset if trackposition is set to false
  95448. if (parentCamera.rawPose && parentCamera.rawPose.position && !parentCamera.webVROptions.trackPosition) {
  95449. BABYLON.Matrix.TranslationToRef(parentCamera.rawPose.position[0], parentCamera.rawPose.position[1], -parentCamera.rawPose.position[2], parentCamera._tmpMatrix);
  95450. parentCamera._tmpMatrix.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  95451. }
  95452. // Compute global position
  95453. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  95454. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  95455. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  95456. this._workingMatrix.getTranslationToRef(this._globalPosition);
  95457. this._markSyncedWithParent();
  95458. return this._webvrViewMatrix;
  95459. };
  95460. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  95461. var _this = this;
  95462. var parentCamera = this.parent;
  95463. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  95464. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  95465. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  95466. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  95467. //babylon compatible matrix
  95468. if (!this.getScene().useRightHandedSystem) {
  95469. [8, 9, 10, 11].forEach(function (num) {
  95470. _this._projectionMatrix.m[num] *= -1;
  95471. });
  95472. }
  95473. return this._projectionMatrix;
  95474. };
  95475. /**
  95476. * Initializes the controllers and their meshes
  95477. */
  95478. WebVRFreeCamera.prototype.initControllers = function () {
  95479. var _this = this;
  95480. this.controllers = [];
  95481. var manager = this.getScene().gamepadManager;
  95482. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  95483. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  95484. var webVrController = gamepad;
  95485. if (webVrController.defaultModel) {
  95486. webVrController.defaultModel.setEnabled(false);
  95487. }
  95488. if (webVrController.hand === "right") {
  95489. _this._rightController = null;
  95490. }
  95491. if (webVrController.hand === "left") {
  95492. _this._leftController = null;
  95493. }
  95494. var controllerIndex = _this.controllers.indexOf(webVrController);
  95495. if (controllerIndex !== -1) {
  95496. _this.controllers.splice(controllerIndex, 1);
  95497. }
  95498. }
  95499. });
  95500. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  95501. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  95502. var webVrController_1 = gamepad;
  95503. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  95504. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  95505. if (_this.webVROptions.controllerMeshes) {
  95506. if (webVrController_1.defaultModel) {
  95507. webVrController_1.defaultModel.setEnabled(true);
  95508. }
  95509. else {
  95510. // Load the meshes
  95511. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  95512. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  95513. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  95514. if (_this.webVROptions.defaultLightingOnControllers) {
  95515. if (!_this._lightOnControllers) {
  95516. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  95517. }
  95518. var activateLightOnSubMeshes_1 = function (mesh, light) {
  95519. var children = mesh.getChildren();
  95520. if (children.length !== 0) {
  95521. children.forEach(function (mesh) {
  95522. light.includedOnlyMeshes.push(mesh);
  95523. activateLightOnSubMeshes_1(mesh, light);
  95524. });
  95525. }
  95526. };
  95527. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  95528. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  95529. }
  95530. });
  95531. }
  95532. }
  95533. webVrController_1.attachToPoseControlledCamera(_this);
  95534. // since this is async - sanity check. Is the controller already stored?
  95535. if (_this.controllers.indexOf(webVrController_1) === -1) {
  95536. //add to the controllers array
  95537. _this.controllers.push(webVrController_1);
  95538. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  95539. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  95540. // So we're overriding setting left & right manually to be sure
  95541. var firstViveWandDetected = false;
  95542. for (var i = 0; i < _this.controllers.length; i++) {
  95543. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  95544. if (!firstViveWandDetected) {
  95545. firstViveWandDetected = true;
  95546. _this.controllers[i].hand = "left";
  95547. }
  95548. else {
  95549. _this.controllers[i].hand = "right";
  95550. }
  95551. }
  95552. }
  95553. //did we find enough controllers? Great! let the developer know.
  95554. if (_this.controllers.length >= 2) {
  95555. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  95556. }
  95557. }
  95558. }
  95559. });
  95560. };
  95561. return WebVRFreeCamera;
  95562. }(BABYLON.FreeCamera));
  95563. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  95564. })(BABYLON || (BABYLON = {}));
  95565. //# sourceMappingURL=babylon.webVRCamera.js.map
  95566. var BABYLON;
  95567. (function (BABYLON) {
  95568. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  95569. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  95570. });
  95571. // We're mainly based on the logic defined into the FreeCamera code
  95572. /**
  95573. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  95574. * being tilted forward or back and left or right.
  95575. */
  95576. var DeviceOrientationCamera = /** @class */ (function (_super) {
  95577. __extends(DeviceOrientationCamera, _super);
  95578. /**
  95579. * Creates a new device orientation camera
  95580. * @param name The name of the camera
  95581. * @param position The start position camera
  95582. * @param scene The scene the camera belongs to
  95583. */
  95584. function DeviceOrientationCamera(name, position, scene) {
  95585. var _this = _super.call(this, name, position, scene) || this;
  95586. _this._quaternionCache = new BABYLON.Quaternion();
  95587. _this.inputs.addDeviceOrientation();
  95588. return _this;
  95589. }
  95590. /**
  95591. * Gets the current instance class name ("DeviceOrientationCamera").
  95592. * This helps avoiding instanceof at run time.
  95593. * @returns the class name
  95594. */
  95595. DeviceOrientationCamera.prototype.getClassName = function () {
  95596. return "DeviceOrientationCamera";
  95597. };
  95598. /**
  95599. * @hidden
  95600. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  95601. */
  95602. DeviceOrientationCamera.prototype._checkInputs = function () {
  95603. _super.prototype._checkInputs.call(this);
  95604. this._quaternionCache.copyFrom(this.rotationQuaternion);
  95605. if (this._initialQuaternion) {
  95606. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  95607. }
  95608. };
  95609. /**
  95610. * Reset the camera to its default orientation on the specified axis only.
  95611. * @param axis The axis to reset
  95612. */
  95613. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  95614. var _this = this;
  95615. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  95616. //can only work if this camera has a rotation quaternion already.
  95617. if (!this.rotationQuaternion)
  95618. return;
  95619. if (!this._initialQuaternion) {
  95620. this._initialQuaternion = new BABYLON.Quaternion();
  95621. }
  95622. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  95623. ['x', 'y', 'z'].forEach(function (axisName) {
  95624. if (!axis[axisName]) {
  95625. _this._initialQuaternion[axisName] = 0;
  95626. }
  95627. else {
  95628. _this._initialQuaternion[axisName] *= -1;
  95629. }
  95630. });
  95631. this._initialQuaternion.normalize();
  95632. //force rotation update
  95633. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  95634. };
  95635. return DeviceOrientationCamera;
  95636. }(BABYLON.FreeCamera));
  95637. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  95638. })(BABYLON || (BABYLON = {}));
  95639. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  95640. var BABYLON;
  95641. (function (BABYLON) {
  95642. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  95643. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  95644. });
  95645. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  95646. __extends(VRDeviceOrientationFreeCamera, _super);
  95647. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  95648. if (compensateDistortion === void 0) { compensateDistortion = true; }
  95649. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  95650. var _this = _super.call(this, name, position, scene) || this;
  95651. vrCameraMetrics.compensateDistortion = compensateDistortion;
  95652. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  95653. return _this;
  95654. }
  95655. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  95656. return "VRDeviceOrientationFreeCamera";
  95657. };
  95658. return VRDeviceOrientationFreeCamera;
  95659. }(BABYLON.DeviceOrientationCamera));
  95660. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  95661. })(BABYLON || (BABYLON = {}));
  95662. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  95663. var BABYLON;
  95664. (function (BABYLON) {
  95665. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  95666. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  95667. });
  95668. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  95669. __extends(VRDeviceOrientationArcRotateCamera, _super);
  95670. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  95671. if (compensateDistortion === void 0) { compensateDistortion = true; }
  95672. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  95673. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  95674. vrCameraMetrics.compensateDistortion = compensateDistortion;
  95675. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  95676. _this.inputs.addVRDeviceOrientation();
  95677. return _this;
  95678. }
  95679. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  95680. return "VRDeviceOrientationArcRotateCamera";
  95681. };
  95682. return VRDeviceOrientationArcRotateCamera;
  95683. }(BABYLON.ArcRotateCamera));
  95684. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  95685. })(BABYLON || (BABYLON = {}));
  95686. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  95687. var BABYLON;
  95688. (function (BABYLON) {
  95689. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  95690. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  95691. });
  95692. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  95693. __extends(VRDeviceOrientationGamepadCamera, _super);
  95694. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  95695. if (compensateDistortion === void 0) { compensateDistortion = true; }
  95696. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  95697. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  95698. _this.inputs.addGamepad();
  95699. return _this;
  95700. }
  95701. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  95702. return "VRDeviceOrientationGamepadCamera";
  95703. };
  95704. return VRDeviceOrientationGamepadCamera;
  95705. }(BABYLON.VRDeviceOrientationFreeCamera));
  95706. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  95707. })(BABYLON || (BABYLON = {}));
  95708. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  95709. var BABYLON;
  95710. (function (BABYLON) {
  95711. var VRExperienceHelperGazer = /** @class */ (function () {
  95712. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  95713. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  95714. this.scene = scene;
  95715. /** @hidden */
  95716. this._pointerDownOnMeshAsked = false;
  95717. /** @hidden */
  95718. this._isActionableMesh = false;
  95719. /** @hidden */
  95720. this._teleportationRequestInitiated = false;
  95721. /** @hidden */
  95722. this._teleportationBackRequestInitiated = false;
  95723. /** @hidden */
  95724. this._rotationRightAsked = false;
  95725. /** @hidden */
  95726. this._rotationLeftAsked = false;
  95727. /** @hidden */
  95728. this._dpadPressed = true;
  95729. /** @hidden */
  95730. this._activePointer = false;
  95731. this._id = VRExperienceHelperGazer._idCounter++;
  95732. // Gaze tracker
  95733. if (!gazeTrackerToClone) {
  95734. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  95735. this._gazeTracker.bakeCurrentTransformIntoVertices();
  95736. this._gazeTracker.isPickable = false;
  95737. this._gazeTracker.isVisible = false;
  95738. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  95739. targetMat.specularColor = BABYLON.Color3.Black();
  95740. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  95741. targetMat.backFaceCulling = false;
  95742. this._gazeTracker.material = targetMat;
  95743. }
  95744. else {
  95745. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  95746. }
  95747. }
  95748. /** @hidden */
  95749. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  95750. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  95751. };
  95752. /** @hidden */
  95753. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  95754. this._pointerDownOnMeshAsked = true;
  95755. if (this._currentHit) {
  95756. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  95757. }
  95758. };
  95759. /** @hidden */
  95760. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  95761. if (this._currentHit) {
  95762. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  95763. }
  95764. this._pointerDownOnMeshAsked = false;
  95765. };
  95766. /** @hidden */
  95767. VRExperienceHelperGazer.prototype._activatePointer = function () {
  95768. this._activePointer = true;
  95769. };
  95770. /** @hidden */
  95771. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  95772. this._activePointer = false;
  95773. };
  95774. /** @hidden */
  95775. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  95776. if (distance === void 0) { distance = 100; }
  95777. };
  95778. VRExperienceHelperGazer.prototype.dispose = function () {
  95779. this._interactionsEnabled = false;
  95780. this._teleportationEnabled = false;
  95781. if (this._gazeTracker) {
  95782. this._gazeTracker.dispose();
  95783. }
  95784. };
  95785. VRExperienceHelperGazer._idCounter = 0;
  95786. return VRExperienceHelperGazer;
  95787. }());
  95788. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  95789. __extends(VRExperienceHelperControllerGazer, _super);
  95790. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  95791. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  95792. _this.webVRController = webVRController;
  95793. // Laser pointer
  95794. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  95795. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  95796. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  95797. laserPointerMaterial.alpha = 0.6;
  95798. _this._laserPointer.material = laserPointerMaterial;
  95799. _this._laserPointer.rotation.x = Math.PI / 2;
  95800. _this._laserPointer.position.z = -0.5;
  95801. _this._laserPointer.isVisible = false;
  95802. _this._laserPointer.isPickable = false;
  95803. if (!webVRController.mesh) {
  95804. // Create an empty mesh that is used prior to loading the high quality model
  95805. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  95806. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  95807. preloadPointerPose.rotation.x = -0.7;
  95808. preloadMesh.addChild(preloadPointerPose);
  95809. webVRController.attachToMesh(preloadMesh);
  95810. }
  95811. _this._setLaserPointerParent(webVRController.mesh);
  95812. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  95813. _this._setLaserPointerParent(mesh);
  95814. });
  95815. return _this;
  95816. }
  95817. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  95818. return this.webVRController.getForwardRay(length);
  95819. };
  95820. /** @hidden */
  95821. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  95822. _super.prototype._activatePointer.call(this);
  95823. this._laserPointer.isVisible = true;
  95824. };
  95825. /** @hidden */
  95826. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  95827. _super.prototype._deactivatePointer.call(this);
  95828. this._laserPointer.isVisible = false;
  95829. };
  95830. /** @hidden */
  95831. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  95832. this._laserPointer.material.emissiveColor = color;
  95833. };
  95834. /** @hidden */
  95835. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  95836. var makeNotPick = function (root) {
  95837. root.isPickable = false;
  95838. root.getChildMeshes().forEach(function (c) {
  95839. makeNotPick(c);
  95840. });
  95841. };
  95842. makeNotPick(mesh);
  95843. var childMeshes = mesh.getChildMeshes();
  95844. this.webVRController._pointingPoseNode = null;
  95845. for (var i = 0; i < childMeshes.length; i++) {
  95846. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  95847. mesh = childMeshes[i];
  95848. this.webVRController._pointingPoseNode = mesh;
  95849. break;
  95850. }
  95851. }
  95852. this._laserPointer.parent = mesh;
  95853. };
  95854. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  95855. if (distance === void 0) { distance = 100; }
  95856. this._laserPointer.scaling.y = distance;
  95857. this._laserPointer.position.z = -distance / 2;
  95858. };
  95859. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  95860. _super.prototype.dispose.call(this);
  95861. this._laserPointer.dispose();
  95862. if (this._meshAttachedObserver) {
  95863. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  95864. }
  95865. };
  95866. return VRExperienceHelperControllerGazer;
  95867. }(VRExperienceHelperGazer));
  95868. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  95869. __extends(VRExperienceHelperCameraGazer, _super);
  95870. function VRExperienceHelperCameraGazer(getCamera, scene) {
  95871. var _this = _super.call(this, scene) || this;
  95872. _this.getCamera = getCamera;
  95873. return _this;
  95874. }
  95875. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  95876. var camera = this.getCamera();
  95877. if (camera) {
  95878. return camera.getForwardRay(length);
  95879. }
  95880. else {
  95881. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  95882. }
  95883. };
  95884. return VRExperienceHelperCameraGazer;
  95885. }(VRExperienceHelperGazer));
  95886. /**
  95887. * Helps to quickly add VR support to an existing scene.
  95888. * See http://doc.babylonjs.com/how_to/webvr_helper
  95889. */
  95890. var VRExperienceHelper = /** @class */ (function () {
  95891. /**
  95892. * Instantiates a VRExperienceHelper.
  95893. * Helps to quickly add VR support to an existing scene.
  95894. * @param scene The scene the VRExperienceHelper belongs to.
  95895. * @param webVROptions Options to modify the vr experience helper's behavior.
  95896. */
  95897. function VRExperienceHelper(scene,
  95898. /** Options to modify the vr experience helper's behavior. */
  95899. webVROptions) {
  95900. if (webVROptions === void 0) { webVROptions = {}; }
  95901. var _this = this;
  95902. this.webVROptions = webVROptions;
  95903. // Can the system support WebVR, even if a headset isn't plugged in?
  95904. this._webVRsupported = false;
  95905. // If WebVR is supported, is a headset plugged in and are we ready to present?
  95906. this._webVRready = false;
  95907. // Are we waiting for the requestPresent callback to complete?
  95908. this._webVRrequesting = false;
  95909. // Are we presenting to the headset right now? (this is the vrDevice state)
  95910. this._webVRpresenting = false;
  95911. // Are we presenting in the fullscreen fallback?
  95912. this._fullscreenVRpresenting = false;
  95913. /**
  95914. * Observable raised when entering VR.
  95915. */
  95916. this.onEnteringVRObservable = new BABYLON.Observable();
  95917. /**
  95918. * Observable raised when exiting VR.
  95919. */
  95920. this.onExitingVRObservable = new BABYLON.Observable();
  95921. /**
  95922. * Observable raised when controller mesh is loaded.
  95923. */
  95924. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  95925. this._useCustomVRButton = false;
  95926. this._teleportationRequested = false;
  95927. this._teleportActive = false;
  95928. this._floorMeshesCollection = [];
  95929. this._rotationAllowed = true;
  95930. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  95931. this._isDefaultTeleportationTarget = true;
  95932. this._teleportationFillColor = "#444444";
  95933. this._teleportationBorderColor = "#FFFFFF";
  95934. this._rotationAngle = 0;
  95935. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  95936. this._padSensibilityUp = 0.65;
  95937. this._padSensibilityDown = 0.35;
  95938. this._leftController = null;
  95939. this._rightController = null;
  95940. /**
  95941. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  95942. */
  95943. this.onNewMeshSelected = new BABYLON.Observable();
  95944. /**
  95945. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  95946. */
  95947. this.onNewMeshPicked = new BABYLON.Observable();
  95948. /**
  95949. * Observable raised before camera teleportation
  95950. */
  95951. this.onBeforeCameraTeleport = new BABYLON.Observable();
  95952. /**
  95953. * Observable raised after camera teleportation
  95954. */
  95955. this.onAfterCameraTeleport = new BABYLON.Observable();
  95956. /**
  95957. * Observable raised when current selected mesh gets unselected
  95958. */
  95959. this.onSelectedMeshUnselected = new BABYLON.Observable();
  95960. /**
  95961. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  95962. */
  95963. this.teleportationEnabled = true;
  95964. this._teleportationInitialized = false;
  95965. this._interactionsEnabled = false;
  95966. this._interactionsRequested = false;
  95967. this._displayGaze = true;
  95968. this._displayLaserPointer = true;
  95969. /**
  95970. * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes
  95971. */
  95972. this.updateGazeTrackerScale = true;
  95973. this._onResize = function () {
  95974. _this.moveButtonToBottomRight();
  95975. if (_this._fullscreenVRpresenting && _this._webVRready) {
  95976. _this.exitVR();
  95977. }
  95978. };
  95979. this._onFullscreenChange = function () {
  95980. if (document.fullscreen !== undefined) {
  95981. _this._fullscreenVRpresenting = document.fullscreen;
  95982. }
  95983. else if (document.mozFullScreen !== undefined) {
  95984. _this._fullscreenVRpresenting = document.mozFullScreen;
  95985. }
  95986. else if (document.webkitIsFullScreen !== undefined) {
  95987. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  95988. }
  95989. else if (document.msIsFullScreen !== undefined) {
  95990. _this._fullscreenVRpresenting = document.msIsFullScreen;
  95991. }
  95992. else if (document.msFullscreenElement !== undefined) {
  95993. _this._fullscreenVRpresenting = document.msFullscreenElement;
  95994. }
  95995. if (!_this._fullscreenVRpresenting && _this._canvas) {
  95996. _this.exitVR();
  95997. if (!_this._useCustomVRButton) {
  95998. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  95999. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  96000. }
  96001. }
  96002. };
  96003. this.beforeRender = function () {
  96004. if (_this._leftController && _this._leftController._activePointer) {
  96005. _this._castRayAndSelectObject(_this._leftController);
  96006. }
  96007. if (_this._rightController && _this._rightController._activePointer) {
  96008. _this._castRayAndSelectObject(_this._rightController);
  96009. }
  96010. if (_this._noControllerIsActive) {
  96011. _this._castRayAndSelectObject(_this._cameraGazer);
  96012. }
  96013. else {
  96014. _this._cameraGazer._gazeTracker.isVisible = false;
  96015. }
  96016. };
  96017. this._onNewGamepadConnected = function (gamepad) {
  96018. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  96019. if (gamepad.leftStick) {
  96020. gamepad.onleftstickchanged(function (stickValues) {
  96021. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  96022. // Listening to classic/xbox gamepad only if no VR controller is active
  96023. if ((!_this._leftController && !_this._rightController) ||
  96024. ((_this._leftController && !_this._leftController._activePointer) &&
  96025. (_this._rightController && !_this._rightController._activePointer))) {
  96026. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  96027. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  96028. }
  96029. }
  96030. });
  96031. }
  96032. if (gamepad.rightStick) {
  96033. gamepad.onrightstickchanged(function (stickValues) {
  96034. if (_this._teleportationInitialized) {
  96035. _this._checkRotate(stickValues, _this._cameraGazer);
  96036. }
  96037. });
  96038. }
  96039. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  96040. gamepad.onbuttondown(function (buttonPressed) {
  96041. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  96042. _this._cameraGazer._selectionPointerDown();
  96043. }
  96044. });
  96045. gamepad.onbuttonup(function (buttonPressed) {
  96046. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  96047. _this._cameraGazer._selectionPointerUp();
  96048. }
  96049. });
  96050. }
  96051. }
  96052. else {
  96053. var webVRController = gamepad;
  96054. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  96055. if (webVRController.hand === "right" || (_this._leftController && _this._leftController.webVRController != webVRController)) {
  96056. _this._rightController = controller;
  96057. }
  96058. else {
  96059. _this._leftController = controller;
  96060. }
  96061. _this._tryEnableInteractionOnController(controller);
  96062. }
  96063. };
  96064. // 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
  96065. this._tryEnableInteractionOnController = function (controller) {
  96066. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  96067. _this._enableInteractionOnController(controller);
  96068. }
  96069. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  96070. _this._enableTeleportationOnController(controller);
  96071. }
  96072. };
  96073. this._onNewGamepadDisconnected = function (gamepad) {
  96074. if (gamepad instanceof BABYLON.WebVRController) {
  96075. if (gamepad.hand === "left" && _this._leftController != null) {
  96076. _this._leftController.dispose();
  96077. _this._leftController = null;
  96078. }
  96079. if (gamepad.hand === "right" && _this._rightController != null) {
  96080. _this._rightController.dispose();
  96081. _this._rightController = null;
  96082. }
  96083. }
  96084. };
  96085. this._workingVector = BABYLON.Vector3.Zero();
  96086. this._workingQuaternion = BABYLON.Quaternion.Identity();
  96087. this._workingMatrix = BABYLON.Matrix.Identity();
  96088. this._scene = scene;
  96089. this._canvas = scene.getEngine().getRenderingCanvas();
  96090. // Parse options
  96091. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  96092. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  96093. }
  96094. if (webVROptions.createDeviceOrientationCamera === undefined) {
  96095. webVROptions.createDeviceOrientationCamera = true;
  96096. }
  96097. if (webVROptions.laserToggle === undefined) {
  96098. webVROptions.laserToggle = true;
  96099. }
  96100. if (webVROptions.defaultHeight === undefined) {
  96101. webVROptions.defaultHeight = 1.7;
  96102. }
  96103. if (webVROptions.useCustomVRButton) {
  96104. this._useCustomVRButton = true;
  96105. if (webVROptions.customVRButton) {
  96106. this._btnVR = webVROptions.customVRButton;
  96107. }
  96108. }
  96109. if (webVROptions.rayLength) {
  96110. this._rayLength = webVROptions.rayLength;
  96111. }
  96112. this._defaultHeight = webVROptions.defaultHeight;
  96113. if (webVROptions.positionScale) {
  96114. this._rayLength *= webVROptions.positionScale;
  96115. this._defaultHeight *= webVROptions.positionScale;
  96116. }
  96117. this._hasEnteredVR = false;
  96118. // Set position
  96119. if (this._scene.activeCamera) {
  96120. this._position = this._scene.activeCamera.position.clone();
  96121. }
  96122. else {
  96123. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  96124. }
  96125. // Set non-vr camera
  96126. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  96127. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  96128. // Copy data from existing camera
  96129. if (this._scene.activeCamera) {
  96130. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  96131. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  96132. // Set rotation from previous camera
  96133. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  96134. var targetCamera = this._scene.activeCamera;
  96135. if (targetCamera.rotationQuaternion) {
  96136. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  96137. }
  96138. else {
  96139. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  96140. }
  96141. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  96142. }
  96143. }
  96144. this._scene.activeCamera = this._deviceOrientationCamera;
  96145. if (this._canvas) {
  96146. this._scene.activeCamera.attachControl(this._canvas);
  96147. }
  96148. }
  96149. else {
  96150. this._existingCamera = this._scene.activeCamera;
  96151. }
  96152. // Create VR cameras
  96153. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  96154. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  96155. }
  96156. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  96157. this._webVRCamera.useStandingMatrix();
  96158. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  96159. // Create default button
  96160. if (!this._useCustomVRButton) {
  96161. this._btnVR = document.createElement("BUTTON");
  96162. this._btnVR.className = "babylonVRicon";
  96163. this._btnVR.id = "babylonVRiconbtn";
  96164. this._btnVR.title = "Click to switch to VR";
  96165. 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) }";
  96166. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  96167. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  96168. // css += ".babylonVRicon.vrdisplaysupported { }";
  96169. // css += ".babylonVRicon.vrdisplayready { }";
  96170. // css += ".babylonVRicon.vrdisplayrequesting { }";
  96171. var style = document.createElement('style');
  96172. style.appendChild(document.createTextNode(css));
  96173. document.getElementsByTagName('head')[0].appendChild(style);
  96174. this.moveButtonToBottomRight();
  96175. }
  96176. // VR button click event
  96177. if (this._btnVR) {
  96178. this._btnVR.addEventListener("click", function () {
  96179. if (!_this.isInVRMode) {
  96180. _this.enterVR();
  96181. }
  96182. else {
  96183. _this.exitVR();
  96184. }
  96185. });
  96186. }
  96187. // Window events
  96188. window.addEventListener("resize", this._onResize);
  96189. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  96190. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  96191. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  96192. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  96193. document.onmsfullscreenchange = this._onFullscreenChange;
  96194. // Display vr button when headset is connected
  96195. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  96196. this.displayVRButton();
  96197. }
  96198. else {
  96199. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  96200. if (e.vrDisplay) {
  96201. _this.displayVRButton();
  96202. }
  96203. });
  96204. }
  96205. // Exiting VR mode using 'ESC' key on desktop
  96206. this._onKeyDown = function (event) {
  96207. if (event.keyCode === 27 && _this.isInVRMode) {
  96208. _this.exitVR();
  96209. }
  96210. };
  96211. document.addEventListener("keydown", this._onKeyDown);
  96212. // Exiting VR mode double tapping the touch screen
  96213. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  96214. if (_this.isInVRMode) {
  96215. _this.exitVR();
  96216. if (_this._fullscreenVRpresenting) {
  96217. _this._scene.getEngine().switchFullscreen(true);
  96218. }
  96219. }
  96220. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  96221. // Listen for WebVR display changes
  96222. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  96223. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  96224. this._onVRRequestPresentStart = function () {
  96225. _this._webVRrequesting = true;
  96226. _this.updateButtonVisibility();
  96227. };
  96228. this._onVRRequestPresentComplete = function (success) {
  96229. _this._webVRrequesting = false;
  96230. _this.updateButtonVisibility();
  96231. };
  96232. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  96233. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  96234. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  96235. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  96236. scene.onDisposeObservable.add(function () {
  96237. _this.dispose();
  96238. });
  96239. // Gamepad connection events
  96240. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  96241. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  96242. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  96243. this.updateButtonVisibility();
  96244. //create easing functions
  96245. this._circleEase = new BABYLON.CircleEase();
  96246. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  96247. if (this.webVROptions.floorMeshes) {
  96248. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  96249. }
  96250. }
  96251. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  96252. /** Return this.onEnteringVRObservable
  96253. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  96254. */
  96255. get: function () {
  96256. return this.onEnteringVRObservable;
  96257. },
  96258. enumerable: true,
  96259. configurable: true
  96260. });
  96261. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  96262. /** Return this.onExitingVRObservable
  96263. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  96264. */
  96265. get: function () {
  96266. return this.onExitingVRObservable;
  96267. },
  96268. enumerable: true,
  96269. configurable: true
  96270. });
  96271. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  96272. /** Return this.onControllerMeshLoadedObservable
  96273. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  96274. */
  96275. get: function () {
  96276. return this.onControllerMeshLoadedObservable;
  96277. },
  96278. enumerable: true,
  96279. configurable: true
  96280. });
  96281. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  96282. /**
  96283. * The mesh used to display where the user is going to teleport.
  96284. */
  96285. get: function () {
  96286. return this._teleportationTarget;
  96287. },
  96288. /**
  96289. * Sets the mesh to be used to display where the user is going to teleport.
  96290. */
  96291. set: function (value) {
  96292. if (value) {
  96293. value.name = "teleportationTarget";
  96294. this._isDefaultTeleportationTarget = false;
  96295. this._teleportationTarget = value;
  96296. }
  96297. },
  96298. enumerable: true,
  96299. configurable: true
  96300. });
  96301. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  96302. /**
  96303. * The mesh used to display where the user is selecting, this mesh will be cloned and set as the gazeTracker for the left and right controller
  96304. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  96305. * See http://doc.babylonjs.com/resources/baking_transformations
  96306. */
  96307. get: function () {
  96308. return this._cameraGazer._gazeTracker;
  96309. },
  96310. set: function (value) {
  96311. if (value) {
  96312. // Dispose of existing meshes
  96313. if (this._cameraGazer._gazeTracker) {
  96314. this._cameraGazer._gazeTracker.dispose();
  96315. }
  96316. if (this._leftController && this._leftController._gazeTracker) {
  96317. this._leftController._gazeTracker.dispose();
  96318. }
  96319. if (this._rightController && this._rightController._gazeTracker) {
  96320. this._rightController._gazeTracker.dispose();
  96321. }
  96322. // Set and create gaze trackers on head and controllers
  96323. this._cameraGazer._gazeTracker = value;
  96324. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  96325. this._cameraGazer._gazeTracker.isPickable = false;
  96326. this._cameraGazer._gazeTracker.isVisible = false;
  96327. this._cameraGazer._gazeTracker.name = "gazeTracker";
  96328. if (this._leftController) {
  96329. this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  96330. }
  96331. if (this._rightController) {
  96332. this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  96333. }
  96334. }
  96335. },
  96336. enumerable: true,
  96337. configurable: true
  96338. });
  96339. Object.defineProperty(VRExperienceHelper.prototype, "leftControllerGazeTrackerMesh", {
  96340. /**
  96341. * The gaze tracking mesh corresponding to the left controller
  96342. */
  96343. get: function () {
  96344. if (this._leftController) {
  96345. return this._leftController._gazeTracker;
  96346. }
  96347. return null;
  96348. },
  96349. enumerable: true,
  96350. configurable: true
  96351. });
  96352. Object.defineProperty(VRExperienceHelper.prototype, "rightControllerGazeTrackerMesh", {
  96353. /**
  96354. * The gaze tracking mesh corresponding to the right controller
  96355. */
  96356. get: function () {
  96357. if (this._rightController) {
  96358. return this._rightController._gazeTracker;
  96359. }
  96360. return null;
  96361. },
  96362. enumerable: true,
  96363. configurable: true
  96364. });
  96365. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  96366. /**
  96367. * If the ray of the gaze should be displayed.
  96368. */
  96369. get: function () {
  96370. return this._displayGaze;
  96371. },
  96372. /**
  96373. * Sets if the ray of the gaze should be displayed.
  96374. */
  96375. set: function (value) {
  96376. this._displayGaze = value;
  96377. if (!value) {
  96378. this._cameraGazer._gazeTracker.isVisible = false;
  96379. if (this._leftController) {
  96380. this._leftController._gazeTracker.isVisible = false;
  96381. }
  96382. if (this._rightController) {
  96383. this._rightController._gazeTracker.isVisible = false;
  96384. }
  96385. }
  96386. },
  96387. enumerable: true,
  96388. configurable: true
  96389. });
  96390. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  96391. /**
  96392. * If the ray of the LaserPointer should be displayed.
  96393. */
  96394. get: function () {
  96395. return this._displayLaserPointer;
  96396. },
  96397. /**
  96398. * Sets if the ray of the LaserPointer should be displayed.
  96399. */
  96400. set: function (value) {
  96401. this._displayLaserPointer = value;
  96402. if (!value) {
  96403. if (this._rightController) {
  96404. this._rightController._deactivatePointer();
  96405. this._rightController._gazeTracker.isVisible = false;
  96406. }
  96407. if (this._leftController) {
  96408. this._leftController._deactivatePointer();
  96409. this._leftController._gazeTracker.isVisible = false;
  96410. }
  96411. }
  96412. else {
  96413. if (this._rightController) {
  96414. this._rightController._activatePointer();
  96415. }
  96416. if (this._leftController) {
  96417. this._leftController._activatePointer();
  96418. }
  96419. }
  96420. },
  96421. enumerable: true,
  96422. configurable: true
  96423. });
  96424. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  96425. /**
  96426. * The deviceOrientationCamera used as the camera when not in VR.
  96427. */
  96428. get: function () {
  96429. return this._deviceOrientationCamera;
  96430. },
  96431. enumerable: true,
  96432. configurable: true
  96433. });
  96434. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  96435. /**
  96436. * Based on the current WebVR support, returns the current VR camera used.
  96437. */
  96438. get: function () {
  96439. if (this._webVRready) {
  96440. return this._webVRCamera;
  96441. }
  96442. else {
  96443. return this._scene.activeCamera;
  96444. }
  96445. },
  96446. enumerable: true,
  96447. configurable: true
  96448. });
  96449. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  96450. /**
  96451. * The webVRCamera which is used when in VR.
  96452. */
  96453. get: function () {
  96454. return this._webVRCamera;
  96455. },
  96456. enumerable: true,
  96457. configurable: true
  96458. });
  96459. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  96460. /**
  96461. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  96462. */
  96463. get: function () {
  96464. return this._vrDeviceOrientationCamera;
  96465. },
  96466. enumerable: true,
  96467. configurable: true
  96468. });
  96469. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  96470. get: function () {
  96471. var result = this._cameraGazer._teleportationRequestInitiated
  96472. || (this._leftController !== null && this._leftController._teleportationRequestInitiated)
  96473. || (this._rightController !== null && this._rightController._teleportationRequestInitiated);
  96474. return result;
  96475. },
  96476. enumerable: true,
  96477. configurable: true
  96478. });
  96479. // Raised when one of the controller has loaded successfully its associated default mesh
  96480. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  96481. if (this._leftController && this._leftController.webVRController == webVRController) {
  96482. if (webVRController.mesh) {
  96483. this._leftController._setLaserPointerParent(webVRController.mesh);
  96484. }
  96485. }
  96486. if (this._rightController && this._rightController.webVRController == webVRController) {
  96487. if (webVRController.mesh) {
  96488. this._rightController._setLaserPointerParent(webVRController.mesh);
  96489. }
  96490. }
  96491. try {
  96492. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  96493. }
  96494. catch (err) {
  96495. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  96496. }
  96497. };
  96498. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  96499. /**
  96500. * Gets a value indicating if we are currently in VR mode.
  96501. */
  96502. get: function () {
  96503. return this._webVRpresenting || this._fullscreenVRpresenting;
  96504. },
  96505. enumerable: true,
  96506. configurable: true
  96507. });
  96508. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  96509. var vrDisplay = this._scene.getEngine().getVRDevice();
  96510. if (vrDisplay) {
  96511. var wasPresenting = this._webVRpresenting;
  96512. this._webVRpresenting = vrDisplay.isPresenting;
  96513. if (wasPresenting && !this._webVRpresenting)
  96514. this.exitVR();
  96515. }
  96516. else {
  96517. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  96518. }
  96519. this.updateButtonVisibility();
  96520. };
  96521. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  96522. this._webVRsupported = eventArgs.vrSupported;
  96523. this._webVRready = !!eventArgs.vrDisplay;
  96524. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  96525. this.updateButtonVisibility();
  96526. };
  96527. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  96528. if (this._canvas && !this._useCustomVRButton) {
  96529. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  96530. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  96531. }
  96532. };
  96533. VRExperienceHelper.prototype.displayVRButton = function () {
  96534. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  96535. document.body.appendChild(this._btnVR);
  96536. this._btnVRDisplayed = true;
  96537. }
  96538. };
  96539. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  96540. if (!this._btnVR || this._useCustomVRButton) {
  96541. return;
  96542. }
  96543. this._btnVR.className = "babylonVRicon";
  96544. if (this.isInVRMode) {
  96545. this._btnVR.className += " vrdisplaypresenting";
  96546. }
  96547. else {
  96548. if (this._webVRready)
  96549. this._btnVR.className += " vrdisplayready";
  96550. if (this._webVRsupported)
  96551. this._btnVR.className += " vrdisplaysupported";
  96552. if (this._webVRrequesting)
  96553. this._btnVR.className += " vrdisplayrequesting";
  96554. }
  96555. };
  96556. /**
  96557. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  96558. * Otherwise, will use the fullscreen API.
  96559. */
  96560. VRExperienceHelper.prototype.enterVR = function () {
  96561. if (this.onEnteringVRObservable) {
  96562. try {
  96563. this.onEnteringVRObservable.notifyObservers(this);
  96564. }
  96565. catch (err) {
  96566. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  96567. }
  96568. }
  96569. if (this._scene.activeCamera) {
  96570. this._position = this._scene.activeCamera.position.clone();
  96571. // make sure that we return to the last active camera
  96572. this._existingCamera = this._scene.activeCamera;
  96573. }
  96574. if (this._webVRrequesting)
  96575. return;
  96576. // If WebVR is supported and a headset is connected
  96577. if (this._webVRready) {
  96578. if (!this._webVRpresenting) {
  96579. this._webVRCamera.position = this._position;
  96580. this._scene.activeCamera = this._webVRCamera;
  96581. }
  96582. }
  96583. else if (this._vrDeviceOrientationCamera) {
  96584. this._vrDeviceOrientationCamera.position = this._position;
  96585. if (this._scene.activeCamera) {
  96586. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  96587. }
  96588. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  96589. this._scene.getEngine().switchFullscreen(true);
  96590. this.updateButtonVisibility();
  96591. }
  96592. if (this._scene.activeCamera && this._canvas) {
  96593. this._scene.activeCamera.attachControl(this._canvas);
  96594. }
  96595. if (this._interactionsEnabled) {
  96596. this._scene.registerBeforeRender(this.beforeRender);
  96597. }
  96598. this._hasEnteredVR = true;
  96599. };
  96600. /**
  96601. * Attempt to exit VR, or fullscreen.
  96602. */
  96603. VRExperienceHelper.prototype.exitVR = function () {
  96604. if (this._hasEnteredVR) {
  96605. if (this.onExitingVRObservable) {
  96606. try {
  96607. this.onExitingVRObservable.notifyObservers(this);
  96608. }
  96609. catch (err) {
  96610. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  96611. }
  96612. }
  96613. if (this._webVRpresenting) {
  96614. this._scene.getEngine().disableVR();
  96615. }
  96616. if (this._scene.activeCamera) {
  96617. this._position = this._scene.activeCamera.position.clone();
  96618. }
  96619. if (this._deviceOrientationCamera) {
  96620. this._deviceOrientationCamera.position = this._position;
  96621. this._scene.activeCamera = this._deviceOrientationCamera;
  96622. if (this._canvas) {
  96623. this._scene.activeCamera.attachControl(this._canvas);
  96624. }
  96625. }
  96626. else if (this._existingCamera) {
  96627. this._existingCamera.position = this._position;
  96628. this._scene.activeCamera = this._existingCamera;
  96629. }
  96630. this.updateButtonVisibility();
  96631. if (this._interactionsEnabled) {
  96632. this._scene.unregisterBeforeRender(this.beforeRender);
  96633. this._cameraGazer._gazeTracker.isVisible = false;
  96634. if (this._leftController) {
  96635. this._leftController._gazeTracker.isVisible = false;
  96636. }
  96637. if (this._rightController) {
  96638. this._rightController._gazeTracker.isVisible = false;
  96639. }
  96640. }
  96641. // resize to update width and height when exiting vr exits fullscreen
  96642. this._scene.getEngine().resize();
  96643. this._hasEnteredVR = false;
  96644. }
  96645. };
  96646. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  96647. /**
  96648. * The position of the vr experience helper.
  96649. */
  96650. get: function () {
  96651. return this._position;
  96652. },
  96653. /**
  96654. * Sets the position of the vr experience helper.
  96655. */
  96656. set: function (value) {
  96657. this._position = value;
  96658. if (this._scene.activeCamera) {
  96659. this._scene.activeCamera.position = value;
  96660. }
  96661. },
  96662. enumerable: true,
  96663. configurable: true
  96664. });
  96665. /**
  96666. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  96667. */
  96668. VRExperienceHelper.prototype.enableInteractions = function () {
  96669. var _this = this;
  96670. if (!this._interactionsEnabled) {
  96671. this._interactionsRequested = true;
  96672. if (this._leftController) {
  96673. this._enableInteractionOnController(this._leftController);
  96674. }
  96675. if (this._rightController) {
  96676. this._enableInteractionOnController(this._rightController);
  96677. }
  96678. this.raySelectionPredicate = function (mesh) {
  96679. return mesh.isVisible && (mesh.isPickable || mesh.name === _this._floorMeshName);
  96680. };
  96681. this.meshSelectionPredicate = function (mesh) {
  96682. return true;
  96683. };
  96684. this._raySelectionPredicate = function (mesh) {
  96685. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  96686. && mesh.name.indexOf("teleportationTarget") === -1
  96687. && mesh.name.indexOf("torusTeleportation") === -1)) {
  96688. return _this.raySelectionPredicate(mesh);
  96689. }
  96690. return false;
  96691. };
  96692. this._interactionsEnabled = true;
  96693. }
  96694. };
  96695. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  96696. get: function () {
  96697. return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer);
  96698. },
  96699. enumerable: true,
  96700. configurable: true
  96701. });
  96702. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  96703. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  96704. if (this._floorMeshesCollection[i].id === mesh.id) {
  96705. return true;
  96706. }
  96707. }
  96708. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  96709. return true;
  96710. }
  96711. return false;
  96712. };
  96713. /**
  96714. * Adds a floor mesh to be used for teleportation.
  96715. * @param floorMesh the mesh to be used for teleportation.
  96716. */
  96717. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  96718. if (!this._floorMeshesCollection) {
  96719. return;
  96720. }
  96721. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  96722. return;
  96723. }
  96724. this._floorMeshesCollection.push(floorMesh);
  96725. };
  96726. /**
  96727. * Removes a floor mesh from being used for teleportation.
  96728. * @param floorMesh the mesh to be removed.
  96729. */
  96730. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  96731. if (!this._floorMeshesCollection) {
  96732. return;
  96733. }
  96734. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  96735. if (meshIndex !== -1) {
  96736. this._floorMeshesCollection.splice(meshIndex, 1);
  96737. }
  96738. };
  96739. /**
  96740. * Enables interactions and teleportation using the VR controllers and gaze.
  96741. * @param vrTeleportationOptions options to modify teleportation behavior.
  96742. */
  96743. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  96744. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  96745. if (!this._teleportationInitialized) {
  96746. this._teleportationRequested = true;
  96747. this.enableInteractions();
  96748. if (vrTeleportationOptions.floorMeshName) {
  96749. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  96750. }
  96751. if (vrTeleportationOptions.floorMeshes) {
  96752. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  96753. }
  96754. if (this._leftController != null) {
  96755. this._enableTeleportationOnController(this._leftController);
  96756. }
  96757. if (this._rightController != null) {
  96758. this._enableTeleportationOnController(this._rightController);
  96759. }
  96760. // Creates an image processing post process for the vignette not relying
  96761. // on the main scene configuration for image processing to reduce setup and spaces
  96762. // (gamma/linear) conflicts.
  96763. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  96764. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  96765. imageProcessingConfiguration.vignetteEnabled = true;
  96766. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  96767. this._webVRCamera.detachPostProcess(this._postProcessMove);
  96768. this._teleportationInitialized = true;
  96769. if (this._isDefaultTeleportationTarget) {
  96770. this._createTeleportationCircles();
  96771. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  96772. }
  96773. }
  96774. };
  96775. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  96776. var _this = this;
  96777. var controllerMesh = controller.webVRController.mesh;
  96778. if (controllerMesh) {
  96779. controller._interactionsEnabled = true;
  96780. controller._activatePointer();
  96781. if (this.webVROptions.laserToggle) {
  96782. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  96783. // Enabling / disabling laserPointer
  96784. if (_this._displayLaserPointer && stateObject.value === 1) {
  96785. if (controller._activePointer) {
  96786. controller._deactivatePointer();
  96787. }
  96788. else {
  96789. controller._activatePointer();
  96790. }
  96791. if (_this.displayGaze) {
  96792. controller._gazeTracker.isVisible = controller._activePointer;
  96793. }
  96794. }
  96795. });
  96796. }
  96797. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  96798. var gazer = controller;
  96799. if (_this._noControllerIsActive) {
  96800. gazer = _this._cameraGazer;
  96801. }
  96802. if (!gazer._pointerDownOnMeshAsked) {
  96803. if (stateObject.value > _this._padSensibilityUp) {
  96804. gazer._selectionPointerDown();
  96805. }
  96806. }
  96807. else if (stateObject.value < _this._padSensibilityDown) {
  96808. gazer._selectionPointerUp();
  96809. }
  96810. });
  96811. }
  96812. };
  96813. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  96814. // Dont teleport if another gaze already requested teleportation
  96815. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  96816. return;
  96817. }
  96818. if (!gazer._teleportationRequestInitiated) {
  96819. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  96820. gazer._activatePointer();
  96821. gazer._teleportationRequestInitiated = true;
  96822. }
  96823. }
  96824. else {
  96825. // Listening to the proper controller values changes to confirm teleportation
  96826. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  96827. if (this._teleportActive) {
  96828. this._teleportCamera(this._haloCenter);
  96829. }
  96830. gazer._teleportationRequestInitiated = false;
  96831. }
  96832. }
  96833. };
  96834. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  96835. // Only rotate when user is not currently selecting a teleportation location
  96836. if (gazer._teleportationRequestInitiated) {
  96837. return;
  96838. }
  96839. if (!gazer._rotationLeftAsked) {
  96840. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  96841. gazer._rotationLeftAsked = true;
  96842. if (this._rotationAllowed) {
  96843. this._rotateCamera(false);
  96844. }
  96845. }
  96846. }
  96847. else {
  96848. if (stateObject.x > -this._padSensibilityDown) {
  96849. gazer._rotationLeftAsked = false;
  96850. }
  96851. }
  96852. if (!gazer._rotationRightAsked) {
  96853. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  96854. gazer._rotationRightAsked = true;
  96855. if (this._rotationAllowed) {
  96856. this._rotateCamera(true);
  96857. }
  96858. }
  96859. }
  96860. else {
  96861. if (stateObject.x < this._padSensibilityDown) {
  96862. gazer._rotationRightAsked = false;
  96863. }
  96864. }
  96865. };
  96866. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  96867. // Only teleport backwards when user is not currently selecting a teleportation location
  96868. if (gazer._teleportationRequestInitiated) {
  96869. return;
  96870. }
  96871. // Teleport backwards
  96872. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  96873. if (!gazer._teleportationBackRequestInitiated) {
  96874. if (!this.currentVRCamera) {
  96875. return;
  96876. }
  96877. // Get rotation and position of the current camera
  96878. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  96879. var position = this.currentVRCamera.position;
  96880. // If the camera has device position, use that instead
  96881. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  96882. rotation = this.currentVRCamera.deviceRotationQuaternion;
  96883. position = this.currentVRCamera.devicePosition;
  96884. }
  96885. // Get matrix with only the y rotation of the device rotation
  96886. rotation.toEulerAnglesToRef(this._workingVector);
  96887. this._workingVector.z = 0;
  96888. this._workingVector.x = 0;
  96889. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  96890. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  96891. // Rotate backwards ray by device rotation to cast at the ground behind the user
  96892. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  96893. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  96894. var ray = new BABYLON.Ray(position, this._workingVector);
  96895. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  96896. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  96897. this._teleportCamera(hit.pickedPoint);
  96898. }
  96899. gazer._teleportationBackRequestInitiated = true;
  96900. }
  96901. }
  96902. else {
  96903. gazer._teleportationBackRequestInitiated = false;
  96904. }
  96905. };
  96906. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  96907. var _this = this;
  96908. var controllerMesh = controller.webVRController.mesh;
  96909. if (controllerMesh) {
  96910. if (!controller._interactionsEnabled) {
  96911. this._enableInteractionOnController(controller);
  96912. }
  96913. controller._interactionsEnabled = true;
  96914. controller._teleportationEnabled = true;
  96915. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  96916. controller._dpadPressed = false;
  96917. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  96918. controller._dpadPressed = stateObject.pressed;
  96919. if (!controller._dpadPressed) {
  96920. controller._rotationLeftAsked = false;
  96921. controller._rotationRightAsked = false;
  96922. controller._teleportationBackRequestInitiated = false;
  96923. }
  96924. });
  96925. }
  96926. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  96927. if (_this.teleportationEnabled) {
  96928. _this._checkTeleportBackwards(stateObject, controller);
  96929. _this._checkTeleportWithRay(stateObject, controller);
  96930. }
  96931. _this._checkRotate(stateObject, controller);
  96932. });
  96933. }
  96934. };
  96935. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  96936. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  96937. this._teleportationTarget.isPickable = false;
  96938. var length = 512;
  96939. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  96940. dynamicTexture.hasAlpha = true;
  96941. var context = dynamicTexture.getContext();
  96942. var centerX = length / 2;
  96943. var centerY = length / 2;
  96944. var radius = 200;
  96945. context.beginPath();
  96946. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  96947. context.fillStyle = this._teleportationFillColor;
  96948. context.fill();
  96949. context.lineWidth = 10;
  96950. context.strokeStyle = this._teleportationBorderColor;
  96951. context.stroke();
  96952. context.closePath();
  96953. dynamicTexture.update();
  96954. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  96955. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  96956. this._teleportationTarget.material = teleportationCircleMaterial;
  96957. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  96958. torus.isPickable = false;
  96959. torus.parent = this._teleportationTarget;
  96960. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  96961. var keys = [];
  96962. keys.push({
  96963. frame: 0,
  96964. value: 0
  96965. });
  96966. keys.push({
  96967. frame: 30,
  96968. value: 0.4
  96969. });
  96970. keys.push({
  96971. frame: 60,
  96972. value: 0
  96973. });
  96974. animationInnerCircle.setKeys(keys);
  96975. var easingFunction = new BABYLON.SineEase();
  96976. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  96977. animationInnerCircle.setEasingFunction(easingFunction);
  96978. torus.animations = [];
  96979. torus.animations.push(animationInnerCircle);
  96980. this._scene.beginAnimation(torus, 0, 60, true);
  96981. this._hideTeleportationTarget();
  96982. };
  96983. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  96984. this._teleportActive = true;
  96985. if (this._teleportationInitialized) {
  96986. this._teleportationTarget.isVisible = true;
  96987. if (this._isDefaultTeleportationTarget) {
  96988. this._teleportationTarget.getChildren()[0].isVisible = true;
  96989. }
  96990. }
  96991. };
  96992. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  96993. this._teleportActive = false;
  96994. if (this._teleportationInitialized) {
  96995. this._teleportationTarget.isVisible = false;
  96996. if (this._isDefaultTeleportationTarget) {
  96997. this._teleportationTarget.getChildren()[0].isVisible = false;
  96998. }
  96999. }
  97000. };
  97001. VRExperienceHelper.prototype._rotateCamera = function (right) {
  97002. var _this = this;
  97003. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  97004. return;
  97005. }
  97006. if (right) {
  97007. this._rotationAngle++;
  97008. }
  97009. else {
  97010. this._rotationAngle--;
  97011. }
  97012. this.currentVRCamera.animations = [];
  97013. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  97014. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  97015. var animationRotationKeys = [];
  97016. animationRotationKeys.push({
  97017. frame: 0,
  97018. value: this.currentVRCamera.rotationQuaternion
  97019. });
  97020. animationRotationKeys.push({
  97021. frame: 6,
  97022. value: target
  97023. });
  97024. animationRotation.setKeys(animationRotationKeys);
  97025. animationRotation.setEasingFunction(this._circleEase);
  97026. this.currentVRCamera.animations.push(animationRotation);
  97027. this._postProcessMove.animations = [];
  97028. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  97029. var vignetteWeightKeys = [];
  97030. vignetteWeightKeys.push({
  97031. frame: 0,
  97032. value: 0
  97033. });
  97034. vignetteWeightKeys.push({
  97035. frame: 3,
  97036. value: 4
  97037. });
  97038. vignetteWeightKeys.push({
  97039. frame: 6,
  97040. value: 0
  97041. });
  97042. animationPP.setKeys(vignetteWeightKeys);
  97043. animationPP.setEasingFunction(this._circleEase);
  97044. this._postProcessMove.animations.push(animationPP);
  97045. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  97046. var vignetteStretchKeys = [];
  97047. vignetteStretchKeys.push({
  97048. frame: 0,
  97049. value: 0
  97050. });
  97051. vignetteStretchKeys.push({
  97052. frame: 3,
  97053. value: 10
  97054. });
  97055. vignetteStretchKeys.push({
  97056. frame: 6,
  97057. value: 0
  97058. });
  97059. animationPP2.setKeys(vignetteStretchKeys);
  97060. animationPP2.setEasingFunction(this._circleEase);
  97061. this._postProcessMove.animations.push(animationPP2);
  97062. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  97063. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  97064. this._postProcessMove.samples = 4;
  97065. this._webVRCamera.attachPostProcess(this._postProcessMove);
  97066. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  97067. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  97068. });
  97069. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  97070. };
  97071. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  97072. if (hit.pickedPoint) {
  97073. if (gazer._teleportationRequestInitiated) {
  97074. this._displayTeleportationTarget();
  97075. this._haloCenter.copyFrom(hit.pickedPoint);
  97076. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  97077. }
  97078. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  97079. if (pickNormal) {
  97080. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  97081. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  97082. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  97083. }
  97084. this._teleportationTarget.position.y += 0.1;
  97085. }
  97086. };
  97087. VRExperienceHelper.prototype._teleportCamera = function (location) {
  97088. var _this = this;
  97089. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  97090. return;
  97091. }
  97092. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  97093. // offset of the headset from the anchor.
  97094. if (this.webVRCamera.leftCamera) {
  97095. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  97096. this._workingVector.subtractInPlace(this.webVRCamera.position);
  97097. location.subtractToRef(this._workingVector, this._workingVector);
  97098. }
  97099. else {
  97100. this._workingVector.copyFrom(location);
  97101. }
  97102. // Add height to account for user's height offset
  97103. if (this.isInVRMode) {
  97104. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  97105. }
  97106. else {
  97107. this._workingVector.y += this._defaultHeight;
  97108. }
  97109. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  97110. // Create animation from the camera's position to the new location
  97111. this.currentVRCamera.animations = [];
  97112. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  97113. var animationCameraTeleportationKeys = [{
  97114. frame: 0,
  97115. value: this.currentVRCamera.position
  97116. },
  97117. {
  97118. frame: 11,
  97119. value: this._workingVector
  97120. }
  97121. ];
  97122. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  97123. animationCameraTeleportation.setEasingFunction(this._circleEase);
  97124. this.currentVRCamera.animations.push(animationCameraTeleportation);
  97125. this._postProcessMove.animations = [];
  97126. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  97127. var vignetteWeightKeys = [];
  97128. vignetteWeightKeys.push({
  97129. frame: 0,
  97130. value: 0
  97131. });
  97132. vignetteWeightKeys.push({
  97133. frame: 5,
  97134. value: 8
  97135. });
  97136. vignetteWeightKeys.push({
  97137. frame: 11,
  97138. value: 0
  97139. });
  97140. animationPP.setKeys(vignetteWeightKeys);
  97141. this._postProcessMove.animations.push(animationPP);
  97142. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  97143. var vignetteStretchKeys = [];
  97144. vignetteStretchKeys.push({
  97145. frame: 0,
  97146. value: 0
  97147. });
  97148. vignetteStretchKeys.push({
  97149. frame: 5,
  97150. value: 10
  97151. });
  97152. vignetteStretchKeys.push({
  97153. frame: 11,
  97154. value: 0
  97155. });
  97156. animationPP2.setKeys(vignetteStretchKeys);
  97157. this._postProcessMove.animations.push(animationPP2);
  97158. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  97159. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  97160. this._webVRCamera.attachPostProcess(this._postProcessMove);
  97161. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  97162. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  97163. });
  97164. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  97165. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  97166. });
  97167. this._hideTeleportationTarget();
  97168. };
  97169. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  97170. if (normal) {
  97171. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  97172. if (angle < Math.PI / 2) {
  97173. normal.scaleInPlace(-1);
  97174. }
  97175. }
  97176. return normal;
  97177. };
  97178. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  97179. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  97180. return;
  97181. }
  97182. var ray = gazer._getForwardRay(this._rayLength);
  97183. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  97184. if (hit) {
  97185. // Populate the contrllers mesh that can be used for drag/drop
  97186. if (gazer._laserPointer) {
  97187. hit.originMesh = gazer._laserPointer.parent;
  97188. }
  97189. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  97190. }
  97191. gazer._currentHit = hit;
  97192. // Moving the gazeTracker on the mesh face targetted
  97193. if (hit && hit.pickedPoint) {
  97194. if (this._displayGaze) {
  97195. var multiplier = 1;
  97196. gazer._gazeTracker.isVisible = true;
  97197. if (gazer._isActionableMesh) {
  97198. multiplier = 3;
  97199. }
  97200. if (this.updateGazeTrackerScale) {
  97201. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  97202. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  97203. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  97204. }
  97205. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  97206. // To avoid z-fighting
  97207. var deltaFighting = 0.002;
  97208. if (pickNormal) {
  97209. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  97210. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  97211. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  97212. }
  97213. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  97214. if (gazer._gazeTracker.position.x < 0) {
  97215. gazer._gazeTracker.position.x += deltaFighting;
  97216. }
  97217. else {
  97218. gazer._gazeTracker.position.x -= deltaFighting;
  97219. }
  97220. if (gazer._gazeTracker.position.y < 0) {
  97221. gazer._gazeTracker.position.y += deltaFighting;
  97222. }
  97223. else {
  97224. gazer._gazeTracker.position.y -= deltaFighting;
  97225. }
  97226. if (gazer._gazeTracker.position.z < 0) {
  97227. gazer._gazeTracker.position.z += deltaFighting;
  97228. }
  97229. else {
  97230. gazer._gazeTracker.position.z -= deltaFighting;
  97231. }
  97232. }
  97233. // Changing the size of the laser pointer based on the distance from the targetted point
  97234. gazer._updatePointerDistance(hit.distance);
  97235. }
  97236. else {
  97237. gazer._updatePointerDistance();
  97238. gazer._gazeTracker.isVisible = false;
  97239. }
  97240. if (hit && hit.pickedMesh) {
  97241. // The object selected is the floor, we're in a teleportation scenario
  97242. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  97243. // Moving the teleportation area to this targetted point
  97244. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  97245. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  97246. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  97247. }
  97248. gazer._currentMeshSelected = null;
  97249. if (gazer._teleportationRequestInitiated) {
  97250. this._moveTeleportationSelectorTo(hit, gazer, ray);
  97251. }
  97252. return;
  97253. }
  97254. // If not, we're in a selection scenario
  97255. //this._teleportationAllowed = false;
  97256. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  97257. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  97258. this.onNewMeshPicked.notifyObservers(hit);
  97259. gazer._currentMeshSelected = hit.pickedMesh;
  97260. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  97261. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  97262. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  97263. gazer._isActionableMesh = true;
  97264. }
  97265. else {
  97266. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  97267. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  97268. gazer._isActionableMesh = false;
  97269. }
  97270. try {
  97271. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  97272. }
  97273. catch (err) {
  97274. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  97275. }
  97276. }
  97277. else {
  97278. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  97279. gazer._currentMeshSelected = null;
  97280. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  97281. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  97282. }
  97283. }
  97284. }
  97285. else {
  97286. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  97287. gazer._currentMeshSelected = null;
  97288. //this._teleportationAllowed = false;
  97289. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  97290. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  97291. }
  97292. };
  97293. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  97294. if (mesh) {
  97295. this.onSelectedMeshUnselected.notifyObservers(mesh);
  97296. }
  97297. };
  97298. /**
  97299. * Sets the color of the laser ray from the vr controllers.
  97300. * @param color new color for the ray.
  97301. */
  97302. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  97303. if (this._leftController) {
  97304. this._leftController._setLaserPointerColor(color);
  97305. }
  97306. if (this._rightController) {
  97307. this._rightController._setLaserPointerColor(color);
  97308. }
  97309. };
  97310. /**
  97311. * Sets the color of the ray from the vr headsets gaze.
  97312. * @param color new color for the ray.
  97313. */
  97314. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  97315. if (!this._cameraGazer._gazeTracker.material) {
  97316. return;
  97317. }
  97318. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  97319. if (this._leftController) {
  97320. this._leftController._gazeTracker.material.emissiveColor = color;
  97321. }
  97322. if (this._rightController) {
  97323. this._rightController._gazeTracker.material.emissiveColor = color;
  97324. }
  97325. };
  97326. /**
  97327. * Exits VR and disposes of the vr experience helper
  97328. */
  97329. VRExperienceHelper.prototype.dispose = function () {
  97330. if (this.isInVRMode) {
  97331. this.exitVR();
  97332. }
  97333. if (this._postProcessMove) {
  97334. this._postProcessMove.dispose();
  97335. }
  97336. if (this._webVRCamera) {
  97337. this._webVRCamera.dispose();
  97338. }
  97339. if (this._vrDeviceOrientationCamera) {
  97340. this._vrDeviceOrientationCamera.dispose();
  97341. }
  97342. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  97343. document.body.removeChild(this._btnVR);
  97344. }
  97345. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  97346. this._deviceOrientationCamera.dispose();
  97347. }
  97348. if (this._cameraGazer) {
  97349. this._cameraGazer.dispose();
  97350. }
  97351. if (this._leftController) {
  97352. this._leftController.dispose();
  97353. }
  97354. if (this._rightController) {
  97355. this._rightController.dispose();
  97356. }
  97357. if (this._teleportationTarget) {
  97358. this._teleportationTarget.dispose();
  97359. }
  97360. this._floorMeshesCollection = [];
  97361. document.removeEventListener("keydown", this._onKeyDown);
  97362. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  97363. window.removeEventListener("resize", this._onResize);
  97364. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  97365. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  97366. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  97367. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  97368. document.onmsfullscreenchange = null;
  97369. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  97370. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  97371. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  97372. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  97373. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  97374. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  97375. this._scene.unregisterBeforeRender(this.beforeRender);
  97376. };
  97377. /**
  97378. * Gets the name of the VRExperienceHelper class
  97379. * @returns "VRExperienceHelper"
  97380. */
  97381. VRExperienceHelper.prototype.getClassName = function () {
  97382. return "VRExperienceHelper";
  97383. };
  97384. return VRExperienceHelper;
  97385. }());
  97386. BABYLON.VRExperienceHelper = VRExperienceHelper;
  97387. })(BABYLON || (BABYLON = {}));
  97388. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  97389. // Mainly based on these 2 articles :
  97390. // 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
  97391. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  97392. var BABYLON;
  97393. (function (BABYLON) {
  97394. /**
  97395. * Defines the potential axis of a Joystick
  97396. */
  97397. var JoystickAxis;
  97398. (function (JoystickAxis) {
  97399. /** X axis */
  97400. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  97401. /** Y axis */
  97402. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  97403. /** Z axis */
  97404. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  97405. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  97406. /**
  97407. * Class used to define virtual joystick (used in touch mode)
  97408. */
  97409. var VirtualJoystick = /** @class */ (function () {
  97410. /**
  97411. * Creates a new virtual joystick
  97412. * @param leftJoystick defines that the joystick is for left hand (false by default)
  97413. */
  97414. function VirtualJoystick(leftJoystick) {
  97415. var _this = this;
  97416. if (leftJoystick) {
  97417. this._leftJoystick = true;
  97418. }
  97419. else {
  97420. this._leftJoystick = false;
  97421. }
  97422. VirtualJoystick._globalJoystickIndex++;
  97423. // By default left & right arrow keys are moving the X
  97424. // and up & down keys are moving the Y
  97425. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  97426. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  97427. this.reverseLeftRight = false;
  97428. this.reverseUpDown = false;
  97429. // collections of pointers
  97430. this._touches = new BABYLON.StringDictionary();
  97431. this.deltaPosition = BABYLON.Vector3.Zero();
  97432. this._joystickSensibility = 25;
  97433. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  97434. this._onResize = function (evt) {
  97435. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  97436. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  97437. if (VirtualJoystick.vjCanvas) {
  97438. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  97439. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  97440. }
  97441. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  97442. };
  97443. // injecting a canvas element on top of the canvas 3D game
  97444. if (!VirtualJoystick.vjCanvas) {
  97445. window.addEventListener("resize", this._onResize, false);
  97446. VirtualJoystick.vjCanvas = document.createElement("canvas");
  97447. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  97448. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  97449. VirtualJoystick.vjCanvas.width = window.innerWidth;
  97450. VirtualJoystick.vjCanvas.height = window.innerHeight;
  97451. VirtualJoystick.vjCanvas.style.width = "100%";
  97452. VirtualJoystick.vjCanvas.style.height = "100%";
  97453. VirtualJoystick.vjCanvas.style.position = "absolute";
  97454. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  97455. VirtualJoystick.vjCanvas.style.top = "0px";
  97456. VirtualJoystick.vjCanvas.style.left = "0px";
  97457. VirtualJoystick.vjCanvas.style.zIndex = "5";
  97458. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  97459. // Support for jQuery PEP polyfill
  97460. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  97461. var context = VirtualJoystick.vjCanvas.getContext('2d');
  97462. if (!context) {
  97463. throw new Error("Unable to create canvas for virtual joystick");
  97464. }
  97465. VirtualJoystick.vjCanvasContext = context;
  97466. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  97467. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  97468. document.body.appendChild(VirtualJoystick.vjCanvas);
  97469. }
  97470. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  97471. this.pressed = false;
  97472. // default joystick color
  97473. this._joystickColor = "cyan";
  97474. this._joystickPointerID = -1;
  97475. // current joystick position
  97476. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  97477. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  97478. // origin joystick position
  97479. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  97480. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  97481. this._onPointerDownHandlerRef = function (evt) {
  97482. _this._onPointerDown(evt);
  97483. };
  97484. this._onPointerMoveHandlerRef = function (evt) {
  97485. _this._onPointerMove(evt);
  97486. };
  97487. this._onPointerUpHandlerRef = function (evt) {
  97488. _this._onPointerUp(evt);
  97489. };
  97490. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  97491. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  97492. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  97493. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  97494. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  97495. evt.preventDefault(); // Disables system menu
  97496. }, false);
  97497. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  97498. }
  97499. /**
  97500. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  97501. * @param newJoystickSensibility defines the new sensibility
  97502. */
  97503. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  97504. this._joystickSensibility = newJoystickSensibility;
  97505. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  97506. };
  97507. VirtualJoystick.prototype._onPointerDown = function (e) {
  97508. var positionOnScreenCondition;
  97509. e.preventDefault();
  97510. if (this._leftJoystick === true) {
  97511. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  97512. }
  97513. else {
  97514. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  97515. }
  97516. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  97517. // First contact will be dedicated to the virtual joystick
  97518. this._joystickPointerID = e.pointerId;
  97519. this._joystickPointerStartPos.x = e.clientX;
  97520. this._joystickPointerStartPos.y = e.clientY;
  97521. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  97522. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  97523. this._deltaJoystickVector.x = 0;
  97524. this._deltaJoystickVector.y = 0;
  97525. this.pressed = true;
  97526. this._touches.add(e.pointerId.toString(), e);
  97527. }
  97528. else {
  97529. // You can only trigger the action buttons with a joystick declared
  97530. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  97531. this._action();
  97532. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  97533. }
  97534. }
  97535. };
  97536. VirtualJoystick.prototype._onPointerMove = function (e) {
  97537. // If the current pointer is the one associated to the joystick (first touch contact)
  97538. if (this._joystickPointerID == e.pointerId) {
  97539. this._joystickPointerPos.x = e.clientX;
  97540. this._joystickPointerPos.y = e.clientY;
  97541. this._deltaJoystickVector = this._joystickPointerPos.clone();
  97542. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  97543. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  97544. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  97545. switch (this._axisTargetedByLeftAndRight) {
  97546. case JoystickAxis.X:
  97547. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  97548. break;
  97549. case JoystickAxis.Y:
  97550. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  97551. break;
  97552. case JoystickAxis.Z:
  97553. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  97554. break;
  97555. }
  97556. var directionUpDown = this.reverseUpDown ? 1 : -1;
  97557. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  97558. switch (this._axisTargetedByUpAndDown) {
  97559. case JoystickAxis.X:
  97560. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  97561. break;
  97562. case JoystickAxis.Y:
  97563. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  97564. break;
  97565. case JoystickAxis.Z:
  97566. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  97567. break;
  97568. }
  97569. }
  97570. else {
  97571. var data = this._touches.get(e.pointerId.toString());
  97572. if (data) {
  97573. data.x = e.clientX;
  97574. data.y = e.clientY;
  97575. }
  97576. }
  97577. };
  97578. VirtualJoystick.prototype._onPointerUp = function (e) {
  97579. if (this._joystickPointerID == e.pointerId) {
  97580. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  97581. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  97582. this._joystickPointerID = -1;
  97583. this.pressed = false;
  97584. }
  97585. else {
  97586. var touch = this._touches.get(e.pointerId.toString());
  97587. if (touch) {
  97588. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  97589. }
  97590. }
  97591. this._deltaJoystickVector.x = 0;
  97592. this._deltaJoystickVector.y = 0;
  97593. this._touches.remove(e.pointerId.toString());
  97594. };
  97595. /**
  97596. * Change the color of the virtual joystick
  97597. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  97598. */
  97599. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  97600. this._joystickColor = newColor;
  97601. };
  97602. /**
  97603. * Defines a callback to call when the joystick is touched
  97604. * @param action defines the callback
  97605. */
  97606. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  97607. this._action = action;
  97608. };
  97609. /**
  97610. * Defines which axis you'd like to control for left & right
  97611. * @param axis defines the axis to use
  97612. */
  97613. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  97614. switch (axis) {
  97615. case JoystickAxis.X:
  97616. case JoystickAxis.Y:
  97617. case JoystickAxis.Z:
  97618. this._axisTargetedByLeftAndRight = axis;
  97619. break;
  97620. default:
  97621. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  97622. break;
  97623. }
  97624. };
  97625. /**
  97626. * Defines which axis you'd like to control for up & down
  97627. * @param axis defines the axis to use
  97628. */
  97629. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  97630. switch (axis) {
  97631. case JoystickAxis.X:
  97632. case JoystickAxis.Y:
  97633. case JoystickAxis.Z:
  97634. this._axisTargetedByUpAndDown = axis;
  97635. break;
  97636. default:
  97637. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  97638. break;
  97639. }
  97640. };
  97641. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  97642. var _this = this;
  97643. if (this.pressed) {
  97644. this._touches.forEach(function (key, touch) {
  97645. if (touch.pointerId === _this._joystickPointerID) {
  97646. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  97647. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  97648. VirtualJoystick.vjCanvasContext.beginPath();
  97649. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  97650. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  97651. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  97652. VirtualJoystick.vjCanvasContext.stroke();
  97653. VirtualJoystick.vjCanvasContext.closePath();
  97654. VirtualJoystick.vjCanvasContext.beginPath();
  97655. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  97656. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  97657. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  97658. VirtualJoystick.vjCanvasContext.stroke();
  97659. VirtualJoystick.vjCanvasContext.closePath();
  97660. VirtualJoystick.vjCanvasContext.beginPath();
  97661. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  97662. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  97663. VirtualJoystick.vjCanvasContext.stroke();
  97664. VirtualJoystick.vjCanvasContext.closePath();
  97665. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  97666. }
  97667. else {
  97668. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  97669. VirtualJoystick.vjCanvasContext.beginPath();
  97670. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  97671. VirtualJoystick.vjCanvasContext.beginPath();
  97672. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  97673. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  97674. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  97675. VirtualJoystick.vjCanvasContext.stroke();
  97676. VirtualJoystick.vjCanvasContext.closePath();
  97677. touch.prevX = touch.x;
  97678. touch.prevY = touch.y;
  97679. }
  97680. ;
  97681. });
  97682. }
  97683. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  97684. };
  97685. /**
  97686. * Release internal HTML canvas
  97687. */
  97688. VirtualJoystick.prototype.releaseCanvas = function () {
  97689. if (VirtualJoystick.vjCanvas) {
  97690. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  97691. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  97692. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  97693. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  97694. window.removeEventListener("resize", this._onResize);
  97695. document.body.removeChild(VirtualJoystick.vjCanvas);
  97696. VirtualJoystick.vjCanvas = null;
  97697. }
  97698. };
  97699. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  97700. VirtualJoystick._globalJoystickIndex = 0;
  97701. return VirtualJoystick;
  97702. }());
  97703. BABYLON.VirtualJoystick = VirtualJoystick;
  97704. })(BABYLON || (BABYLON = {}));
  97705. //# sourceMappingURL=babylon.virtualJoystick.js.map
  97706. var BABYLON;
  97707. (function (BABYLON) {
  97708. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  97709. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  97710. });
  97711. // We're mainly based on the logic defined into the FreeCamera code
  97712. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  97713. __extends(VirtualJoysticksCamera, _super);
  97714. function VirtualJoysticksCamera(name, position, scene) {
  97715. var _this = _super.call(this, name, position, scene) || this;
  97716. _this.inputs.addVirtualJoystick();
  97717. return _this;
  97718. }
  97719. VirtualJoysticksCamera.prototype.getClassName = function () {
  97720. return "VirtualJoysticksCamera";
  97721. };
  97722. return VirtualJoysticksCamera;
  97723. }(BABYLON.FreeCamera));
  97724. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  97725. })(BABYLON || (BABYLON = {}));
  97726. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  97727. var BABYLON;
  97728. (function (BABYLON) {
  97729. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  97730. function FreeCameraVirtualJoystickInput() {
  97731. }
  97732. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  97733. return this._leftjoystick;
  97734. };
  97735. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  97736. return this._rightjoystick;
  97737. };
  97738. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  97739. if (this._leftjoystick) {
  97740. var camera = this.camera;
  97741. var speed = camera._computeLocalCameraSpeed() * 50;
  97742. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  97743. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  97744. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  97745. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  97746. if (!this._leftjoystick.pressed) {
  97747. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  97748. }
  97749. if (!this._rightjoystick.pressed) {
  97750. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  97751. }
  97752. }
  97753. };
  97754. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  97755. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  97756. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  97757. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  97758. this._leftjoystick.setJoystickSensibility(0.15);
  97759. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  97760. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  97761. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  97762. this._rightjoystick.reverseUpDown = true;
  97763. this._rightjoystick.setJoystickSensibility(0.05);
  97764. this._rightjoystick.setJoystickColor("yellow");
  97765. };
  97766. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  97767. this._leftjoystick.releaseCanvas();
  97768. this._rightjoystick.releaseCanvas();
  97769. };
  97770. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  97771. return "FreeCameraVirtualJoystickInput";
  97772. };
  97773. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  97774. return "virtualJoystick";
  97775. };
  97776. return FreeCameraVirtualJoystickInput;
  97777. }());
  97778. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  97779. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  97780. })(BABYLON || (BABYLON = {}));
  97781. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  97782. var BABYLON;
  97783. (function (BABYLON) {
  97784. var SimplificationSettings = /** @class */ (function () {
  97785. function SimplificationSettings(quality, distance, optimizeMesh) {
  97786. this.quality = quality;
  97787. this.distance = distance;
  97788. this.optimizeMesh = optimizeMesh;
  97789. }
  97790. return SimplificationSettings;
  97791. }());
  97792. BABYLON.SimplificationSettings = SimplificationSettings;
  97793. var SimplificationQueue = /** @class */ (function () {
  97794. function SimplificationQueue() {
  97795. this.running = false;
  97796. this._simplificationArray = [];
  97797. }
  97798. SimplificationQueue.prototype.addTask = function (task) {
  97799. this._simplificationArray.push(task);
  97800. };
  97801. SimplificationQueue.prototype.executeNext = function () {
  97802. var task = this._simplificationArray.pop();
  97803. if (task) {
  97804. this.running = true;
  97805. this.runSimplification(task);
  97806. }
  97807. else {
  97808. this.running = false;
  97809. }
  97810. };
  97811. SimplificationQueue.prototype.runSimplification = function (task) {
  97812. var _this = this;
  97813. if (task.parallelProcessing) {
  97814. //parallel simplifier
  97815. task.settings.forEach(function (setting) {
  97816. var simplifier = _this.getSimplifier(task);
  97817. simplifier.simplify(setting, function (newMesh) {
  97818. task.mesh.addLODLevel(setting.distance, newMesh);
  97819. newMesh.isVisible = true;
  97820. //check if it is the last
  97821. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  97822. //all done, run the success callback.
  97823. task.successCallback();
  97824. }
  97825. _this.executeNext();
  97826. });
  97827. });
  97828. }
  97829. else {
  97830. //single simplifier.
  97831. var simplifier = this.getSimplifier(task);
  97832. var runDecimation = function (setting, callback) {
  97833. simplifier.simplify(setting, function (newMesh) {
  97834. task.mesh.addLODLevel(setting.distance, newMesh);
  97835. newMesh.isVisible = true;
  97836. //run the next quality level
  97837. callback();
  97838. });
  97839. };
  97840. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  97841. runDecimation(task.settings[loop.index], function () {
  97842. loop.executeNext();
  97843. });
  97844. }, function () {
  97845. //execution ended, run the success callback.
  97846. if (task.successCallback) {
  97847. task.successCallback();
  97848. }
  97849. _this.executeNext();
  97850. });
  97851. }
  97852. };
  97853. SimplificationQueue.prototype.getSimplifier = function (task) {
  97854. switch (task.simplificationType) {
  97855. case SimplificationType.QUADRATIC:
  97856. default:
  97857. return new QuadraticErrorSimplification(task.mesh);
  97858. }
  97859. };
  97860. return SimplificationQueue;
  97861. }());
  97862. BABYLON.SimplificationQueue = SimplificationQueue;
  97863. /**
  97864. * The implemented types of simplification
  97865. * At the moment only Quadratic Error Decimation is implemented
  97866. */
  97867. var SimplificationType;
  97868. (function (SimplificationType) {
  97869. /** Quadratic error decimation */
  97870. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  97871. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  97872. var DecimationTriangle = /** @class */ (function () {
  97873. function DecimationTriangle(vertices) {
  97874. this.vertices = vertices;
  97875. this.error = new Array(4);
  97876. this.deleted = false;
  97877. this.isDirty = false;
  97878. this.deletePending = false;
  97879. this.borderFactor = 0;
  97880. }
  97881. return DecimationTriangle;
  97882. }());
  97883. BABYLON.DecimationTriangle = DecimationTriangle;
  97884. var DecimationVertex = /** @class */ (function () {
  97885. function DecimationVertex(position, id) {
  97886. this.position = position;
  97887. this.id = id;
  97888. this.isBorder = true;
  97889. this.q = new QuadraticMatrix();
  97890. this.triangleCount = 0;
  97891. this.triangleStart = 0;
  97892. this.originalOffsets = [];
  97893. }
  97894. DecimationVertex.prototype.updatePosition = function (newPosition) {
  97895. this.position.copyFrom(newPosition);
  97896. };
  97897. return DecimationVertex;
  97898. }());
  97899. BABYLON.DecimationVertex = DecimationVertex;
  97900. var QuadraticMatrix = /** @class */ (function () {
  97901. function QuadraticMatrix(data) {
  97902. this.data = new Array(10);
  97903. for (var i = 0; i < 10; ++i) {
  97904. if (data && data[i]) {
  97905. this.data[i] = data[i];
  97906. }
  97907. else {
  97908. this.data[i] = 0;
  97909. }
  97910. }
  97911. }
  97912. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  97913. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  97914. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  97915. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  97916. return det;
  97917. };
  97918. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  97919. for (var i = 0; i < 10; ++i) {
  97920. this.data[i] += matrix.data[i];
  97921. }
  97922. };
  97923. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  97924. for (var i = 0; i < 10; ++i) {
  97925. this.data[i] += data[i];
  97926. }
  97927. };
  97928. QuadraticMatrix.prototype.add = function (matrix) {
  97929. var m = new QuadraticMatrix();
  97930. for (var i = 0; i < 10; ++i) {
  97931. m.data[i] = this.data[i] + matrix.data[i];
  97932. }
  97933. return m;
  97934. };
  97935. QuadraticMatrix.FromData = function (a, b, c, d) {
  97936. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  97937. };
  97938. //returning an array to avoid garbage collection
  97939. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  97940. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  97941. };
  97942. return QuadraticMatrix;
  97943. }());
  97944. BABYLON.QuadraticMatrix = QuadraticMatrix;
  97945. var Reference = /** @class */ (function () {
  97946. function Reference(vertexId, triangleId) {
  97947. this.vertexId = vertexId;
  97948. this.triangleId = triangleId;
  97949. }
  97950. return Reference;
  97951. }());
  97952. BABYLON.Reference = Reference;
  97953. /**
  97954. * An implementation of the Quadratic Error simplification algorithm.
  97955. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  97956. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  97957. * @author RaananW
  97958. */
  97959. var QuadraticErrorSimplification = /** @class */ (function () {
  97960. function QuadraticErrorSimplification(_mesh) {
  97961. this._mesh = _mesh;
  97962. this.syncIterations = 5000;
  97963. this.aggressiveness = 7;
  97964. this.decimationIterations = 100;
  97965. this.boundingBoxEpsilon = BABYLON.Epsilon;
  97966. }
  97967. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  97968. var _this = this;
  97969. this.initDecimatedMesh();
  97970. //iterating through the submeshes array, one after the other.
  97971. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  97972. _this.initWithMesh(loop.index, function () {
  97973. _this.runDecimation(settings, loop.index, function () {
  97974. loop.executeNext();
  97975. });
  97976. }, settings.optimizeMesh);
  97977. }, function () {
  97978. setTimeout(function () {
  97979. successCallback(_this._reconstructedMesh);
  97980. }, 0);
  97981. });
  97982. };
  97983. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  97984. var _this = this;
  97985. var targetCount = ~~(this.triangles.length * settings.quality);
  97986. var deletedTriangles = 0;
  97987. var triangleCount = this.triangles.length;
  97988. var iterationFunction = function (iteration, callback) {
  97989. setTimeout(function () {
  97990. if (iteration % 5 === 0) {
  97991. _this.updateMesh(iteration === 0);
  97992. }
  97993. for (var i = 0; i < _this.triangles.length; ++i) {
  97994. _this.triangles[i].isDirty = false;
  97995. }
  97996. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  97997. var trianglesIterator = function (i) {
  97998. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  97999. var t = _this.triangles[tIdx];
  98000. if (!t)
  98001. return;
  98002. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  98003. return;
  98004. }
  98005. for (var j = 0; j < 3; ++j) {
  98006. if (t.error[j] < threshold) {
  98007. var deleted0 = [];
  98008. var deleted1 = [];
  98009. var v0 = t.vertices[j];
  98010. var v1 = t.vertices[(j + 1) % 3];
  98011. if (v0.isBorder || v1.isBorder)
  98012. continue;
  98013. var p = BABYLON.Vector3.Zero();
  98014. var n = BABYLON.Vector3.Zero();
  98015. var uv = BABYLON.Vector2.Zero();
  98016. var color = new BABYLON.Color4(0, 0, 0, 1);
  98017. _this.calculateError(v0, v1, p, n, uv, color);
  98018. var delTr = new Array();
  98019. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  98020. continue;
  98021. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  98022. continue;
  98023. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  98024. continue;
  98025. var uniqueArray = new Array();
  98026. delTr.forEach(function (deletedT) {
  98027. if (uniqueArray.indexOf(deletedT) === -1) {
  98028. deletedT.deletePending = true;
  98029. uniqueArray.push(deletedT);
  98030. }
  98031. });
  98032. if (uniqueArray.length % 2 !== 0) {
  98033. continue;
  98034. }
  98035. v0.q = v1.q.add(v0.q);
  98036. v0.updatePosition(p);
  98037. var tStart = _this.references.length;
  98038. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  98039. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  98040. var tCount = _this.references.length - tStart;
  98041. if (tCount <= v0.triangleCount) {
  98042. if (tCount) {
  98043. for (var c = 0; c < tCount; c++) {
  98044. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  98045. }
  98046. }
  98047. }
  98048. else {
  98049. v0.triangleStart = tStart;
  98050. }
  98051. v0.triangleCount = tCount;
  98052. break;
  98053. }
  98054. }
  98055. };
  98056. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  98057. }, 0);
  98058. };
  98059. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  98060. if (triangleCount - deletedTriangles <= targetCount)
  98061. loop.breakLoop();
  98062. else {
  98063. iterationFunction(loop.index, function () {
  98064. loop.executeNext();
  98065. });
  98066. }
  98067. }, function () {
  98068. setTimeout(function () {
  98069. //reconstruct this part of the mesh
  98070. _this.reconstructMesh(submeshIndex);
  98071. successCallback();
  98072. }, 0);
  98073. });
  98074. };
  98075. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  98076. var _this = this;
  98077. this.vertices = [];
  98078. this.triangles = [];
  98079. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  98080. var indices = this._mesh.getIndices();
  98081. var submesh = this._mesh.subMeshes[submeshIndex];
  98082. var findInVertices = function (positionToSearch) {
  98083. if (optimizeMesh) {
  98084. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  98085. if (_this.vertices[ii].position.equals(positionToSearch)) {
  98086. return _this.vertices[ii];
  98087. }
  98088. }
  98089. }
  98090. return null;
  98091. };
  98092. var vertexReferences = [];
  98093. var vertexInit = function (i) {
  98094. if (!positionData) {
  98095. return;
  98096. }
  98097. var offset = i + submesh.verticesStart;
  98098. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  98099. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  98100. vertex.originalOffsets.push(offset);
  98101. if (vertex.id === _this.vertices.length) {
  98102. _this.vertices.push(vertex);
  98103. }
  98104. vertexReferences.push(vertex.id);
  98105. };
  98106. //var totalVertices = mesh.getTotalVertices();
  98107. var totalVertices = submesh.verticesCount;
  98108. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  98109. var indicesInit = function (i) {
  98110. if (!indices) {
  98111. return;
  98112. }
  98113. var offset = (submesh.indexStart / 3) + i;
  98114. var pos = (offset * 3);
  98115. var i0 = indices[pos + 0];
  98116. var i1 = indices[pos + 1];
  98117. var i2 = indices[pos + 2];
  98118. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  98119. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  98120. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  98121. var triangle = new DecimationTriangle([v0, v1, v2]);
  98122. triangle.originalOffset = pos;
  98123. _this.triangles.push(triangle);
  98124. };
  98125. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  98126. _this.init(callback);
  98127. });
  98128. });
  98129. };
  98130. QuadraticErrorSimplification.prototype.init = function (callback) {
  98131. var _this = this;
  98132. var triangleInit1 = function (i) {
  98133. var t = _this.triangles[i];
  98134. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  98135. for (var j = 0; j < 3; j++) {
  98136. 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))));
  98137. }
  98138. };
  98139. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  98140. var triangleInit2 = function (i) {
  98141. var t = _this.triangles[i];
  98142. for (var j = 0; j < 3; ++j) {
  98143. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  98144. }
  98145. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  98146. };
  98147. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  98148. callback();
  98149. });
  98150. });
  98151. };
  98152. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  98153. var newTriangles = [];
  98154. var i;
  98155. for (i = 0; i < this.vertices.length; ++i) {
  98156. this.vertices[i].triangleCount = 0;
  98157. }
  98158. var t;
  98159. var j;
  98160. for (i = 0; i < this.triangles.length; ++i) {
  98161. if (!this.triangles[i].deleted) {
  98162. t = this.triangles[i];
  98163. for (j = 0; j < 3; ++j) {
  98164. t.vertices[j].triangleCount = 1;
  98165. }
  98166. newTriangles.push(t);
  98167. }
  98168. }
  98169. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  98170. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  98171. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  98172. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  98173. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  98174. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  98175. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  98176. var vertexCount = 0;
  98177. for (i = 0; i < this.vertices.length; ++i) {
  98178. var vertex = this.vertices[i];
  98179. vertex.id = vertexCount;
  98180. if (vertex.triangleCount) {
  98181. vertex.originalOffsets.forEach(function (originalOffset) {
  98182. if (!normalData) {
  98183. return;
  98184. }
  98185. newPositionData.push(vertex.position.x);
  98186. newPositionData.push(vertex.position.y);
  98187. newPositionData.push(vertex.position.z);
  98188. newNormalData.push(normalData[originalOffset * 3]);
  98189. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  98190. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  98191. if (uvs && uvs.length) {
  98192. newUVsData.push(uvs[(originalOffset * 2)]);
  98193. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  98194. }
  98195. else if (colorsData && colorsData.length) {
  98196. newColorsData.push(colorsData[(originalOffset * 4)]);
  98197. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  98198. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  98199. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  98200. }
  98201. ++vertexCount;
  98202. });
  98203. }
  98204. }
  98205. var startingIndex = this._reconstructedMesh.getTotalIndices();
  98206. var startingVertex = this._reconstructedMesh.getTotalVertices();
  98207. var submeshesArray = this._reconstructedMesh.subMeshes;
  98208. this._reconstructedMesh.subMeshes = [];
  98209. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  98210. var originalIndices = this._mesh.getIndices();
  98211. for (i = 0; i < newTriangles.length; ++i) {
  98212. t = newTriangles[i]; //now get the new referencing point for each vertex
  98213. [0, 1, 2].forEach(function (idx) {
  98214. var id = originalIndices[t.originalOffset + idx];
  98215. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  98216. if (offset < 0)
  98217. offset = 0;
  98218. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  98219. });
  98220. }
  98221. //overwriting the old vertex buffers and indices.
  98222. this._reconstructedMesh.setIndices(newIndicesArray);
  98223. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  98224. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  98225. if (newUVsData.length > 0)
  98226. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  98227. if (newColorsData.length > 0)
  98228. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  98229. //create submesh
  98230. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  98231. if (submeshIndex > 0) {
  98232. this._reconstructedMesh.subMeshes = [];
  98233. submeshesArray.forEach(function (submesh) {
  98234. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  98235. });
  98236. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  98237. }
  98238. };
  98239. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  98240. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  98241. this._reconstructedMesh.material = this._mesh.material;
  98242. this._reconstructedMesh.parent = this._mesh.parent;
  98243. this._reconstructedMesh.isVisible = false;
  98244. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  98245. };
  98246. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  98247. for (var i = 0; i < vertex1.triangleCount; ++i) {
  98248. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  98249. if (t.deleted)
  98250. continue;
  98251. var s = this.references[vertex1.triangleStart + i].vertexId;
  98252. var v1 = t.vertices[(s + 1) % 3];
  98253. var v2 = t.vertices[(s + 2) % 3];
  98254. if ((v1 === vertex2 || v2 === vertex2)) {
  98255. deletedArray[i] = true;
  98256. delTr.push(t);
  98257. continue;
  98258. }
  98259. var d1 = v1.position.subtract(point);
  98260. d1 = d1.normalize();
  98261. var d2 = v2.position.subtract(point);
  98262. d2 = d2.normalize();
  98263. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  98264. return true;
  98265. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  98266. deletedArray[i] = false;
  98267. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  98268. return true;
  98269. }
  98270. return false;
  98271. };
  98272. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  98273. var newDeleted = deletedTriangles;
  98274. for (var i = 0; i < vertex.triangleCount; ++i) {
  98275. var ref = this.references[vertex.triangleStart + i];
  98276. var t = this.triangles[ref.triangleId];
  98277. if (t.deleted)
  98278. continue;
  98279. if (deletedArray[i] && t.deletePending) {
  98280. t.deleted = true;
  98281. newDeleted++;
  98282. continue;
  98283. }
  98284. t.vertices[ref.vertexId] = origVertex;
  98285. t.isDirty = true;
  98286. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  98287. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  98288. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  98289. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  98290. this.references.push(ref);
  98291. }
  98292. return newDeleted;
  98293. };
  98294. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  98295. for (var i = 0; i < this.vertices.length; ++i) {
  98296. var vCount = [];
  98297. var vId = [];
  98298. var v = this.vertices[i];
  98299. var j;
  98300. for (j = 0; j < v.triangleCount; ++j) {
  98301. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  98302. for (var ii = 0; ii < 3; ii++) {
  98303. var ofs = 0;
  98304. var vv = triangle.vertices[ii];
  98305. while (ofs < vCount.length) {
  98306. if (vId[ofs] === vv.id)
  98307. break;
  98308. ++ofs;
  98309. }
  98310. if (ofs === vCount.length) {
  98311. vCount.push(1);
  98312. vId.push(vv.id);
  98313. }
  98314. else {
  98315. vCount[ofs]++;
  98316. }
  98317. }
  98318. }
  98319. for (j = 0; j < vCount.length; ++j) {
  98320. if (vCount[j] === 1) {
  98321. this.vertices[vId[j]].isBorder = true;
  98322. }
  98323. else {
  98324. this.vertices[vId[j]].isBorder = false;
  98325. }
  98326. }
  98327. }
  98328. };
  98329. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  98330. if (identifyBorders === void 0) { identifyBorders = false; }
  98331. var i;
  98332. if (!identifyBorders) {
  98333. var newTrianglesVector = [];
  98334. for (i = 0; i < this.triangles.length; ++i) {
  98335. if (!this.triangles[i].deleted) {
  98336. newTrianglesVector.push(this.triangles[i]);
  98337. }
  98338. }
  98339. this.triangles = newTrianglesVector;
  98340. }
  98341. for (i = 0; i < this.vertices.length; ++i) {
  98342. this.vertices[i].triangleCount = 0;
  98343. this.vertices[i].triangleStart = 0;
  98344. }
  98345. var t;
  98346. var j;
  98347. var v;
  98348. for (i = 0; i < this.triangles.length; ++i) {
  98349. t = this.triangles[i];
  98350. for (j = 0; j < 3; ++j) {
  98351. v = t.vertices[j];
  98352. v.triangleCount++;
  98353. }
  98354. }
  98355. var tStart = 0;
  98356. for (i = 0; i < this.vertices.length; ++i) {
  98357. this.vertices[i].triangleStart = tStart;
  98358. tStart += this.vertices[i].triangleCount;
  98359. this.vertices[i].triangleCount = 0;
  98360. }
  98361. var newReferences = new Array(this.triangles.length * 3);
  98362. for (i = 0; i < this.triangles.length; ++i) {
  98363. t = this.triangles[i];
  98364. for (j = 0; j < 3; ++j) {
  98365. v = t.vertices[j];
  98366. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  98367. v.triangleCount++;
  98368. }
  98369. }
  98370. this.references = newReferences;
  98371. if (identifyBorders) {
  98372. this.identifyBorder();
  98373. }
  98374. };
  98375. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  98376. var x = point.x;
  98377. var y = point.y;
  98378. var z = point.z;
  98379. 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
  98380. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  98381. };
  98382. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  98383. var q = vertex1.q.add(vertex2.q);
  98384. var border = vertex1.isBorder && vertex2.isBorder;
  98385. var error = 0;
  98386. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  98387. if (qDet !== 0 && !border) {
  98388. if (!pointResult) {
  98389. pointResult = BABYLON.Vector3.Zero();
  98390. }
  98391. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  98392. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  98393. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  98394. error = this.vertexError(q, pointResult);
  98395. }
  98396. else {
  98397. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  98398. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  98399. var error1 = this.vertexError(q, vertex1.position);
  98400. var error2 = this.vertexError(q, vertex2.position);
  98401. var error3 = this.vertexError(q, p3);
  98402. error = Math.min(error1, error2, error3);
  98403. if (error === error1) {
  98404. if (pointResult) {
  98405. pointResult.copyFrom(vertex1.position);
  98406. }
  98407. }
  98408. else if (error === error2) {
  98409. if (pointResult) {
  98410. pointResult.copyFrom(vertex2.position);
  98411. }
  98412. }
  98413. else {
  98414. if (pointResult) {
  98415. pointResult.copyFrom(p3);
  98416. }
  98417. }
  98418. }
  98419. return error;
  98420. };
  98421. return QuadraticErrorSimplification;
  98422. }());
  98423. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  98424. })(BABYLON || (BABYLON = {}));
  98425. //# sourceMappingURL=babylon.meshSimplification.js.map
  98426. var BABYLON;
  98427. (function (BABYLON) {
  98428. Object.defineProperty(BABYLON.Scene.prototype, "simplificationQueue", {
  98429. get: function () {
  98430. if (!this._simplificationQueue) {
  98431. this._simplificationQueue = new BABYLON.SimplificationQueue();
  98432. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);
  98433. if (!component) {
  98434. component = new SimplicationQueueSceneComponent(this);
  98435. this._addComponent(component);
  98436. }
  98437. }
  98438. return this._simplificationQueue;
  98439. },
  98440. set: function (value) {
  98441. this._simplificationQueue = value;
  98442. },
  98443. enumerable: true,
  98444. configurable: true
  98445. });
  98446. BABYLON.Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  98447. if (parallelProcessing === void 0) { parallelProcessing = true; }
  98448. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  98449. this.getScene().simplificationQueue.addTask({
  98450. settings: settings,
  98451. parallelProcessing: parallelProcessing,
  98452. mesh: this,
  98453. simplificationType: simplificationType,
  98454. successCallback: successCallback
  98455. });
  98456. return this;
  98457. };
  98458. /**
  98459. * Defines the simplification queue scene component responsible to help scheduling the various simplification task
  98460. * created in a scene
  98461. */
  98462. var SimplicationQueueSceneComponent = /** @class */ (function () {
  98463. /**
  98464. * Creates a new instance of the component for the given scene
  98465. * @param scene Defines the scene to register the component in
  98466. */
  98467. function SimplicationQueueSceneComponent(scene) {
  98468. /**
  98469. * The component name helpfull to identify the component in the list of scene components.
  98470. */
  98471. this.name = BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE;
  98472. this.scene = scene;
  98473. }
  98474. /**
  98475. * Registers the component in a given scene
  98476. */
  98477. SimplicationQueueSceneComponent.prototype.register = function () {
  98478. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate);
  98479. };
  98480. /**
  98481. * Rebuilds the elements related to this component in case of
  98482. * context lost for instance.
  98483. */
  98484. SimplicationQueueSceneComponent.prototype.rebuild = function () {
  98485. // Nothing to do for this component
  98486. };
  98487. /**
  98488. * Disposes the component and the associated ressources
  98489. */
  98490. SimplicationQueueSceneComponent.prototype.dispose = function () {
  98491. // Nothing to do for this component
  98492. };
  98493. SimplicationQueueSceneComponent.prototype._beforeCameraUpdate = function () {
  98494. if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) {
  98495. this.scene._simplificationQueue.executeNext();
  98496. }
  98497. };
  98498. return SimplicationQueueSceneComponent;
  98499. }());
  98500. BABYLON.SimplicationQueueSceneComponent = SimplicationQueueSceneComponent;
  98501. })(BABYLON || (BABYLON = {}));
  98502. //# sourceMappingURL=babylon.meshSimplificationSceneComponent.js.map
  98503. var BABYLON;
  98504. (function (BABYLON) {
  98505. var MeshLODLevel = /** @class */ (function () {
  98506. function MeshLODLevel(distance, mesh) {
  98507. this.distance = distance;
  98508. this.mesh = mesh;
  98509. }
  98510. return MeshLODLevel;
  98511. }());
  98512. BABYLON.MeshLODLevel = MeshLODLevel;
  98513. })(BABYLON || (BABYLON = {}));
  98514. //# sourceMappingURL=babylon.meshLODLevel.js.map
  98515. var BABYLON;
  98516. (function (BABYLON) {
  98517. /**
  98518. * Defines the root class used to create scene optimization to use with SceneOptimizer
  98519. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98520. */
  98521. var SceneOptimization = /** @class */ (function () {
  98522. /**
  98523. * Creates the SceneOptimization object
  98524. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  98525. * @param desc defines the description associated with the optimization
  98526. */
  98527. function SceneOptimization(
  98528. /**
  98529. * Defines the priority of this optimization (0 by default which means first in the list)
  98530. */
  98531. priority) {
  98532. if (priority === void 0) { priority = 0; }
  98533. this.priority = priority;
  98534. }
  98535. /**
  98536. * Gets a string describing the action executed by the current optimization
  98537. * @returns description string
  98538. */
  98539. SceneOptimization.prototype.getDescription = function () {
  98540. return "";
  98541. };
  98542. /**
  98543. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98544. * @param scene defines the current scene where to apply this optimization
  98545. * @param optimizer defines the current optimizer
  98546. * @returns true if everything that can be done was applied
  98547. */
  98548. SceneOptimization.prototype.apply = function (scene, optimizer) {
  98549. return true;
  98550. };
  98551. ;
  98552. return SceneOptimization;
  98553. }());
  98554. BABYLON.SceneOptimization = SceneOptimization;
  98555. /**
  98556. * Defines an optimization used to reduce the size of render target textures
  98557. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98558. */
  98559. var TextureOptimization = /** @class */ (function (_super) {
  98560. __extends(TextureOptimization, _super);
  98561. /**
  98562. * Creates the TextureOptimization object
  98563. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  98564. * @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
  98565. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  98566. */
  98567. function TextureOptimization(
  98568. /**
  98569. * Defines the priority of this optimization (0 by default which means first in the list)
  98570. */
  98571. priority,
  98572. /**
  98573. * 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
  98574. */
  98575. maximumSize,
  98576. /**
  98577. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  98578. */
  98579. step) {
  98580. if (priority === void 0) { priority = 0; }
  98581. if (maximumSize === void 0) { maximumSize = 1024; }
  98582. if (step === void 0) { step = 0.5; }
  98583. var _this = _super.call(this, priority) || this;
  98584. _this.priority = priority;
  98585. _this.maximumSize = maximumSize;
  98586. _this.step = step;
  98587. return _this;
  98588. }
  98589. /**
  98590. * Gets a string describing the action executed by the current optimization
  98591. * @returns description string
  98592. */
  98593. TextureOptimization.prototype.getDescription = function () {
  98594. return "Reducing render target texture size to " + this.maximumSize;
  98595. };
  98596. /**
  98597. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98598. * @param scene defines the current scene where to apply this optimization
  98599. * @param optimizer defines the current optimizer
  98600. * @returns true if everything that can be done was applied
  98601. */
  98602. TextureOptimization.prototype.apply = function (scene, optimizer) {
  98603. var allDone = true;
  98604. for (var index = 0; index < scene.textures.length; index++) {
  98605. var texture = scene.textures[index];
  98606. if (!texture.canRescale || texture.getContext) {
  98607. continue;
  98608. }
  98609. var currentSize = texture.getSize();
  98610. var maxDimension = Math.max(currentSize.width, currentSize.height);
  98611. if (maxDimension > this.maximumSize) {
  98612. texture.scale(this.step);
  98613. allDone = false;
  98614. }
  98615. }
  98616. return allDone;
  98617. };
  98618. return TextureOptimization;
  98619. }(SceneOptimization));
  98620. BABYLON.TextureOptimization = TextureOptimization;
  98621. /**
  98622. * Defines an optimization used to increase or decrease the rendering resolution
  98623. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98624. */
  98625. var HardwareScalingOptimization = /** @class */ (function (_super) {
  98626. __extends(HardwareScalingOptimization, _super);
  98627. /**
  98628. * Creates the HardwareScalingOptimization object
  98629. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  98630. * @param maximumScale defines the maximum scale to use (2 by default)
  98631. * @param step defines the step to use between two passes (0.5 by default)
  98632. */
  98633. function HardwareScalingOptimization(
  98634. /**
  98635. * Defines the priority of this optimization (0 by default which means first in the list)
  98636. */
  98637. priority,
  98638. /**
  98639. * Defines the maximum scale to use (2 by default)
  98640. */
  98641. maximumScale,
  98642. /**
  98643. * Defines the step to use between two passes (0.5 by default)
  98644. */
  98645. step) {
  98646. if (priority === void 0) { priority = 0; }
  98647. if (maximumScale === void 0) { maximumScale = 2; }
  98648. if (step === void 0) { step = 0.25; }
  98649. var _this = _super.call(this, priority) || this;
  98650. _this.priority = priority;
  98651. _this.maximumScale = maximumScale;
  98652. _this.step = step;
  98653. _this._currentScale = -1;
  98654. _this._directionOffset = 1;
  98655. return _this;
  98656. }
  98657. /**
  98658. * Gets a string describing the action executed by the current optimization
  98659. * @return description string
  98660. */
  98661. HardwareScalingOptimization.prototype.getDescription = function () {
  98662. return "Setting hardware scaling level to " + this._currentScale;
  98663. };
  98664. /**
  98665. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98666. * @param scene defines the current scene where to apply this optimization
  98667. * @param optimizer defines the current optimizer
  98668. * @returns true if everything that can be done was applied
  98669. */
  98670. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  98671. if (this._currentScale === -1) {
  98672. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  98673. if (this._currentScale > this.maximumScale) {
  98674. this._directionOffset = -1;
  98675. }
  98676. }
  98677. this._currentScale += this._directionOffset * this.step;
  98678. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  98679. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  98680. };
  98681. ;
  98682. return HardwareScalingOptimization;
  98683. }(SceneOptimization));
  98684. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  98685. /**
  98686. * Defines an optimization used to remove shadows
  98687. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98688. */
  98689. var ShadowsOptimization = /** @class */ (function (_super) {
  98690. __extends(ShadowsOptimization, _super);
  98691. function ShadowsOptimization() {
  98692. return _super !== null && _super.apply(this, arguments) || this;
  98693. }
  98694. /**
  98695. * Gets a string describing the action executed by the current optimization
  98696. * @return description string
  98697. */
  98698. ShadowsOptimization.prototype.getDescription = function () {
  98699. return "Turning shadows on/off";
  98700. };
  98701. /**
  98702. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98703. * @param scene defines the current scene where to apply this optimization
  98704. * @param optimizer defines the current optimizer
  98705. * @returns true if everything that can be done was applied
  98706. */
  98707. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  98708. scene.shadowsEnabled = optimizer.isInImprovementMode;
  98709. return true;
  98710. };
  98711. ;
  98712. return ShadowsOptimization;
  98713. }(SceneOptimization));
  98714. BABYLON.ShadowsOptimization = ShadowsOptimization;
  98715. /**
  98716. * Defines an optimization used to turn post-processes off
  98717. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98718. */
  98719. var PostProcessesOptimization = /** @class */ (function (_super) {
  98720. __extends(PostProcessesOptimization, _super);
  98721. function PostProcessesOptimization() {
  98722. return _super !== null && _super.apply(this, arguments) || this;
  98723. }
  98724. /**
  98725. * Gets a string describing the action executed by the current optimization
  98726. * @return description string
  98727. */
  98728. PostProcessesOptimization.prototype.getDescription = function () {
  98729. return "Turning post-processes on/off";
  98730. };
  98731. /**
  98732. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98733. * @param scene defines the current scene where to apply this optimization
  98734. * @param optimizer defines the current optimizer
  98735. * @returns true if everything that can be done was applied
  98736. */
  98737. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  98738. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  98739. return true;
  98740. };
  98741. ;
  98742. return PostProcessesOptimization;
  98743. }(SceneOptimization));
  98744. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  98745. /**
  98746. * Defines an optimization used to turn lens flares off
  98747. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98748. */
  98749. var LensFlaresOptimization = /** @class */ (function (_super) {
  98750. __extends(LensFlaresOptimization, _super);
  98751. function LensFlaresOptimization() {
  98752. return _super !== null && _super.apply(this, arguments) || this;
  98753. }
  98754. /**
  98755. * Gets a string describing the action executed by the current optimization
  98756. * @return description string
  98757. */
  98758. LensFlaresOptimization.prototype.getDescription = function () {
  98759. return "Turning lens flares on/off";
  98760. };
  98761. /**
  98762. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98763. * @param scene defines the current scene where to apply this optimization
  98764. * @param optimizer defines the current optimizer
  98765. * @returns true if everything that can be done was applied
  98766. */
  98767. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  98768. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  98769. return true;
  98770. };
  98771. ;
  98772. return LensFlaresOptimization;
  98773. }(SceneOptimization));
  98774. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  98775. /**
  98776. * Defines an optimization based on user defined callback.
  98777. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98778. */
  98779. var CustomOptimization = /** @class */ (function (_super) {
  98780. __extends(CustomOptimization, _super);
  98781. function CustomOptimization() {
  98782. return _super !== null && _super.apply(this, arguments) || this;
  98783. }
  98784. /**
  98785. * Gets a string describing the action executed by the current optimization
  98786. * @returns description string
  98787. */
  98788. CustomOptimization.prototype.getDescription = function () {
  98789. if (this.onGetDescription) {
  98790. return this.onGetDescription();
  98791. }
  98792. return "Running user defined callback";
  98793. };
  98794. /**
  98795. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98796. * @param scene defines the current scene where to apply this optimization
  98797. * @param optimizer defines the current optimizer
  98798. * @returns true if everything that can be done was applied
  98799. */
  98800. CustomOptimization.prototype.apply = function (scene, optimizer) {
  98801. if (this.onApply) {
  98802. return this.onApply(scene, optimizer);
  98803. }
  98804. return true;
  98805. };
  98806. ;
  98807. return CustomOptimization;
  98808. }(SceneOptimization));
  98809. BABYLON.CustomOptimization = CustomOptimization;
  98810. /**
  98811. * Defines an optimization used to turn particles off
  98812. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98813. */
  98814. var ParticlesOptimization = /** @class */ (function (_super) {
  98815. __extends(ParticlesOptimization, _super);
  98816. function ParticlesOptimization() {
  98817. return _super !== null && _super.apply(this, arguments) || this;
  98818. }
  98819. /**
  98820. * Gets a string describing the action executed by the current optimization
  98821. * @return description string
  98822. */
  98823. ParticlesOptimization.prototype.getDescription = function () {
  98824. return "Turning particles on/off";
  98825. };
  98826. /**
  98827. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98828. * @param scene defines the current scene where to apply this optimization
  98829. * @param optimizer defines the current optimizer
  98830. * @returns true if everything that can be done was applied
  98831. */
  98832. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  98833. scene.particlesEnabled = optimizer.isInImprovementMode;
  98834. return true;
  98835. };
  98836. ;
  98837. return ParticlesOptimization;
  98838. }(SceneOptimization));
  98839. BABYLON.ParticlesOptimization = ParticlesOptimization;
  98840. /**
  98841. * Defines an optimization used to turn render targets off
  98842. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98843. */
  98844. var RenderTargetsOptimization = /** @class */ (function (_super) {
  98845. __extends(RenderTargetsOptimization, _super);
  98846. function RenderTargetsOptimization() {
  98847. return _super !== null && _super.apply(this, arguments) || this;
  98848. }
  98849. /**
  98850. * Gets a string describing the action executed by the current optimization
  98851. * @return description string
  98852. */
  98853. RenderTargetsOptimization.prototype.getDescription = function () {
  98854. return "Turning render targets off";
  98855. };
  98856. /**
  98857. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98858. * @param scene defines the current scene where to apply this optimization
  98859. * @param optimizer defines the current optimizer
  98860. * @returns true if everything that can be done was applied
  98861. */
  98862. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  98863. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  98864. return true;
  98865. };
  98866. ;
  98867. return RenderTargetsOptimization;
  98868. }(SceneOptimization));
  98869. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  98870. /**
  98871. * Defines an optimization used to merge meshes with compatible materials
  98872. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98873. */
  98874. var MergeMeshesOptimization = /** @class */ (function (_super) {
  98875. __extends(MergeMeshesOptimization, _super);
  98876. function MergeMeshesOptimization() {
  98877. var _this = _super !== null && _super.apply(this, arguments) || this;
  98878. _this._canBeMerged = function (abstractMesh) {
  98879. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  98880. return false;
  98881. }
  98882. var mesh = abstractMesh;
  98883. if (mesh.isDisposed()) {
  98884. return false;
  98885. }
  98886. if (!mesh.isVisible || !mesh.isEnabled()) {
  98887. return false;
  98888. }
  98889. if (mesh.instances.length > 0) {
  98890. return false;
  98891. }
  98892. if (mesh.skeleton || mesh.hasLODLevels) {
  98893. return false;
  98894. }
  98895. return true;
  98896. };
  98897. return _this;
  98898. }
  98899. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  98900. /**
  98901. * Gets or sets a boolean which defines if optimization octree has to be updated
  98902. */
  98903. get: function () {
  98904. return MergeMeshesOptimization._UpdateSelectionTree;
  98905. },
  98906. /**
  98907. * Gets or sets a boolean which defines if optimization octree has to be updated
  98908. */
  98909. set: function (value) {
  98910. MergeMeshesOptimization._UpdateSelectionTree = value;
  98911. },
  98912. enumerable: true,
  98913. configurable: true
  98914. });
  98915. /**
  98916. * Gets a string describing the action executed by the current optimization
  98917. * @return description string
  98918. */
  98919. MergeMeshesOptimization.prototype.getDescription = function () {
  98920. return "Merging similar meshes together";
  98921. };
  98922. /**
  98923. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98924. * @param scene defines the current scene where to apply this optimization
  98925. * @param optimizer defines the current optimizer
  98926. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  98927. * @returns true if everything that can be done was applied
  98928. */
  98929. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  98930. var globalPool = scene.meshes.slice(0);
  98931. var globalLength = globalPool.length;
  98932. for (var index = 0; index < globalLength; index++) {
  98933. var currentPool = new Array();
  98934. var current = globalPool[index];
  98935. // Checks
  98936. if (!this._canBeMerged(current)) {
  98937. continue;
  98938. }
  98939. currentPool.push(current);
  98940. // Find compatible meshes
  98941. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  98942. var otherMesh = globalPool[subIndex];
  98943. if (!this._canBeMerged(otherMesh)) {
  98944. continue;
  98945. }
  98946. if (otherMesh.material !== current.material) {
  98947. continue;
  98948. }
  98949. if (otherMesh.checkCollisions !== current.checkCollisions) {
  98950. continue;
  98951. }
  98952. currentPool.push(otherMesh);
  98953. globalLength--;
  98954. globalPool.splice(subIndex, 1);
  98955. subIndex--;
  98956. }
  98957. if (currentPool.length < 2) {
  98958. continue;
  98959. }
  98960. // Merge meshes
  98961. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  98962. }
  98963. if (updateSelectionTree != undefined) {
  98964. if (updateSelectionTree) {
  98965. scene.createOrUpdateSelectionOctree();
  98966. }
  98967. }
  98968. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  98969. scene.createOrUpdateSelectionOctree();
  98970. }
  98971. return true;
  98972. };
  98973. ;
  98974. MergeMeshesOptimization._UpdateSelectionTree = false;
  98975. return MergeMeshesOptimization;
  98976. }(SceneOptimization));
  98977. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  98978. /**
  98979. * Defines a list of options used by SceneOptimizer
  98980. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98981. */
  98982. var SceneOptimizerOptions = /** @class */ (function () {
  98983. /**
  98984. * Creates a new list of options used by SceneOptimizer
  98985. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  98986. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  98987. */
  98988. function SceneOptimizerOptions(
  98989. /**
  98990. * Defines the target frame rate to reach (60 by default)
  98991. */
  98992. targetFrameRate,
  98993. /**
  98994. * Defines the interval between two checkes (2000ms by default)
  98995. */
  98996. trackerDuration) {
  98997. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  98998. if (trackerDuration === void 0) { trackerDuration = 2000; }
  98999. this.targetFrameRate = targetFrameRate;
  99000. this.trackerDuration = trackerDuration;
  99001. /**
  99002. * Gets the list of optimizations to apply
  99003. */
  99004. this.optimizations = new Array();
  99005. }
  99006. /**
  99007. * Add a new optimization
  99008. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  99009. * @returns the current SceneOptimizerOptions
  99010. */
  99011. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  99012. this.optimizations.push(optimization);
  99013. return this;
  99014. };
  99015. /**
  99016. * Add a new custom optimization
  99017. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  99018. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  99019. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  99020. * @returns the current SceneOptimizerOptions
  99021. */
  99022. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  99023. if (priority === void 0) { priority = 0; }
  99024. var optimization = new CustomOptimization(priority);
  99025. optimization.onApply = onApply;
  99026. optimization.onGetDescription = onGetDescription;
  99027. this.optimizations.push(optimization);
  99028. return this;
  99029. };
  99030. /**
  99031. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  99032. * @param targetFrameRate defines the target frame rate (60 by default)
  99033. * @returns a SceneOptimizerOptions object
  99034. */
  99035. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  99036. var result = new SceneOptimizerOptions(targetFrameRate);
  99037. var priority = 0;
  99038. result.addOptimization(new MergeMeshesOptimization(priority));
  99039. result.addOptimization(new ShadowsOptimization(priority));
  99040. result.addOptimization(new LensFlaresOptimization(priority));
  99041. // Next priority
  99042. priority++;
  99043. result.addOptimization(new PostProcessesOptimization(priority));
  99044. result.addOptimization(new ParticlesOptimization(priority));
  99045. // Next priority
  99046. priority++;
  99047. result.addOptimization(new TextureOptimization(priority, 1024));
  99048. return result;
  99049. };
  99050. /**
  99051. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  99052. * @param targetFrameRate defines the target frame rate (60 by default)
  99053. * @returns a SceneOptimizerOptions object
  99054. */
  99055. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  99056. var result = new SceneOptimizerOptions(targetFrameRate);
  99057. var priority = 0;
  99058. result.addOptimization(new MergeMeshesOptimization(priority));
  99059. result.addOptimization(new ShadowsOptimization(priority));
  99060. result.addOptimization(new LensFlaresOptimization(priority));
  99061. // Next priority
  99062. priority++;
  99063. result.addOptimization(new PostProcessesOptimization(priority));
  99064. result.addOptimization(new ParticlesOptimization(priority));
  99065. // Next priority
  99066. priority++;
  99067. result.addOptimization(new TextureOptimization(priority, 512));
  99068. // Next priority
  99069. priority++;
  99070. result.addOptimization(new RenderTargetsOptimization(priority));
  99071. // Next priority
  99072. priority++;
  99073. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  99074. return result;
  99075. };
  99076. /**
  99077. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  99078. * @param targetFrameRate defines the target frame rate (60 by default)
  99079. * @returns a SceneOptimizerOptions object
  99080. */
  99081. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  99082. var result = new SceneOptimizerOptions(targetFrameRate);
  99083. var priority = 0;
  99084. result.addOptimization(new MergeMeshesOptimization(priority));
  99085. result.addOptimization(new ShadowsOptimization(priority));
  99086. result.addOptimization(new LensFlaresOptimization(priority));
  99087. // Next priority
  99088. priority++;
  99089. result.addOptimization(new PostProcessesOptimization(priority));
  99090. result.addOptimization(new ParticlesOptimization(priority));
  99091. // Next priority
  99092. priority++;
  99093. result.addOptimization(new TextureOptimization(priority, 256));
  99094. // Next priority
  99095. priority++;
  99096. result.addOptimization(new RenderTargetsOptimization(priority));
  99097. // Next priority
  99098. priority++;
  99099. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  99100. return result;
  99101. };
  99102. return SceneOptimizerOptions;
  99103. }());
  99104. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  99105. /**
  99106. * Class used to run optimizations in order to reach a target frame rate
  99107. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  99108. */
  99109. var SceneOptimizer = /** @class */ (function () {
  99110. /**
  99111. * Creates a new SceneOptimizer
  99112. * @param scene defines the scene to work on
  99113. * @param options defines the options to use with the SceneOptimizer
  99114. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  99115. * @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)
  99116. */
  99117. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  99118. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  99119. if (improvementMode === void 0) { improvementMode = false; }
  99120. var _this = this;
  99121. this._isRunning = false;
  99122. this._currentPriorityLevel = 0;
  99123. this._targetFrameRate = 60;
  99124. this._trackerDuration = 2000;
  99125. this._currentFrameRate = 0;
  99126. this._improvementMode = false;
  99127. /**
  99128. * Defines an observable called when the optimizer reaches the target frame rate
  99129. */
  99130. this.onSuccessObservable = new BABYLON.Observable();
  99131. /**
  99132. * Defines an observable called when the optimizer enables an optimization
  99133. */
  99134. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  99135. /**
  99136. * Defines an observable called when the optimizer is not able to reach the target frame rate
  99137. */
  99138. this.onFailureObservable = new BABYLON.Observable();
  99139. if (!options) {
  99140. this._options = new SceneOptimizerOptions();
  99141. }
  99142. else {
  99143. this._options = options;
  99144. }
  99145. if (this._options.targetFrameRate) {
  99146. this._targetFrameRate = this._options.targetFrameRate;
  99147. }
  99148. if (this._options.trackerDuration) {
  99149. this._trackerDuration = this._options.trackerDuration;
  99150. }
  99151. if (autoGeneratePriorities) {
  99152. var priority = 0;
  99153. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  99154. var optim = _a[_i];
  99155. optim.priority = priority++;
  99156. }
  99157. }
  99158. this._improvementMode = improvementMode;
  99159. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  99160. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  99161. _this._sceneDisposeObserver = null;
  99162. _this.dispose();
  99163. });
  99164. }
  99165. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  99166. /**
  99167. * Gets a boolean indicating if the optimizer is in improvement mode
  99168. */
  99169. get: function () {
  99170. return this._improvementMode;
  99171. },
  99172. enumerable: true,
  99173. configurable: true
  99174. });
  99175. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  99176. /**
  99177. * Gets the current priority level (0 at start)
  99178. */
  99179. get: function () {
  99180. return this._currentPriorityLevel;
  99181. },
  99182. enumerable: true,
  99183. configurable: true
  99184. });
  99185. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  99186. /**
  99187. * Gets the current frame rate checked by the SceneOptimizer
  99188. */
  99189. get: function () {
  99190. return this._currentFrameRate;
  99191. },
  99192. enumerable: true,
  99193. configurable: true
  99194. });
  99195. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  99196. /**
  99197. * Gets or sets the current target frame rate (60 by default)
  99198. */
  99199. get: function () {
  99200. return this._targetFrameRate;
  99201. },
  99202. /**
  99203. * Gets or sets the current target frame rate (60 by default)
  99204. */
  99205. set: function (value) {
  99206. this._targetFrameRate = value;
  99207. },
  99208. enumerable: true,
  99209. configurable: true
  99210. });
  99211. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  99212. /**
  99213. * Gets or sets the current interval between two checks (every 2000ms by default)
  99214. */
  99215. get: function () {
  99216. return this._trackerDuration;
  99217. },
  99218. /**
  99219. * Gets or sets the current interval between two checks (every 2000ms by default)
  99220. */
  99221. set: function (value) {
  99222. this._trackerDuration = value;
  99223. },
  99224. enumerable: true,
  99225. configurable: true
  99226. });
  99227. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  99228. /**
  99229. * Gets the list of active optimizations
  99230. */
  99231. get: function () {
  99232. return this._options.optimizations;
  99233. },
  99234. enumerable: true,
  99235. configurable: true
  99236. });
  99237. /**
  99238. * Stops the current optimizer
  99239. */
  99240. SceneOptimizer.prototype.stop = function () {
  99241. this._isRunning = false;
  99242. };
  99243. /**
  99244. * Reset the optimizer to initial step (current priority level = 0)
  99245. */
  99246. SceneOptimizer.prototype.reset = function () {
  99247. this._currentPriorityLevel = 0;
  99248. };
  99249. /**
  99250. * Start the optimizer. By default it will try to reach a specific framerate
  99251. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  99252. */
  99253. SceneOptimizer.prototype.start = function () {
  99254. var _this = this;
  99255. if (this._isRunning) {
  99256. return;
  99257. }
  99258. this._isRunning = true;
  99259. // Let's wait for the scene to be ready before running our check
  99260. this._scene.executeWhenReady(function () {
  99261. setTimeout(function () {
  99262. _this._checkCurrentState();
  99263. }, _this._trackerDuration);
  99264. });
  99265. };
  99266. SceneOptimizer.prototype._checkCurrentState = function () {
  99267. var _this = this;
  99268. if (!this._isRunning) {
  99269. return;
  99270. }
  99271. var scene = this._scene;
  99272. var options = this._options;
  99273. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  99274. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  99275. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  99276. this._isRunning = false;
  99277. this.onSuccessObservable.notifyObservers(this);
  99278. return;
  99279. }
  99280. // Apply current level of optimizations
  99281. var allDone = true;
  99282. var noOptimizationApplied = true;
  99283. for (var index = 0; index < options.optimizations.length; index++) {
  99284. var optimization = options.optimizations[index];
  99285. if (optimization.priority === this._currentPriorityLevel) {
  99286. noOptimizationApplied = false;
  99287. allDone = allDone && optimization.apply(scene, this);
  99288. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  99289. }
  99290. }
  99291. // If no optimization was applied, this is a failure :(
  99292. if (noOptimizationApplied) {
  99293. this._isRunning = false;
  99294. this.onFailureObservable.notifyObservers(this);
  99295. return;
  99296. }
  99297. // If all optimizations were done, move to next level
  99298. if (allDone) {
  99299. this._currentPriorityLevel++;
  99300. }
  99301. // Let's the system running for a specific amount of time before checking FPS
  99302. scene.executeWhenReady(function () {
  99303. setTimeout(function () {
  99304. _this._checkCurrentState();
  99305. }, _this._trackerDuration);
  99306. });
  99307. };
  99308. /**
  99309. * Release all resources
  99310. */
  99311. SceneOptimizer.prototype.dispose = function () {
  99312. this.stop();
  99313. this.onSuccessObservable.clear();
  99314. this.onFailureObservable.clear();
  99315. this.onNewOptimizationAppliedObservable.clear();
  99316. if (this._sceneDisposeObserver) {
  99317. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  99318. }
  99319. };
  99320. /**
  99321. * Helper function to create a SceneOptimizer with one single line of code
  99322. * @param scene defines the scene to work on
  99323. * @param options defines the options to use with the SceneOptimizer
  99324. * @param onSuccess defines a callback to call on success
  99325. * @param onFailure defines a callback to call on failure
  99326. * @returns the new SceneOptimizer object
  99327. */
  99328. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  99329. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  99330. if (onSuccess) {
  99331. optimizer.onSuccessObservable.add(function () {
  99332. onSuccess();
  99333. });
  99334. }
  99335. if (onFailure) {
  99336. optimizer.onFailureObservable.add(function () {
  99337. onFailure();
  99338. });
  99339. }
  99340. optimizer.start();
  99341. return optimizer;
  99342. };
  99343. return SceneOptimizer;
  99344. }());
  99345. BABYLON.SceneOptimizer = SceneOptimizer;
  99346. })(BABYLON || (BABYLON = {}));
  99347. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  99348. var BABYLON;
  99349. (function (BABYLON) {
  99350. var OutlineRenderer = /** @class */ (function () {
  99351. function OutlineRenderer(scene) {
  99352. this.zOffset = 1;
  99353. this._scene = scene;
  99354. }
  99355. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  99356. var _this = this;
  99357. if (useOverlay === void 0) { useOverlay = false; }
  99358. var scene = this._scene;
  99359. var engine = this._scene.getEngine();
  99360. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  99361. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  99362. return;
  99363. }
  99364. var mesh = subMesh.getRenderingMesh();
  99365. var material = subMesh.getMaterial();
  99366. if (!material || !scene.activeCamera) {
  99367. return;
  99368. }
  99369. engine.enableEffect(this._effect);
  99370. // Logarithmic depth
  99371. if (material.useLogarithmicDepth) {
  99372. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  99373. }
  99374. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  99375. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  99376. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  99377. // Bones
  99378. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  99379. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  99380. }
  99381. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  99382. // Alpha test
  99383. if (material && material.needAlphaTesting()) {
  99384. var alphaTexture = material.getAlphaTestTexture();
  99385. if (alphaTexture) {
  99386. this._effect.setTexture("diffuseSampler", alphaTexture);
  99387. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  99388. }
  99389. }
  99390. engine.setZOffset(-this.zOffset);
  99391. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  99392. engine.setZOffset(0);
  99393. };
  99394. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  99395. var defines = [];
  99396. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  99397. var mesh = subMesh.getMesh();
  99398. var material = subMesh.getMaterial();
  99399. if (material) {
  99400. // Alpha test
  99401. if (material.needAlphaTesting()) {
  99402. defines.push("#define ALPHATEST");
  99403. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  99404. attribs.push(BABYLON.VertexBuffer.UVKind);
  99405. defines.push("#define UV1");
  99406. }
  99407. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  99408. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  99409. defines.push("#define UV2");
  99410. }
  99411. }
  99412. //Logarithmic depth
  99413. if (material.useLogarithmicDepth) {
  99414. defines.push("#define LOGARITHMICDEPTH");
  99415. }
  99416. }
  99417. // Bones
  99418. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  99419. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  99420. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  99421. if (mesh.numBoneInfluencers > 4) {
  99422. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  99423. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  99424. }
  99425. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  99426. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  99427. }
  99428. else {
  99429. defines.push("#define NUM_BONE_INFLUENCERS 0");
  99430. }
  99431. // Instances
  99432. if (useInstances) {
  99433. defines.push("#define INSTANCES");
  99434. attribs.push("world0");
  99435. attribs.push("world1");
  99436. attribs.push("world2");
  99437. attribs.push("world3");
  99438. }
  99439. // Get correct effect
  99440. var join = defines.join("\n");
  99441. if (this._cachedDefines !== join) {
  99442. this._cachedDefines = join;
  99443. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  99444. }
  99445. return this._effect.isReady();
  99446. };
  99447. return OutlineRenderer;
  99448. }());
  99449. BABYLON.OutlineRenderer = OutlineRenderer;
  99450. })(BABYLON || (BABYLON = {}));
  99451. //# sourceMappingURL=babylon.outlineRenderer.js.map
  99452. var BABYLON;
  99453. (function (BABYLON) {
  99454. /**
  99455. * FaceAdjacencies Helper class to generate edges
  99456. */
  99457. var FaceAdjacencies = /** @class */ (function () {
  99458. function FaceAdjacencies() {
  99459. this.edges = new Array();
  99460. this.edgesConnectedCount = 0;
  99461. }
  99462. return FaceAdjacencies;
  99463. }());
  99464. /**
  99465. * This class is used to generate edges of the mesh that could then easily be rendered in a scene.
  99466. */
  99467. var EdgesRenderer = /** @class */ (function () {
  99468. /**
  99469. * Creates an instance of the EdgesRenderer. It is primarily use to display edges of a mesh.
  99470. * Beware when you use this class with complex objects as the adjacencies computation can be really long
  99471. * @param source Mesh used to create edges
  99472. * @param epsilon sum of angles in adjacency to check for edge
  99473. * @param checkVerticesInsteadOfIndices
  99474. * @param generateEdgesLines - should generate Lines or only prepare resources.
  99475. */
  99476. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices, generateEdgesLines) {
  99477. if (epsilon === void 0) { epsilon = 0.95; }
  99478. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  99479. if (generateEdgesLines === void 0) { generateEdgesLines = true; }
  99480. this.edgesWidthScalerForOrthographic = 1000.0;
  99481. this.edgesWidthScalerForPerspective = 50.0;
  99482. this._linesPositions = new Array();
  99483. this._linesNormals = new Array();
  99484. this._linesIndices = new Array();
  99485. this._buffers = {};
  99486. this._checkVerticesInsteadOfIndices = false;
  99487. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  99488. this.isEnabled = true;
  99489. this._source = source;
  99490. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  99491. this._epsilon = epsilon;
  99492. this._prepareRessources();
  99493. if (generateEdgesLines) {
  99494. this._generateEdgesLines();
  99495. }
  99496. }
  99497. EdgesRenderer.prototype._prepareRessources = function () {
  99498. if (this._lineShader) {
  99499. return;
  99500. }
  99501. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  99502. attributes: ["position", "normal"],
  99503. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  99504. });
  99505. this._lineShader.disableDepthWrite = true;
  99506. this._lineShader.backFaceCulling = false;
  99507. };
  99508. /** @hidden */
  99509. EdgesRenderer.prototype._rebuild = function () {
  99510. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  99511. if (buffer) {
  99512. buffer._rebuild();
  99513. }
  99514. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  99515. if (buffer) {
  99516. buffer._rebuild();
  99517. }
  99518. var scene = this._source.getScene();
  99519. var engine = scene.getEngine();
  99520. this._ib = engine.createIndexBuffer(this._linesIndices);
  99521. };
  99522. /**
  99523. * Releases the required resources for the edges renderer
  99524. */
  99525. EdgesRenderer.prototype.dispose = function () {
  99526. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  99527. if (buffer) {
  99528. buffer.dispose();
  99529. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  99530. }
  99531. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  99532. if (buffer) {
  99533. buffer.dispose();
  99534. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  99535. }
  99536. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  99537. this._lineShader.dispose();
  99538. };
  99539. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  99540. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  99541. return 0;
  99542. }
  99543. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  99544. return 1;
  99545. }
  99546. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  99547. return 2;
  99548. }
  99549. return -1;
  99550. };
  99551. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  99552. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  99553. return 0;
  99554. }
  99555. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  99556. return 1;
  99557. }
  99558. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  99559. return 2;
  99560. }
  99561. return -1;
  99562. };
  99563. /**
  99564. * Checks if the pair of p0 and p1 is en edge
  99565. * @param faceIndex
  99566. * @param edge
  99567. * @param faceNormals
  99568. * @param p0
  99569. * @param p1
  99570. * @private
  99571. */
  99572. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  99573. var needToCreateLine;
  99574. if (edge === undefined) {
  99575. needToCreateLine = true;
  99576. }
  99577. else {
  99578. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  99579. needToCreateLine = dotProduct < this._epsilon;
  99580. }
  99581. if (needToCreateLine) {
  99582. var offset = this._linesPositions.length / 3;
  99583. var normal = p0.subtract(p1);
  99584. normal.normalize();
  99585. // Positions
  99586. this._linesPositions.push(p0.x);
  99587. this._linesPositions.push(p0.y);
  99588. this._linesPositions.push(p0.z);
  99589. this._linesPositions.push(p0.x);
  99590. this._linesPositions.push(p0.y);
  99591. this._linesPositions.push(p0.z);
  99592. this._linesPositions.push(p1.x);
  99593. this._linesPositions.push(p1.y);
  99594. this._linesPositions.push(p1.z);
  99595. this._linesPositions.push(p1.x);
  99596. this._linesPositions.push(p1.y);
  99597. this._linesPositions.push(p1.z);
  99598. // Normals
  99599. this._linesNormals.push(p1.x);
  99600. this._linesNormals.push(p1.y);
  99601. this._linesNormals.push(p1.z);
  99602. this._linesNormals.push(-1);
  99603. this._linesNormals.push(p1.x);
  99604. this._linesNormals.push(p1.y);
  99605. this._linesNormals.push(p1.z);
  99606. this._linesNormals.push(1);
  99607. this._linesNormals.push(p0.x);
  99608. this._linesNormals.push(p0.y);
  99609. this._linesNormals.push(p0.z);
  99610. this._linesNormals.push(-1);
  99611. this._linesNormals.push(p0.x);
  99612. this._linesNormals.push(p0.y);
  99613. this._linesNormals.push(p0.z);
  99614. this._linesNormals.push(1);
  99615. // Indices
  99616. this._linesIndices.push(offset);
  99617. this._linesIndices.push(offset + 1);
  99618. this._linesIndices.push(offset + 2);
  99619. this._linesIndices.push(offset);
  99620. this._linesIndices.push(offset + 2);
  99621. this._linesIndices.push(offset + 3);
  99622. }
  99623. };
  99624. /**
  99625. * Generates lines edges from adjacencjes
  99626. * @private
  99627. */
  99628. EdgesRenderer.prototype._generateEdgesLines = function () {
  99629. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  99630. var indices = this._source.getIndices();
  99631. if (!indices || !positions) {
  99632. return;
  99633. }
  99634. // First let's find adjacencies
  99635. var adjacencies = new Array();
  99636. var faceNormals = new Array();
  99637. var index;
  99638. var faceAdjacencies;
  99639. // Prepare faces
  99640. for (index = 0; index < indices.length; index += 3) {
  99641. faceAdjacencies = new FaceAdjacencies();
  99642. var p0Index = indices[index];
  99643. var p1Index = indices[index + 1];
  99644. var p2Index = indices[index + 2];
  99645. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  99646. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  99647. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  99648. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  99649. faceNormal.normalize();
  99650. faceNormals.push(faceNormal);
  99651. adjacencies.push(faceAdjacencies);
  99652. }
  99653. // Scan
  99654. for (index = 0; index < adjacencies.length; index++) {
  99655. faceAdjacencies = adjacencies[index];
  99656. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  99657. var otherFaceAdjacencies = adjacencies[otherIndex];
  99658. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  99659. break;
  99660. }
  99661. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  99662. continue;
  99663. }
  99664. var otherP0 = indices[otherIndex * 3];
  99665. var otherP1 = indices[otherIndex * 3 + 1];
  99666. var otherP2 = indices[otherIndex * 3 + 2];
  99667. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  99668. var otherEdgeIndex = 0;
  99669. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  99670. continue;
  99671. }
  99672. switch (edgeIndex) {
  99673. case 0:
  99674. if (this._checkVerticesInsteadOfIndices) {
  99675. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  99676. }
  99677. else {
  99678. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  99679. }
  99680. break;
  99681. case 1:
  99682. if (this._checkVerticesInsteadOfIndices) {
  99683. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  99684. }
  99685. else {
  99686. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  99687. }
  99688. break;
  99689. case 2:
  99690. if (this._checkVerticesInsteadOfIndices) {
  99691. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  99692. }
  99693. else {
  99694. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  99695. }
  99696. break;
  99697. }
  99698. if (otherEdgeIndex === -1) {
  99699. continue;
  99700. }
  99701. faceAdjacencies.edges[edgeIndex] = otherIndex;
  99702. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  99703. faceAdjacencies.edgesConnectedCount++;
  99704. otherFaceAdjacencies.edgesConnectedCount++;
  99705. if (faceAdjacencies.edgesConnectedCount === 3) {
  99706. break;
  99707. }
  99708. }
  99709. }
  99710. }
  99711. // Create lines
  99712. for (index = 0; index < adjacencies.length; index++) {
  99713. // 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
  99714. var current = adjacencies[index];
  99715. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  99716. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  99717. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  99718. }
  99719. // Merge into a single mesh
  99720. var engine = this._source.getScene().getEngine();
  99721. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  99722. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  99723. this._ib = engine.createIndexBuffer(this._linesIndices);
  99724. this._indicesCount = this._linesIndices.length;
  99725. };
  99726. EdgesRenderer.prototype.render = function () {
  99727. var scene = this._source.getScene();
  99728. if (!this._lineShader.isReady() || !scene.activeCamera) {
  99729. return;
  99730. }
  99731. var engine = scene.getEngine();
  99732. this._lineShader._preBind();
  99733. if (this._source.edgesColor.a !== 1) {
  99734. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  99735. }
  99736. else {
  99737. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  99738. }
  99739. // VBOs
  99740. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  99741. scene.resetCachedMaterial();
  99742. this._lineShader.setColor4("color", this._source.edgesColor);
  99743. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  99744. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  99745. }
  99746. else {
  99747. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  99748. }
  99749. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  99750. this._lineShader.bind(this._source.getWorldMatrix());
  99751. // Draw order
  99752. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  99753. this._lineShader.unbind();
  99754. };
  99755. return EdgesRenderer;
  99756. }());
  99757. BABYLON.EdgesRenderer = EdgesRenderer;
  99758. })(BABYLON || (BABYLON = {}));
  99759. //# sourceMappingURL=babylon.edgesRenderer.js.map
  99760. var BABYLON;
  99761. (function (BABYLON) {
  99762. /**
  99763. * FaceAdjacencies Helper class to generate edges
  99764. */
  99765. var FaceAdjacencies = /** @class */ (function () {
  99766. function FaceAdjacencies() {
  99767. this.edges = new Array();
  99768. this.edgesConnectedCount = 0;
  99769. }
  99770. return FaceAdjacencies;
  99771. }());
  99772. /**
  99773. * LineEdgesRenderer for LineMeshes to remove unnecessary triangulation
  99774. */
  99775. var LineEdgesRenderer = /** @class */ (function (_super) {
  99776. __extends(LineEdgesRenderer, _super);
  99777. /**
  99778. * This constructor turns off auto generating edges line in Edges Renderer to make it here.
  99779. * @param source LineMesh used to generate edges
  99780. * @param epsilon not important (specified angle for edge detection)
  99781. * @param checkVerticesInsteadOfIndices not important for LineMesh
  99782. */
  99783. function LineEdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  99784. if (epsilon === void 0) { epsilon = 0.95; }
  99785. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  99786. var _this = _super.call(this, source, epsilon, checkVerticesInsteadOfIndices, false) || this;
  99787. _this._generateEdgesLines();
  99788. return _this;
  99789. }
  99790. /**
  99791. * Always create the edge since its a line so only important things are p0 and p1
  99792. * @param faceIndex not important for LineMesh
  99793. * @param edge not important for LineMesh
  99794. * @param faceNormals not important for LineMesh
  99795. * @param p0 beginnig of line
  99796. * @param p1 end of line
  99797. */
  99798. LineEdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  99799. var offset = this._linesPositions.length / 3;
  99800. var normal = p0.subtract(p1);
  99801. normal.normalize();
  99802. // Positions
  99803. this._linesPositions.push(p0.x);
  99804. this._linesPositions.push(p0.y);
  99805. this._linesPositions.push(p0.z);
  99806. this._linesPositions.push(p0.x);
  99807. this._linesPositions.push(p0.y);
  99808. this._linesPositions.push(p0.z);
  99809. this._linesPositions.push(p1.x);
  99810. this._linesPositions.push(p1.y);
  99811. this._linesPositions.push(p1.z);
  99812. this._linesPositions.push(p1.x);
  99813. this._linesPositions.push(p1.y);
  99814. this._linesPositions.push(p1.z);
  99815. // Normals
  99816. this._linesNormals.push(p1.x);
  99817. this._linesNormals.push(p1.y);
  99818. this._linesNormals.push(p1.z);
  99819. this._linesNormals.push(-1);
  99820. this._linesNormals.push(p1.x);
  99821. this._linesNormals.push(p1.y);
  99822. this._linesNormals.push(p1.z);
  99823. this._linesNormals.push(1);
  99824. this._linesNormals.push(p0.x);
  99825. this._linesNormals.push(p0.y);
  99826. this._linesNormals.push(p0.z);
  99827. this._linesNormals.push(-1);
  99828. this._linesNormals.push(p0.x);
  99829. this._linesNormals.push(p0.y);
  99830. this._linesNormals.push(p0.z);
  99831. this._linesNormals.push(1);
  99832. // Indices
  99833. this._linesIndices.push(offset);
  99834. this._linesIndices.push(offset + 1);
  99835. this._linesIndices.push(offset + 2);
  99836. this._linesIndices.push(offset);
  99837. this._linesIndices.push(offset + 2);
  99838. this._linesIndices.push(offset + 3);
  99839. };
  99840. /**
  99841. * Generate edges for each line in LinesMesh. Every Line should be rendered as edge.
  99842. */
  99843. LineEdgesRenderer.prototype._generateEdgesLines = function () {
  99844. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  99845. var indices = this._source.getIndices();
  99846. if (!indices || !positions) {
  99847. return;
  99848. }
  99849. // First let's find adjacencies
  99850. var adjacencies = new Array();
  99851. var faceNormals = new Array();
  99852. var index;
  99853. for (var i = 0; i < (positions.length / 3) - 1; i++) {
  99854. var currentAdjecancy = new FaceAdjacencies();
  99855. currentAdjecancy.p0 = new BABYLON.Vector3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
  99856. currentAdjecancy.p1 = new BABYLON.Vector3(positions[(i + 1) * 3], positions[(i + 1) * 3 + 1], positions[(i + 1) * 3 + 2]);
  99857. adjacencies.push(currentAdjecancy);
  99858. }
  99859. // Create lines
  99860. for (index = 0; index < adjacencies.length; index++) {
  99861. // 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
  99862. var current = adjacencies[index];
  99863. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  99864. }
  99865. // Merge into a single mesh
  99866. var engine = this._source.getScene().getEngine();
  99867. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  99868. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  99869. this._ib = engine.createIndexBuffer(this._linesIndices);
  99870. this._indicesCount = this._linesIndices.length;
  99871. };
  99872. return LineEdgesRenderer;
  99873. }(BABYLON.EdgesRenderer));
  99874. BABYLON.LineEdgesRenderer = LineEdgesRenderer;
  99875. })(BABYLON || (BABYLON = {}));
  99876. //# sourceMappingURL=babylon.lineEdgesRenderer.js.map
  99877. var BABYLON;
  99878. (function (BABYLON) {
  99879. // Adds the parser to the scene parsers.
  99880. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  99881. if (parsedData.effectLayers) {
  99882. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  99883. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  99884. container.effectLayers.push(effectLayer);
  99885. }
  99886. }
  99887. });
  99888. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  99889. var index = this.effectLayers.indexOf(toRemove);
  99890. if (index !== -1) {
  99891. this.effectLayers.splice(index, 1);
  99892. }
  99893. return index;
  99894. };
  99895. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  99896. this.effectLayers.push(newEffectLayer);
  99897. };
  99898. /**
  99899. * Defines the layer scene component responsible to manage any effect layers
  99900. * in a given scene.
  99901. */
  99902. var EffectLayerSceneComponent = /** @class */ (function () {
  99903. /**
  99904. * Creates a new instance of the component for the given scene
  99905. * @param scene Defines the scene to register the component in
  99906. */
  99907. function EffectLayerSceneComponent(scene) {
  99908. /**
  99909. * The component name helpfull to identify the component in the list of scene components.
  99910. */
  99911. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  99912. this._renderEffects = false;
  99913. this._needStencil = false;
  99914. this._previousStencilState = false;
  99915. this.scene = scene;
  99916. this._engine = scene.getEngine();
  99917. scene.effectLayers = new Array();
  99918. }
  99919. /**
  99920. * Registers the component in a given scene
  99921. */
  99922. EffectLayerSceneComponent.prototype.register = function () {
  99923. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  99924. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  99925. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  99926. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  99927. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  99928. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  99929. };
  99930. /**
  99931. * Rebuilds the elements related to this component in case of
  99932. * context lost for instance.
  99933. */
  99934. EffectLayerSceneComponent.prototype.rebuild = function () {
  99935. var layers = this.scene.effectLayers;
  99936. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  99937. var effectLayer = layers_1[_i];
  99938. effectLayer._rebuild();
  99939. }
  99940. };
  99941. /**
  99942. * Serializes the component data to the specified json object
  99943. * @param serializationObject The object to serialize to
  99944. */
  99945. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  99946. // Effect layers
  99947. serializationObject.effectLayers = [];
  99948. var layers = this.scene.effectLayers;
  99949. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  99950. var effectLayer = layers_2[_i];
  99951. if (effectLayer.serialize) {
  99952. serializationObject.effectLayers.push(effectLayer.serialize());
  99953. }
  99954. }
  99955. };
  99956. /**
  99957. * Adds all the element from the container to the scene
  99958. * @param container the container holding the elements
  99959. */
  99960. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  99961. var _this = this;
  99962. if (!container.effectLayers) {
  99963. return;
  99964. }
  99965. container.effectLayers.forEach(function (o) {
  99966. _this.scene.addEffectLayer(o);
  99967. });
  99968. };
  99969. /**
  99970. * Removes all the elements in the container from the scene
  99971. * @param container contains the elements to remove
  99972. */
  99973. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  99974. var _this = this;
  99975. if (!container.effectLayers) {
  99976. return;
  99977. }
  99978. container.effectLayers.forEach(function (o) {
  99979. _this.scene.removeEffectLayer(o);
  99980. });
  99981. };
  99982. /**
  99983. * Disposes the component and the associated ressources.
  99984. */
  99985. EffectLayerSceneComponent.prototype.dispose = function () {
  99986. var layers = this.scene.effectLayers;
  99987. while (layers.length) {
  99988. layers[0].dispose();
  99989. }
  99990. };
  99991. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  99992. var layers = this.scene.effectLayers;
  99993. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  99994. var layer = layers_3[_i];
  99995. if (!layer.hasMesh(mesh)) {
  99996. continue;
  99997. }
  99998. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  99999. var subMesh = _b[_a];
  100000. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  100001. return false;
  100002. }
  100003. }
  100004. }
  100005. return true;
  100006. };
  100007. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  100008. this._renderEffects = false;
  100009. this._needStencil = false;
  100010. var layers = this.scene.effectLayers;
  100011. if (layers && layers.length > 0) {
  100012. this._previousStencilState = this._engine.getStencilBuffer();
  100013. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  100014. var effectLayer = layers_4[_i];
  100015. if (effectLayer.shouldRender() &&
  100016. (!effectLayer.camera ||
  100017. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  100018. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  100019. this._renderEffects = true;
  100020. this._needStencil = this._needStencil || effectLayer.needStencil();
  100021. var renderTarget = effectLayer._mainTexture;
  100022. if (renderTarget._shouldRender()) {
  100023. this.scene.incrementRenderId();
  100024. renderTarget.render(false, false);
  100025. }
  100026. }
  100027. }
  100028. this.scene.incrementRenderId();
  100029. }
  100030. };
  100031. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  100032. // Activate effect Layer stencil
  100033. if (this._needStencil) {
  100034. this._engine.setStencilBuffer(true);
  100035. }
  100036. };
  100037. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  100038. // Restore effect Layer stencil
  100039. if (this._needStencil) {
  100040. this._engine.setStencilBuffer(this._previousStencilState);
  100041. }
  100042. };
  100043. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  100044. if (this._renderEffects) {
  100045. this._engine.setDepthBuffer(false);
  100046. var layers = this.scene.effectLayers;
  100047. for (var i = 0; i < layers.length; i++) {
  100048. var effectLayer = layers[i];
  100049. if (effectLayer.renderingGroupId === renderingGroupId) {
  100050. if (effectLayer.shouldRender()) {
  100051. effectLayer.render();
  100052. }
  100053. }
  100054. }
  100055. this._engine.setDepthBuffer(true);
  100056. }
  100057. };
  100058. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  100059. if (this._renderEffects) {
  100060. this._draw(-1);
  100061. }
  100062. };
  100063. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  100064. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  100065. this._draw(index);
  100066. }
  100067. };
  100068. return EffectLayerSceneComponent;
  100069. }());
  100070. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  100071. })(BABYLON || (BABYLON = {}));
  100072. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  100073. var __assign = (this && this.__assign) || function () {
  100074. __assign = Object.assign || function(t) {
  100075. for (var s, i = 1, n = arguments.length; i < n; i++) {
  100076. s = arguments[i];
  100077. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  100078. t[p] = s[p];
  100079. }
  100080. return t;
  100081. };
  100082. return __assign.apply(this, arguments);
  100083. };
  100084. var BABYLON;
  100085. (function (BABYLON) {
  100086. /**
  100087. * The effect layer Helps adding post process effect blended with the main pass.
  100088. *
  100089. * This can be for instance use to generate glow or higlight effects on the scene.
  100090. *
  100091. * The effect layer class can not be used directly and is intented to inherited from to be
  100092. * customized per effects.
  100093. */
  100094. var EffectLayer = /** @class */ (function () {
  100095. /**
  100096. * Instantiates a new effect Layer and references it in the scene.
  100097. * @param name The name of the layer
  100098. * @param scene The scene to use the layer in
  100099. */
  100100. function EffectLayer(
  100101. /** The Friendly of the effect in the scene */
  100102. name, scene) {
  100103. this._vertexBuffers = {};
  100104. this._maxSize = 0;
  100105. this._mainTextureDesiredSize = { width: 0, height: 0 };
  100106. this._shouldRender = true;
  100107. this._postProcesses = [];
  100108. this._textures = [];
  100109. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  100110. /**
  100111. * The clear color of the texture used to generate the glow map.
  100112. */
  100113. this.neutralColor = new BABYLON.Color4();
  100114. /**
  100115. * Specifies wether the highlight layer is enabled or not.
  100116. */
  100117. this.isEnabled = true;
  100118. /**
  100119. * An event triggered when the effect layer has been disposed.
  100120. */
  100121. this.onDisposeObservable = new BABYLON.Observable();
  100122. /**
  100123. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  100124. */
  100125. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  100126. /**
  100127. * An event triggered when the generated texture is being merged in the scene.
  100128. */
  100129. this.onBeforeComposeObservable = new BABYLON.Observable();
  100130. /**
  100131. * An event triggered when the generated texture has been merged in the scene.
  100132. */
  100133. this.onAfterComposeObservable = new BABYLON.Observable();
  100134. /**
  100135. * An event triggered when the efffect layer changes its size.
  100136. */
  100137. this.onSizeChangedObservable = new BABYLON.Observable();
  100138. this.name = name;
  100139. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  100140. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  100141. if (!component) {
  100142. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  100143. this._scene._addComponent(component);
  100144. }
  100145. this._engine = this._scene.getEngine();
  100146. this._maxSize = this._engine.getCaps().maxTextureSize;
  100147. this._scene.effectLayers.push(this);
  100148. // Generate Buffers
  100149. this._generateIndexBuffer();
  100150. this._genrateVertexBuffer();
  100151. }
  100152. Object.defineProperty(EffectLayer.prototype, "camera", {
  100153. /**
  100154. * Gets the camera attached to the layer.
  100155. */
  100156. get: function () {
  100157. return this._effectLayerOptions.camera;
  100158. },
  100159. enumerable: true,
  100160. configurable: true
  100161. });
  100162. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  100163. /**
  100164. * Gets the rendering group id the layer should render in.
  100165. */
  100166. get: function () {
  100167. return this._effectLayerOptions.renderingGroupId;
  100168. },
  100169. enumerable: true,
  100170. configurable: true
  100171. });
  100172. /**
  100173. * Initializes the effect layer with the required options.
  100174. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  100175. */
  100176. EffectLayer.prototype._init = function (options) {
  100177. // Adapt options
  100178. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  100179. this._setMainTextureSize();
  100180. this._createMainTexture();
  100181. this._createTextureAndPostProcesses();
  100182. this._mergeEffect = this._createMergeEffect();
  100183. };
  100184. /**
  100185. * Generates the index buffer of the full screen quad blending to the main canvas.
  100186. */
  100187. EffectLayer.prototype._generateIndexBuffer = function () {
  100188. // Indices
  100189. var indices = [];
  100190. indices.push(0);
  100191. indices.push(1);
  100192. indices.push(2);
  100193. indices.push(0);
  100194. indices.push(2);
  100195. indices.push(3);
  100196. this._indexBuffer = this._engine.createIndexBuffer(indices);
  100197. };
  100198. /**
  100199. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  100200. */
  100201. EffectLayer.prototype._genrateVertexBuffer = function () {
  100202. // VBO
  100203. var vertices = [];
  100204. vertices.push(1, 1);
  100205. vertices.push(-1, 1);
  100206. vertices.push(-1, -1);
  100207. vertices.push(1, -1);
  100208. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  100209. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  100210. };
  100211. /**
  100212. * Sets the main texture desired size which is the closest power of two
  100213. * of the engine canvas size.
  100214. */
  100215. EffectLayer.prototype._setMainTextureSize = function () {
  100216. if (this._effectLayerOptions.mainTextureFixedSize) {
  100217. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  100218. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  100219. }
  100220. else {
  100221. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  100222. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  100223. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  100224. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  100225. }
  100226. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  100227. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  100228. };
  100229. /**
  100230. * Creates the main texture for the effect layer.
  100231. */
  100232. EffectLayer.prototype._createMainTexture = function () {
  100233. var _this = this;
  100234. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  100235. width: this._mainTextureDesiredSize.width,
  100236. height: this._mainTextureDesiredSize.height
  100237. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  100238. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  100239. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100240. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100241. this._mainTexture.anisotropicFilteringLevel = 1;
  100242. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  100243. this._mainTexture.renderParticles = false;
  100244. this._mainTexture.renderList = null;
  100245. this._mainTexture.ignoreCameraViewport = true;
  100246. // Custom render function
  100247. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  100248. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  100249. var index;
  100250. var engine = _this._scene.getEngine();
  100251. if (depthOnlySubMeshes.length) {
  100252. engine.setColorWrite(false);
  100253. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  100254. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  100255. }
  100256. engine.setColorWrite(true);
  100257. }
  100258. for (index = 0; index < opaqueSubMeshes.length; index++) {
  100259. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  100260. }
  100261. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  100262. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  100263. }
  100264. for (index = 0; index < transparentSubMeshes.length; index++) {
  100265. _this._renderSubMesh(transparentSubMeshes.data[index]);
  100266. }
  100267. };
  100268. this._mainTexture.onClearObservable.add(function (engine) {
  100269. engine.clear(_this.neutralColor, true, true, true);
  100270. });
  100271. };
  100272. /**
  100273. * Checks for the readiness of the element composing the layer.
  100274. * @param subMesh the mesh to check for
  100275. * @param useInstances specify wether or not to use instances to render the mesh
  100276. * @param emissiveTexture the associated emissive texture used to generate the glow
  100277. * @return true if ready otherwise, false
  100278. */
  100279. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  100280. var material = subMesh.getMaterial();
  100281. if (!material) {
  100282. return false;
  100283. }
  100284. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  100285. return false;
  100286. }
  100287. var defines = [];
  100288. var attribs = [BABYLON.VertexBuffer.PositionKind];
  100289. var mesh = subMesh.getMesh();
  100290. var uv1 = false;
  100291. var uv2 = false;
  100292. // Alpha test
  100293. if (material && material.needAlphaTesting()) {
  100294. var alphaTexture = material.getAlphaTestTexture();
  100295. if (alphaTexture) {
  100296. defines.push("#define ALPHATEST");
  100297. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  100298. alphaTexture.coordinatesIndex === 1) {
  100299. defines.push("#define DIFFUSEUV2");
  100300. uv2 = true;
  100301. }
  100302. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  100303. defines.push("#define DIFFUSEUV1");
  100304. uv1 = true;
  100305. }
  100306. }
  100307. }
  100308. // Emissive
  100309. if (emissiveTexture) {
  100310. defines.push("#define EMISSIVE");
  100311. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  100312. emissiveTexture.coordinatesIndex === 1) {
  100313. defines.push("#define EMISSIVEUV2");
  100314. uv2 = true;
  100315. }
  100316. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  100317. defines.push("#define EMISSIVEUV1");
  100318. uv1 = true;
  100319. }
  100320. }
  100321. if (uv1) {
  100322. attribs.push(BABYLON.VertexBuffer.UVKind);
  100323. defines.push("#define UV1");
  100324. }
  100325. if (uv2) {
  100326. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  100327. defines.push("#define UV2");
  100328. }
  100329. // Bones
  100330. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  100331. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  100332. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  100333. if (mesh.numBoneInfluencers > 4) {
  100334. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  100335. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  100336. }
  100337. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  100338. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  100339. }
  100340. else {
  100341. defines.push("#define NUM_BONE_INFLUENCERS 0");
  100342. }
  100343. // Morph targets
  100344. var manager = mesh.morphTargetManager;
  100345. var morphInfluencers = 0;
  100346. if (manager) {
  100347. if (manager.numInfluencers > 0) {
  100348. defines.push("#define MORPHTARGETS");
  100349. morphInfluencers = manager.numInfluencers;
  100350. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  100351. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  100352. }
  100353. }
  100354. // Instances
  100355. if (useInstances) {
  100356. defines.push("#define INSTANCES");
  100357. attribs.push("world0");
  100358. attribs.push("world1");
  100359. attribs.push("world2");
  100360. attribs.push("world3");
  100361. }
  100362. // Get correct effect
  100363. var join = defines.join("\n");
  100364. if (this._cachedDefines !== join) {
  100365. this._cachedDefines = join;
  100366. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  100367. }
  100368. return this._effectLayerMapGenerationEffect.isReady();
  100369. };
  100370. /**
  100371. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  100372. */
  100373. EffectLayer.prototype.render = function () {
  100374. var currentEffect = this._mergeEffect;
  100375. // Check
  100376. if (!currentEffect.isReady())
  100377. return;
  100378. for (var i = 0; i < this._postProcesses.length; i++) {
  100379. if (!this._postProcesses[i].isReady()) {
  100380. return;
  100381. }
  100382. }
  100383. var engine = this._scene.getEngine();
  100384. this.onBeforeComposeObservable.notifyObservers(this);
  100385. // Render
  100386. engine.enableEffect(currentEffect);
  100387. engine.setState(false);
  100388. // VBOs
  100389. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  100390. // Cache
  100391. var previousAlphaMode = engine.getAlphaMode();
  100392. // Go Blend.
  100393. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  100394. // Blends the map on the main canvas.
  100395. this._internalRender(currentEffect);
  100396. // Restore Alpha
  100397. engine.setAlphaMode(previousAlphaMode);
  100398. this.onAfterComposeObservable.notifyObservers(this);
  100399. // Handle size changes.
  100400. var size = this._mainTexture.getSize();
  100401. this._setMainTextureSize();
  100402. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  100403. // Recreate RTT and post processes on size change.
  100404. this.onSizeChangedObservable.notifyObservers(this);
  100405. this._disposeTextureAndPostProcesses();
  100406. this._createMainTexture();
  100407. this._createTextureAndPostProcesses();
  100408. }
  100409. };
  100410. /**
  100411. * Determine if a given mesh will be used in the current effect.
  100412. * @param mesh mesh to test
  100413. * @returns true if the mesh will be used
  100414. */
  100415. EffectLayer.prototype.hasMesh = function (mesh) {
  100416. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  100417. return true;
  100418. }
  100419. return false;
  100420. };
  100421. /**
  100422. * Returns true if the layer contains information to display, otherwise false.
  100423. * @returns true if the glow layer should be rendered
  100424. */
  100425. EffectLayer.prototype.shouldRender = function () {
  100426. return this.isEnabled && this._shouldRender;
  100427. };
  100428. /**
  100429. * Returns true if the mesh should render, otherwise false.
  100430. * @param mesh The mesh to render
  100431. * @returns true if it should render otherwise false
  100432. */
  100433. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  100434. return true;
  100435. };
  100436. /**
  100437. * Returns true if the mesh should render, otherwise false.
  100438. * @param mesh The mesh to render
  100439. * @returns true if it should render otherwise false
  100440. */
  100441. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  100442. return true;
  100443. };
  100444. /**
  100445. * Renders the submesh passed in parameter to the generation map.
  100446. */
  100447. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  100448. var _this = this;
  100449. if (!this.shouldRender()) {
  100450. return;
  100451. }
  100452. var material = subMesh.getMaterial();
  100453. var mesh = subMesh.getRenderingMesh();
  100454. var scene = this._scene;
  100455. var engine = scene.getEngine();
  100456. if (!material) {
  100457. return;
  100458. }
  100459. // Do not block in blend mode.
  100460. if (material.needAlphaBlendingForMesh(mesh)) {
  100461. return;
  100462. }
  100463. // Culling
  100464. engine.setState(material.backFaceCulling);
  100465. // Managing instances
  100466. var batch = mesh._getInstancesRenderList(subMesh._id);
  100467. if (batch.mustReturn) {
  100468. return;
  100469. }
  100470. // Early Exit per mesh
  100471. if (!this._shouldRenderMesh(mesh)) {
  100472. return;
  100473. }
  100474. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  100475. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  100476. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  100477. engine.enableEffect(this._effectLayerMapGenerationEffect);
  100478. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  100479. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  100480. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  100481. // Alpha test
  100482. if (material && material.needAlphaTesting()) {
  100483. var alphaTexture = material.getAlphaTestTexture();
  100484. if (alphaTexture) {
  100485. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  100486. var textureMatrix = alphaTexture.getTextureMatrix();
  100487. if (textureMatrix) {
  100488. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  100489. }
  100490. }
  100491. }
  100492. // Glow emissive only
  100493. if (this._emissiveTextureAndColor.texture) {
  100494. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  100495. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  100496. }
  100497. // Bones
  100498. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  100499. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  100500. }
  100501. // Morph targets
  100502. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  100503. // Draw
  100504. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  100505. }
  100506. else {
  100507. // Need to reset refresh rate of the main map
  100508. this._mainTexture.resetRefreshCounter();
  100509. }
  100510. };
  100511. /**
  100512. * Rebuild the required buffers.
  100513. * @hidden Internal use only.
  100514. */
  100515. EffectLayer.prototype._rebuild = function () {
  100516. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  100517. if (vb) {
  100518. vb._rebuild();
  100519. }
  100520. this._generateIndexBuffer();
  100521. };
  100522. /**
  100523. * Dispose only the render target textures and post process.
  100524. */
  100525. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  100526. this._mainTexture.dispose();
  100527. for (var i = 0; i < this._postProcesses.length; i++) {
  100528. if (this._postProcesses[i]) {
  100529. this._postProcesses[i].dispose();
  100530. }
  100531. }
  100532. this._postProcesses = [];
  100533. for (var i = 0; i < this._textures.length; i++) {
  100534. if (this._textures[i]) {
  100535. this._textures[i].dispose();
  100536. }
  100537. }
  100538. this._textures = [];
  100539. };
  100540. /**
  100541. * Dispose the highlight layer and free resources.
  100542. */
  100543. EffectLayer.prototype.dispose = function () {
  100544. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  100545. if (vertexBuffer) {
  100546. vertexBuffer.dispose();
  100547. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  100548. }
  100549. if (this._indexBuffer) {
  100550. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  100551. this._indexBuffer = null;
  100552. }
  100553. // Clean textures and post processes
  100554. this._disposeTextureAndPostProcesses();
  100555. // Remove from scene
  100556. var index = this._scene.effectLayers.indexOf(this, 0);
  100557. if (index > -1) {
  100558. this._scene.effectLayers.splice(index, 1);
  100559. }
  100560. // Callback
  100561. this.onDisposeObservable.notifyObservers(this);
  100562. this.onDisposeObservable.clear();
  100563. this.onBeforeRenderMainTextureObservable.clear();
  100564. this.onBeforeComposeObservable.clear();
  100565. this.onAfterComposeObservable.clear();
  100566. this.onSizeChangedObservable.clear();
  100567. };
  100568. /**
  100569. * Gets the class name of the effect layer
  100570. * @returns the string with the class name of the effect layer
  100571. */
  100572. EffectLayer.prototype.getClassName = function () {
  100573. return "EffectLayer";
  100574. };
  100575. /**
  100576. * Creates an effect layer from parsed effect layer data
  100577. * @param parsedEffectLayer defines effect layer data
  100578. * @param scene defines the current scene
  100579. * @param rootUrl defines the root URL containing the effect layer information
  100580. * @returns a parsed effect Layer
  100581. */
  100582. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  100583. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  100584. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  100585. };
  100586. __decorate([
  100587. BABYLON.serialize()
  100588. ], EffectLayer.prototype, "name", void 0);
  100589. __decorate([
  100590. BABYLON.serializeAsColor4()
  100591. ], EffectLayer.prototype, "neutralColor", void 0);
  100592. __decorate([
  100593. BABYLON.serialize()
  100594. ], EffectLayer.prototype, "isEnabled", void 0);
  100595. __decorate([
  100596. BABYLON.serializeAsCameraReference()
  100597. ], EffectLayer.prototype, "camera", null);
  100598. __decorate([
  100599. BABYLON.serialize()
  100600. ], EffectLayer.prototype, "renderingGroupId", null);
  100601. return EffectLayer;
  100602. }());
  100603. BABYLON.EffectLayer = EffectLayer;
  100604. })(BABYLON || (BABYLON = {}));
  100605. //# sourceMappingURL=babylon.effectLayer.js.map
  100606. var BABYLON;
  100607. (function (BABYLON) {
  100608. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  100609. for (var index = 0; index < this.effectLayers.length; index++) {
  100610. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  100611. return this.effectLayers[index];
  100612. }
  100613. }
  100614. return null;
  100615. };
  100616. /**
  100617. * Special Glow Blur post process only blurring the alpha channel
  100618. * It enforces keeping the most luminous color in the color channel.
  100619. */
  100620. var GlowBlurPostProcess = /** @class */ (function (_super) {
  100621. __extends(GlowBlurPostProcess, _super);
  100622. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  100623. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  100624. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  100625. _this.direction = direction;
  100626. _this.kernel = kernel;
  100627. _this.onApplyObservable.add(function (effect) {
  100628. effect.setFloat2("screenSize", _this.width, _this.height);
  100629. effect.setVector2("direction", _this.direction);
  100630. effect.setFloat("blurWidth", _this.kernel);
  100631. });
  100632. return _this;
  100633. }
  100634. return GlowBlurPostProcess;
  100635. }(BABYLON.PostProcess));
  100636. /**
  100637. * The highlight layer Helps adding a glow effect around a mesh.
  100638. *
  100639. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  100640. * glowy meshes to your scene.
  100641. *
  100642. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  100643. */
  100644. var HighlightLayer = /** @class */ (function (_super) {
  100645. __extends(HighlightLayer, _super);
  100646. /**
  100647. * Instantiates a new highlight Layer and references it to the scene..
  100648. * @param name The name of the layer
  100649. * @param scene The scene to use the layer in
  100650. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  100651. */
  100652. function HighlightLayer(name, scene, options) {
  100653. var _this = _super.call(this, name, scene) || this;
  100654. _this.name = name;
  100655. /**
  100656. * Specifies whether or not the inner glow is ACTIVE in the layer.
  100657. */
  100658. _this.innerGlow = true;
  100659. /**
  100660. * Specifies whether or not the outer glow is ACTIVE in the layer.
  100661. */
  100662. _this.outerGlow = true;
  100663. /**
  100664. * An event triggered when the highlight layer is being blurred.
  100665. */
  100666. _this.onBeforeBlurObservable = new BABYLON.Observable();
  100667. /**
  100668. * An event triggered when the highlight layer has been blurred.
  100669. */
  100670. _this.onAfterBlurObservable = new BABYLON.Observable();
  100671. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  100672. _this._meshes = {};
  100673. _this._excludedMeshes = {};
  100674. _this.neutralColor = HighlightLayer.NeutralColor;
  100675. // Warn on stencil
  100676. if (!_this._engine.isStencilEnable) {
  100677. 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 }");
  100678. }
  100679. // Adapt options
  100680. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  100681. // Initialize the layer
  100682. _this._init({
  100683. alphaBlendingMode: _this._options.alphaBlendingMode,
  100684. camera: _this._options.camera,
  100685. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  100686. mainTextureRatio: _this._options.mainTextureRatio,
  100687. renderingGroupId: _this._options.renderingGroupId
  100688. });
  100689. // Do not render as long as no meshes have been added
  100690. _this._shouldRender = false;
  100691. return _this;
  100692. }
  100693. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  100694. /**
  100695. * Gets the horizontal size of the blur.
  100696. */
  100697. get: function () {
  100698. return this._horizontalBlurPostprocess.kernel;
  100699. },
  100700. /**
  100701. * Specifies the horizontal size of the blur.
  100702. */
  100703. set: function (value) {
  100704. this._horizontalBlurPostprocess.kernel = value;
  100705. },
  100706. enumerable: true,
  100707. configurable: true
  100708. });
  100709. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  100710. /**
  100711. * Gets the vertical size of the blur.
  100712. */
  100713. get: function () {
  100714. return this._verticalBlurPostprocess.kernel;
  100715. },
  100716. /**
  100717. * Specifies the vertical size of the blur.
  100718. */
  100719. set: function (value) {
  100720. this._verticalBlurPostprocess.kernel = value;
  100721. },
  100722. enumerable: true,
  100723. configurable: true
  100724. });
  100725. /**
  100726. * Get the effect name of the layer.
  100727. * @return The effect name
  100728. */
  100729. HighlightLayer.prototype.getEffectName = function () {
  100730. return HighlightLayer.EffectName;
  100731. };
  100732. /**
  100733. * Create the merge effect. This is the shader use to blit the information back
  100734. * to the main canvas at the end of the scene rendering.
  100735. */
  100736. HighlightLayer.prototype._createMergeEffect = function () {
  100737. // Effect
  100738. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  100739. };
  100740. /**
  100741. * Creates the render target textures and post processes used in the highlight layer.
  100742. */
  100743. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  100744. var _this = this;
  100745. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  100746. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  100747. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  100748. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  100749. var textureType = 0;
  100750. if (this._engine.getCaps().textureHalfFloatRender) {
  100751. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  100752. }
  100753. else {
  100754. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  100755. }
  100756. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  100757. width: blurTextureWidth,
  100758. height: blurTextureHeight
  100759. }, this._scene, false, true, textureType);
  100760. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100761. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100762. this._blurTexture.anisotropicFilteringLevel = 16;
  100763. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  100764. this._blurTexture.renderParticles = false;
  100765. this._blurTexture.ignoreCameraViewport = true;
  100766. this._textures = [this._blurTexture];
  100767. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  100768. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  100769. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  100770. effect.setTexture("textureSampler", _this._mainTexture);
  100771. });
  100772. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  100773. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  100774. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  100775. });
  100776. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  100777. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  100778. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  100779. });
  100780. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  100781. }
  100782. else {
  100783. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  100784. width: blurTextureWidth,
  100785. height: blurTextureHeight
  100786. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  100787. this._horizontalBlurPostprocess.width = blurTextureWidth;
  100788. this._horizontalBlurPostprocess.height = blurTextureHeight;
  100789. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  100790. effect.setTexture("textureSampler", _this._mainTexture);
  100791. });
  100792. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  100793. width: blurTextureWidth,
  100794. height: blurTextureHeight
  100795. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  100796. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  100797. }
  100798. this._mainTexture.onAfterUnbindObservable.add(function () {
  100799. _this.onBeforeBlurObservable.notifyObservers(_this);
  100800. var internalTexture = _this._blurTexture.getInternalTexture();
  100801. if (internalTexture) {
  100802. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  100803. }
  100804. _this.onAfterBlurObservable.notifyObservers(_this);
  100805. });
  100806. // Prevent autoClear.
  100807. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  100808. };
  100809. /**
  100810. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  100811. */
  100812. HighlightLayer.prototype.needStencil = function () {
  100813. return true;
  100814. };
  100815. /**
  100816. * Checks for the readiness of the element composing the layer.
  100817. * @param subMesh the mesh to check for
  100818. * @param useInstances specify wether or not to use instances to render the mesh
  100819. * @param emissiveTexture the associated emissive texture used to generate the glow
  100820. * @return true if ready otherwise, false
  100821. */
  100822. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  100823. var material = subMesh.getMaterial();
  100824. var mesh = subMesh.getRenderingMesh();
  100825. if (!material || !mesh || !this._meshes) {
  100826. return false;
  100827. }
  100828. var emissiveTexture = null;
  100829. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  100830. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  100831. emissiveTexture = material.emissiveTexture;
  100832. }
  100833. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  100834. };
  100835. /**
  100836. * Implementation specific of rendering the generating effect on the main canvas.
  100837. * @param effect The effect used to render through
  100838. */
  100839. HighlightLayer.prototype._internalRender = function (effect) {
  100840. // Texture
  100841. effect.setTexture("textureSampler", this._blurTexture);
  100842. // Cache
  100843. var engine = this._engine;
  100844. var previousStencilBuffer = engine.getStencilBuffer();
  100845. var previousStencilFunction = engine.getStencilFunction();
  100846. var previousStencilMask = engine.getStencilMask();
  100847. var previousStencilOperationPass = engine.getStencilOperationPass();
  100848. var previousStencilOperationFail = engine.getStencilOperationFail();
  100849. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  100850. var previousStencilReference = engine.getStencilFunctionReference();
  100851. // Stencil operations
  100852. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  100853. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  100854. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  100855. // Draw order
  100856. engine.setStencilMask(0x00);
  100857. engine.setStencilBuffer(true);
  100858. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  100859. // 2 passes inner outer
  100860. if (this.outerGlow) {
  100861. effect.setFloat("offset", 0);
  100862. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  100863. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  100864. }
  100865. if (this.innerGlow) {
  100866. effect.setFloat("offset", 1);
  100867. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  100868. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  100869. }
  100870. // Restore Cache
  100871. engine.setStencilFunction(previousStencilFunction);
  100872. engine.setStencilMask(previousStencilMask);
  100873. engine.setStencilBuffer(previousStencilBuffer);
  100874. engine.setStencilOperationPass(previousStencilOperationPass);
  100875. engine.setStencilOperationFail(previousStencilOperationFail);
  100876. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  100877. engine.setStencilFunctionReference(previousStencilReference);
  100878. };
  100879. /**
  100880. * Returns true if the layer contains information to display, otherwise false.
  100881. */
  100882. HighlightLayer.prototype.shouldRender = function () {
  100883. if (_super.prototype.shouldRender.call(this)) {
  100884. return this._meshes ? true : false;
  100885. }
  100886. return false;
  100887. };
  100888. /**
  100889. * Returns true if the mesh should render, otherwise false.
  100890. * @param mesh The mesh to render
  100891. * @returns true if it should render otherwise false
  100892. */
  100893. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  100894. // Excluded Mesh
  100895. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  100896. return false;
  100897. }
  100898. ;
  100899. if (!_super.prototype.hasMesh.call(this, mesh)) {
  100900. return false;
  100901. }
  100902. return true;
  100903. };
  100904. /**
  100905. * Sets the required values for both the emissive texture and and the main color.
  100906. */
  100907. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  100908. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  100909. if (highlightLayerMesh) {
  100910. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  100911. }
  100912. else {
  100913. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  100914. }
  100915. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  100916. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  100917. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  100918. }
  100919. else {
  100920. this._emissiveTextureAndColor.texture = null;
  100921. }
  100922. };
  100923. /**
  100924. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  100925. * @param mesh The mesh to exclude from the highlight layer
  100926. */
  100927. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  100928. if (!this._excludedMeshes) {
  100929. return;
  100930. }
  100931. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  100932. if (!meshExcluded) {
  100933. this._excludedMeshes[mesh.uniqueId] = {
  100934. mesh: mesh,
  100935. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  100936. mesh.getEngine().setStencilBuffer(false);
  100937. }),
  100938. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  100939. mesh.getEngine().setStencilBuffer(true);
  100940. }),
  100941. };
  100942. }
  100943. };
  100944. /**
  100945. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  100946. * @param mesh The mesh to highlight
  100947. */
  100948. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  100949. if (!this._excludedMeshes) {
  100950. return;
  100951. }
  100952. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  100953. if (meshExcluded) {
  100954. if (meshExcluded.beforeRender) {
  100955. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  100956. }
  100957. if (meshExcluded.afterRender) {
  100958. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  100959. }
  100960. }
  100961. this._excludedMeshes[mesh.uniqueId] = null;
  100962. };
  100963. /**
  100964. * Determine if a given mesh will be highlighted by the current HighlightLayer
  100965. * @param mesh mesh to test
  100966. * @returns true if the mesh will be highlighted by the current HighlightLayer
  100967. */
  100968. HighlightLayer.prototype.hasMesh = function (mesh) {
  100969. if (!this._meshes) {
  100970. return false;
  100971. }
  100972. if (!_super.prototype.hasMesh.call(this, mesh)) {
  100973. return false;
  100974. }
  100975. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  100976. };
  100977. /**
  100978. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  100979. * @param mesh The mesh to highlight
  100980. * @param color The color of the highlight
  100981. * @param glowEmissiveOnly Extract the glow from the emissive texture
  100982. */
  100983. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  100984. var _this = this;
  100985. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  100986. if (!this._meshes) {
  100987. return;
  100988. }
  100989. var meshHighlight = this._meshes[mesh.uniqueId];
  100990. if (meshHighlight) {
  100991. meshHighlight.color = color;
  100992. }
  100993. else {
  100994. this._meshes[mesh.uniqueId] = {
  100995. mesh: mesh,
  100996. color: color,
  100997. // Lambda required for capture due to Observable this context
  100998. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  100999. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  101000. _this._defaultStencilReference(mesh);
  101001. }
  101002. else {
  101003. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  101004. }
  101005. }),
  101006. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  101007. glowEmissiveOnly: glowEmissiveOnly
  101008. };
  101009. mesh.onDisposeObservable.add(function () {
  101010. _this._disposeMesh(mesh);
  101011. });
  101012. }
  101013. this._shouldRender = true;
  101014. };
  101015. /**
  101016. * Remove a mesh from the highlight layer in order to make it stop glowing.
  101017. * @param mesh The mesh to highlight
  101018. */
  101019. HighlightLayer.prototype.removeMesh = function (mesh) {
  101020. if (!this._meshes) {
  101021. return;
  101022. }
  101023. var meshHighlight = this._meshes[mesh.uniqueId];
  101024. if (meshHighlight) {
  101025. if (meshHighlight.observerHighlight) {
  101026. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  101027. }
  101028. if (meshHighlight.observerDefault) {
  101029. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  101030. }
  101031. delete this._meshes[mesh.uniqueId];
  101032. }
  101033. this._shouldRender = false;
  101034. for (var meshHighlightToCheck in this._meshes) {
  101035. if (this._meshes[meshHighlightToCheck]) {
  101036. this._shouldRender = true;
  101037. break;
  101038. }
  101039. }
  101040. };
  101041. /**
  101042. * Force the stencil to the normal expected value for none glowing parts
  101043. */
  101044. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  101045. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  101046. };
  101047. /**
  101048. * Free any resources and references associated to a mesh.
  101049. * Internal use
  101050. * @param mesh The mesh to free.
  101051. * @hidden
  101052. */
  101053. HighlightLayer.prototype._disposeMesh = function (mesh) {
  101054. this.removeMesh(mesh);
  101055. this.removeExcludedMesh(mesh);
  101056. };
  101057. /**
  101058. * Dispose the highlight layer and free resources.
  101059. */
  101060. HighlightLayer.prototype.dispose = function () {
  101061. if (this._meshes) {
  101062. // Clean mesh references
  101063. for (var id in this._meshes) {
  101064. var meshHighlight = this._meshes[id];
  101065. if (meshHighlight && meshHighlight.mesh) {
  101066. if (meshHighlight.observerHighlight) {
  101067. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  101068. }
  101069. if (meshHighlight.observerDefault) {
  101070. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  101071. }
  101072. }
  101073. }
  101074. this._meshes = null;
  101075. }
  101076. if (this._excludedMeshes) {
  101077. for (var id in this._excludedMeshes) {
  101078. var meshHighlight = this._excludedMeshes[id];
  101079. if (meshHighlight) {
  101080. if (meshHighlight.beforeRender) {
  101081. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  101082. }
  101083. if (meshHighlight.afterRender) {
  101084. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  101085. }
  101086. }
  101087. }
  101088. this._excludedMeshes = null;
  101089. }
  101090. _super.prototype.dispose.call(this);
  101091. };
  101092. /**
  101093. * Gets the class name of the effect layer
  101094. * @returns the string with the class name of the effect layer
  101095. */
  101096. HighlightLayer.prototype.getClassName = function () {
  101097. return "HighlightLayer";
  101098. };
  101099. /**
  101100. * Serializes this Highlight layer
  101101. * @returns a serialized Highlight layer object
  101102. */
  101103. HighlightLayer.prototype.serialize = function () {
  101104. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  101105. serializationObject.customType = "BABYLON.HighlightLayer";
  101106. // Highlighted meshes
  101107. serializationObject.meshes = [];
  101108. if (this._meshes) {
  101109. for (var m in this._meshes) {
  101110. var mesh = this._meshes[m];
  101111. if (mesh) {
  101112. serializationObject.meshes.push({
  101113. glowEmissiveOnly: mesh.glowEmissiveOnly,
  101114. color: mesh.color.asArray(),
  101115. meshId: mesh.mesh.id
  101116. });
  101117. }
  101118. }
  101119. }
  101120. // Excluded meshes
  101121. serializationObject.excludedMeshes = [];
  101122. if (this._excludedMeshes) {
  101123. for (var e in this._excludedMeshes) {
  101124. var excludedMesh = this._excludedMeshes[e];
  101125. if (excludedMesh) {
  101126. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  101127. }
  101128. }
  101129. }
  101130. return serializationObject;
  101131. };
  101132. /**
  101133. * Creates a Highlight layer from parsed Highlight layer data
  101134. * @param parsedHightlightLayer defines the Highlight layer data
  101135. * @param scene defines the current scene
  101136. * @param rootUrl defines the root URL containing the Highlight layer information
  101137. * @returns a parsed Highlight layer
  101138. */
  101139. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  101140. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  101141. var index;
  101142. // Excluded meshes
  101143. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  101144. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  101145. if (mesh) {
  101146. hl.addExcludedMesh(mesh);
  101147. }
  101148. }
  101149. // Included meshes
  101150. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  101151. var highlightedMesh = parsedHightlightLayer.meshes[index];
  101152. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  101153. if (mesh) {
  101154. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  101155. }
  101156. }
  101157. return hl;
  101158. };
  101159. /**
  101160. * Effect Name of the highlight layer.
  101161. */
  101162. HighlightLayer.EffectName = "HighlightLayer";
  101163. /**
  101164. * The neutral color used during the preparation of the glow effect.
  101165. * This is black by default as the blend operation is a blend operation.
  101166. */
  101167. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  101168. /**
  101169. * Stencil value used for glowing meshes.
  101170. */
  101171. HighlightLayer.GlowingMeshStencilReference = 0x02;
  101172. /**
  101173. * Stencil value used for the other meshes in the scene.
  101174. */
  101175. HighlightLayer.NormalMeshStencilReference = 0x01;
  101176. __decorate([
  101177. BABYLON.serialize()
  101178. ], HighlightLayer.prototype, "innerGlow", void 0);
  101179. __decorate([
  101180. BABYLON.serialize()
  101181. ], HighlightLayer.prototype, "outerGlow", void 0);
  101182. __decorate([
  101183. BABYLON.serialize()
  101184. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  101185. __decorate([
  101186. BABYLON.serialize()
  101187. ], HighlightLayer.prototype, "blurVerticalSize", null);
  101188. __decorate([
  101189. BABYLON.serialize("options")
  101190. ], HighlightLayer.prototype, "_options", void 0);
  101191. return HighlightLayer;
  101192. }(BABYLON.EffectLayer));
  101193. BABYLON.HighlightLayer = HighlightLayer;
  101194. })(BABYLON || (BABYLON = {}));
  101195. //# sourceMappingURL=babylon.highlightLayer.js.map
  101196. var BABYLON;
  101197. (function (BABYLON) {
  101198. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  101199. for (var index = 0; index < this.effectLayers.length; index++) {
  101200. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  101201. return this.effectLayers[index];
  101202. }
  101203. }
  101204. return null;
  101205. };
  101206. /**
  101207. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  101208. *
  101209. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  101210. * glowy meshes to your scene.
  101211. *
  101212. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  101213. */
  101214. var GlowLayer = /** @class */ (function (_super) {
  101215. __extends(GlowLayer, _super);
  101216. /**
  101217. * Instantiates a new glow Layer and references it to the scene.
  101218. * @param name The name of the layer
  101219. * @param scene The scene to use the layer in
  101220. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  101221. */
  101222. function GlowLayer(name, scene, options) {
  101223. var _this = _super.call(this, name, scene) || this;
  101224. _this._intensity = 1.0;
  101225. _this._includedOnlyMeshes = [];
  101226. _this._excludedMeshes = [];
  101227. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  101228. // Adapt options
  101229. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  101230. // Initialize the layer
  101231. _this._init({
  101232. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  101233. camera: _this._options.camera,
  101234. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  101235. mainTextureRatio: _this._options.mainTextureRatio,
  101236. renderingGroupId: _this._options.renderingGroupId
  101237. });
  101238. return _this;
  101239. }
  101240. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  101241. /**
  101242. * Gets the kernel size of the blur.
  101243. */
  101244. get: function () {
  101245. return this._horizontalBlurPostprocess1.kernel;
  101246. },
  101247. /**
  101248. * Sets the kernel size of the blur.
  101249. */
  101250. set: function (value) {
  101251. this._horizontalBlurPostprocess1.kernel = value;
  101252. this._verticalBlurPostprocess1.kernel = value;
  101253. this._horizontalBlurPostprocess2.kernel = value;
  101254. this._verticalBlurPostprocess2.kernel = value;
  101255. },
  101256. enumerable: true,
  101257. configurable: true
  101258. });
  101259. Object.defineProperty(GlowLayer.prototype, "intensity", {
  101260. /**
  101261. * Gets the glow intensity.
  101262. */
  101263. get: function () {
  101264. return this._intensity;
  101265. },
  101266. /**
  101267. * Sets the glow intensity.
  101268. */
  101269. set: function (value) {
  101270. this._intensity = value;
  101271. },
  101272. enumerable: true,
  101273. configurable: true
  101274. });
  101275. /**
  101276. * Get the effect name of the layer.
  101277. * @return The effect name
  101278. */
  101279. GlowLayer.prototype.getEffectName = function () {
  101280. return GlowLayer.EffectName;
  101281. };
  101282. /**
  101283. * Create the merge effect. This is the shader use to blit the information back
  101284. * to the main canvas at the end of the scene rendering.
  101285. */
  101286. GlowLayer.prototype._createMergeEffect = function () {
  101287. // Effect
  101288. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  101289. };
  101290. /**
  101291. * Creates the render target textures and post processes used in the glow layer.
  101292. */
  101293. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  101294. var _this = this;
  101295. var blurTextureWidth = this._mainTextureDesiredSize.width;
  101296. var blurTextureHeight = this._mainTextureDesiredSize.height;
  101297. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  101298. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  101299. var textureType = 0;
  101300. if (this._engine.getCaps().textureHalfFloatRender) {
  101301. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  101302. }
  101303. else {
  101304. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  101305. }
  101306. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  101307. width: blurTextureWidth,
  101308. height: blurTextureHeight
  101309. }, this._scene, false, true, textureType);
  101310. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101311. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101312. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  101313. this._blurTexture1.renderParticles = false;
  101314. this._blurTexture1.ignoreCameraViewport = true;
  101315. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  101316. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  101317. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  101318. width: blurTextureWidth2,
  101319. height: blurTextureHeight2
  101320. }, this._scene, false, true, textureType);
  101321. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101322. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101323. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  101324. this._blurTexture2.renderParticles = false;
  101325. this._blurTexture2.ignoreCameraViewport = true;
  101326. this._textures = [this._blurTexture1, this._blurTexture2];
  101327. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  101328. width: blurTextureWidth,
  101329. height: blurTextureHeight
  101330. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  101331. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  101332. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  101333. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  101334. effect.setTexture("textureSampler", _this._mainTexture);
  101335. });
  101336. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  101337. width: blurTextureWidth,
  101338. height: blurTextureHeight
  101339. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  101340. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  101341. width: blurTextureWidth2,
  101342. height: blurTextureHeight2
  101343. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  101344. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  101345. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  101346. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  101347. effect.setTexture("textureSampler", _this._blurTexture1);
  101348. });
  101349. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  101350. width: blurTextureWidth2,
  101351. height: blurTextureHeight2
  101352. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  101353. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  101354. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  101355. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  101356. this._mainTexture.samples = this._options.mainTextureSamples;
  101357. this._mainTexture.onAfterUnbindObservable.add(function () {
  101358. var internalTexture = _this._blurTexture1.getInternalTexture();
  101359. if (internalTexture) {
  101360. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  101361. internalTexture = _this._blurTexture2.getInternalTexture();
  101362. if (internalTexture) {
  101363. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  101364. }
  101365. }
  101366. });
  101367. // Prevent autoClear.
  101368. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  101369. };
  101370. /**
  101371. * Checks for the readiness of the element composing the layer.
  101372. * @param subMesh the mesh to check for
  101373. * @param useInstances specify wether or not to use instances to render the mesh
  101374. * @param emissiveTexture the associated emissive texture used to generate the glow
  101375. * @return true if ready otherwise, false
  101376. */
  101377. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  101378. var material = subMesh.getMaterial();
  101379. var mesh = subMesh.getRenderingMesh();
  101380. if (!material || !mesh) {
  101381. return false;
  101382. }
  101383. var emissiveTexture = material.emissiveTexture;
  101384. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  101385. };
  101386. /**
  101387. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  101388. */
  101389. GlowLayer.prototype.needStencil = function () {
  101390. return false;
  101391. };
  101392. /**
  101393. * Implementation specific of rendering the generating effect on the main canvas.
  101394. * @param effect The effect used to render through
  101395. */
  101396. GlowLayer.prototype._internalRender = function (effect) {
  101397. // Texture
  101398. effect.setTexture("textureSampler", this._blurTexture1);
  101399. effect.setTexture("textureSampler2", this._blurTexture2);
  101400. effect.setFloat("offset", this._intensity);
  101401. // Cache
  101402. var engine = this._engine;
  101403. var previousStencilBuffer = engine.getStencilBuffer();
  101404. // Draw order
  101405. engine.setStencilBuffer(false);
  101406. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  101407. // Draw order
  101408. engine.setStencilBuffer(previousStencilBuffer);
  101409. };
  101410. /**
  101411. * Sets the required values for both the emissive texture and and the main color.
  101412. */
  101413. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  101414. var textureLevel = 1.0;
  101415. if (this.customEmissiveTextureSelector) {
  101416. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  101417. }
  101418. else {
  101419. if (material) {
  101420. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  101421. if (this._emissiveTextureAndColor.texture) {
  101422. textureLevel = this._emissiveTextureAndColor.texture.level;
  101423. }
  101424. }
  101425. else {
  101426. this._emissiveTextureAndColor.texture = null;
  101427. }
  101428. }
  101429. if (this.customEmissiveColorSelector) {
  101430. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  101431. }
  101432. else {
  101433. if (material.emissiveColor) {
  101434. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  101435. }
  101436. else {
  101437. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  101438. }
  101439. }
  101440. };
  101441. /**
  101442. * Returns true if the mesh should render, otherwise false.
  101443. * @param mesh The mesh to render
  101444. * @returns true if it should render otherwise false
  101445. */
  101446. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  101447. return this.hasMesh(mesh);
  101448. };
  101449. /**
  101450. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  101451. * @param mesh The mesh to exclude from the glow layer
  101452. */
  101453. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  101454. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  101455. this._excludedMeshes.push(mesh.uniqueId);
  101456. }
  101457. };
  101458. /**
  101459. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  101460. * @param mesh The mesh to remove
  101461. */
  101462. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  101463. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  101464. if (index !== -1) {
  101465. this._excludedMeshes.splice(index, 1);
  101466. }
  101467. };
  101468. /**
  101469. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  101470. * @param mesh The mesh to include in the glow layer
  101471. */
  101472. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  101473. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  101474. this._includedOnlyMeshes.push(mesh.uniqueId);
  101475. }
  101476. };
  101477. /**
  101478. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  101479. * @param mesh The mesh to remove
  101480. */
  101481. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  101482. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  101483. if (index !== -1) {
  101484. this._includedOnlyMeshes.splice(index, 1);
  101485. }
  101486. };
  101487. /**
  101488. * Determine if a given mesh will be used in the glow layer
  101489. * @param mesh The mesh to test
  101490. * @returns true if the mesh will be highlighted by the current glow layer
  101491. */
  101492. GlowLayer.prototype.hasMesh = function (mesh) {
  101493. if (!_super.prototype.hasMesh.call(this, mesh)) {
  101494. return false;
  101495. }
  101496. // Included Mesh
  101497. if (this._includedOnlyMeshes.length) {
  101498. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  101499. }
  101500. ;
  101501. // Excluded Mesh
  101502. if (this._excludedMeshes.length) {
  101503. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  101504. }
  101505. ;
  101506. return true;
  101507. };
  101508. /**
  101509. * Free any resources and references associated to a mesh.
  101510. * Internal use
  101511. * @param mesh The mesh to free.
  101512. * @hidden
  101513. */
  101514. GlowLayer.prototype._disposeMesh = function (mesh) {
  101515. this.removeIncludedOnlyMesh(mesh);
  101516. this.removeExcludedMesh(mesh);
  101517. };
  101518. /**
  101519. * Gets the class name of the effect layer
  101520. * @returns the string with the class name of the effect layer
  101521. */
  101522. GlowLayer.prototype.getClassName = function () {
  101523. return "GlowLayer";
  101524. };
  101525. /**
  101526. * Serializes this glow layer
  101527. * @returns a serialized glow layer object
  101528. */
  101529. GlowLayer.prototype.serialize = function () {
  101530. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  101531. serializationObject.customType = "BABYLON.GlowLayer";
  101532. var index;
  101533. // Included meshes
  101534. serializationObject.includedMeshes = [];
  101535. if (this._includedOnlyMeshes.length) {
  101536. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  101537. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  101538. if (mesh) {
  101539. serializationObject.includedMeshes.push(mesh.id);
  101540. }
  101541. }
  101542. }
  101543. // Excluded meshes
  101544. serializationObject.excludedMeshes = [];
  101545. if (this._excludedMeshes.length) {
  101546. for (index = 0; index < this._excludedMeshes.length; index++) {
  101547. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  101548. if (mesh) {
  101549. serializationObject.excludedMeshes.push(mesh.id);
  101550. }
  101551. }
  101552. }
  101553. return serializationObject;
  101554. };
  101555. /**
  101556. * Creates a Glow Layer from parsed glow layer data
  101557. * @param parsedGlowLayer defines glow layer data
  101558. * @param scene defines the current scene
  101559. * @param rootUrl defines the root URL containing the glow layer information
  101560. * @returns a parsed Glow Layer
  101561. */
  101562. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  101563. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  101564. var index;
  101565. // Excluded meshes
  101566. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  101567. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  101568. if (mesh) {
  101569. gl.addExcludedMesh(mesh);
  101570. }
  101571. }
  101572. // Included meshes
  101573. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  101574. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  101575. if (mesh) {
  101576. gl.addIncludedOnlyMesh(mesh);
  101577. }
  101578. }
  101579. return gl;
  101580. };
  101581. /**
  101582. * Effect Name of the layer.
  101583. */
  101584. GlowLayer.EffectName = "GlowLayer";
  101585. /**
  101586. * The default blur kernel size used for the glow.
  101587. */
  101588. GlowLayer.DefaultBlurKernelSize = 32;
  101589. /**
  101590. * The default texture size ratio used for the glow.
  101591. */
  101592. GlowLayer.DefaultTextureRatio = 0.5;
  101593. __decorate([
  101594. BABYLON.serialize()
  101595. ], GlowLayer.prototype, "blurKernelSize", null);
  101596. __decorate([
  101597. BABYLON.serialize()
  101598. ], GlowLayer.prototype, "intensity", null);
  101599. __decorate([
  101600. BABYLON.serialize("options")
  101601. ], GlowLayer.prototype, "_options", void 0);
  101602. return GlowLayer;
  101603. }(BABYLON.EffectLayer));
  101604. BABYLON.GlowLayer = GlowLayer;
  101605. })(BABYLON || (BABYLON = {}));
  101606. //# sourceMappingURL=babylon.glowLayer.js.map
  101607. var BABYLON;
  101608. (function (BABYLON) {
  101609. /**
  101610. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  101611. */
  101612. var AssetTaskState;
  101613. (function (AssetTaskState) {
  101614. /**
  101615. * Initialization
  101616. */
  101617. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  101618. /**
  101619. * Running
  101620. */
  101621. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  101622. /**
  101623. * Done
  101624. */
  101625. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  101626. /**
  101627. * Error
  101628. */
  101629. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  101630. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  101631. /**
  101632. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  101633. */
  101634. var AbstractAssetTask = /** @class */ (function () {
  101635. /**
  101636. * Creates a new {BABYLON.AssetsManager}
  101637. * @param name defines the name of the task
  101638. */
  101639. function AbstractAssetTask(
  101640. /**
  101641. * Task name
  101642. */ name) {
  101643. this.name = name;
  101644. this._isCompleted = false;
  101645. this._taskState = AssetTaskState.INIT;
  101646. }
  101647. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  101648. /**
  101649. * Get if the task is completed
  101650. */
  101651. get: function () {
  101652. return this._isCompleted;
  101653. },
  101654. enumerable: true,
  101655. configurable: true
  101656. });
  101657. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  101658. /**
  101659. * Gets the current state of the task
  101660. */
  101661. get: function () {
  101662. return this._taskState;
  101663. },
  101664. enumerable: true,
  101665. configurable: true
  101666. });
  101667. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  101668. /**
  101669. * Gets the current error object (if task is in error)
  101670. */
  101671. get: function () {
  101672. return this._errorObject;
  101673. },
  101674. enumerable: true,
  101675. configurable: true
  101676. });
  101677. /**
  101678. * Internal only
  101679. * @hidden
  101680. */
  101681. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  101682. if (this._errorObject) {
  101683. return;
  101684. }
  101685. this._errorObject = {
  101686. message: message,
  101687. exception: exception
  101688. };
  101689. };
  101690. /**
  101691. * Execute the current task
  101692. * @param scene defines the scene where you want your assets to be loaded
  101693. * @param onSuccess is a callback called when the task is successfully executed
  101694. * @param onError is a callback called if an error occurs
  101695. */
  101696. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  101697. var _this = this;
  101698. this._taskState = AssetTaskState.RUNNING;
  101699. this.runTask(scene, function () {
  101700. _this.onDoneCallback(onSuccess, onError);
  101701. }, function (msg, exception) {
  101702. _this.onErrorCallback(onError, msg, exception);
  101703. });
  101704. };
  101705. /**
  101706. * Execute the current task
  101707. * @param scene defines the scene where you want your assets to be loaded
  101708. * @param onSuccess is a callback called when the task is successfully executed
  101709. * @param onError is a callback called if an error occurs
  101710. */
  101711. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  101712. throw new Error("runTask is not implemented");
  101713. };
  101714. /**
  101715. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  101716. * This can be used with failed tasks that have the reason for failure fixed.
  101717. */
  101718. AbstractAssetTask.prototype.reset = function () {
  101719. this._taskState = AssetTaskState.INIT;
  101720. };
  101721. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  101722. this._taskState = AssetTaskState.ERROR;
  101723. this._errorObject = {
  101724. message: message,
  101725. exception: exception
  101726. };
  101727. if (this.onError) {
  101728. this.onError(this, message, exception);
  101729. }
  101730. onError();
  101731. };
  101732. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  101733. try {
  101734. this._taskState = AssetTaskState.DONE;
  101735. this._isCompleted = true;
  101736. if (this.onSuccess) {
  101737. this.onSuccess(this);
  101738. }
  101739. onSuccess();
  101740. }
  101741. catch (e) {
  101742. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  101743. }
  101744. };
  101745. return AbstractAssetTask;
  101746. }());
  101747. BABYLON.AbstractAssetTask = AbstractAssetTask;
  101748. /**
  101749. * Class used to share progress information about assets loading
  101750. */
  101751. var AssetsProgressEvent = /** @class */ (function () {
  101752. /**
  101753. * Creates a {BABYLON.AssetsProgressEvent}
  101754. * @param remainingCount defines the number of remaining tasks to process
  101755. * @param totalCount defines the total number of tasks
  101756. * @param task defines the task that was just processed
  101757. */
  101758. function AssetsProgressEvent(remainingCount, totalCount, task) {
  101759. this.remainingCount = remainingCount;
  101760. this.totalCount = totalCount;
  101761. this.task = task;
  101762. }
  101763. return AssetsProgressEvent;
  101764. }());
  101765. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  101766. /**
  101767. * Define a task used by {BABYLON.AssetsManager} to load meshes
  101768. */
  101769. var MeshAssetTask = /** @class */ (function (_super) {
  101770. __extends(MeshAssetTask, _super);
  101771. /**
  101772. * Creates a new {BABYLON.MeshAssetTask}
  101773. * @param name defines the name of the task
  101774. * @param meshesNames defines the list of mesh's names you want to load
  101775. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  101776. * @param sceneFilename defines the filename of the scene to load from
  101777. */
  101778. function MeshAssetTask(
  101779. /**
  101780. * Defines the name of the task
  101781. */
  101782. name,
  101783. /**
  101784. * Defines the list of mesh's names you want to load
  101785. */
  101786. meshesNames,
  101787. /**
  101788. * Defines the root url to use as a base to load your meshes and associated resources
  101789. */
  101790. rootUrl,
  101791. /**
  101792. * Defines the filename of the scene to load from
  101793. */
  101794. sceneFilename) {
  101795. var _this = _super.call(this, name) || this;
  101796. _this.name = name;
  101797. _this.meshesNames = meshesNames;
  101798. _this.rootUrl = rootUrl;
  101799. _this.sceneFilename = sceneFilename;
  101800. return _this;
  101801. }
  101802. /**
  101803. * Execute the current task
  101804. * @param scene defines the scene where you want your assets to be loaded
  101805. * @param onSuccess is a callback called when the task is successfully executed
  101806. * @param onError is a callback called if an error occurs
  101807. */
  101808. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  101809. var _this = this;
  101810. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  101811. _this.loadedMeshes = meshes;
  101812. _this.loadedParticleSystems = particleSystems;
  101813. _this.loadedSkeletons = skeletons;
  101814. onSuccess();
  101815. }, null, function (scene, message, exception) {
  101816. onError(message, exception);
  101817. });
  101818. };
  101819. return MeshAssetTask;
  101820. }(AbstractAssetTask));
  101821. BABYLON.MeshAssetTask = MeshAssetTask;
  101822. /**
  101823. * Define a task used by {BABYLON.AssetsManager} to load text content
  101824. */
  101825. var TextFileAssetTask = /** @class */ (function (_super) {
  101826. __extends(TextFileAssetTask, _super);
  101827. /**
  101828. * Creates a new TextFileAssetTask object
  101829. * @param name defines the name of the task
  101830. * @param url defines the location of the file to load
  101831. */
  101832. function TextFileAssetTask(
  101833. /**
  101834. * Defines the name of the task
  101835. */
  101836. name,
  101837. /**
  101838. * Defines the location of the file to load
  101839. */
  101840. url) {
  101841. var _this = _super.call(this, name) || this;
  101842. _this.name = name;
  101843. _this.url = url;
  101844. return _this;
  101845. }
  101846. /**
  101847. * Execute the current task
  101848. * @param scene defines the scene where you want your assets to be loaded
  101849. * @param onSuccess is a callback called when the task is successfully executed
  101850. * @param onError is a callback called if an error occurs
  101851. */
  101852. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  101853. var _this = this;
  101854. scene._loadFile(this.url, function (data) {
  101855. _this.text = data;
  101856. onSuccess();
  101857. }, undefined, false, false, function (request, exception) {
  101858. if (request) {
  101859. onError(request.status + " " + request.statusText, exception);
  101860. }
  101861. });
  101862. };
  101863. return TextFileAssetTask;
  101864. }(AbstractAssetTask));
  101865. BABYLON.TextFileAssetTask = TextFileAssetTask;
  101866. /**
  101867. * Define a task used by {BABYLON.AssetsManager} to load binary data
  101868. */
  101869. var BinaryFileAssetTask = /** @class */ (function (_super) {
  101870. __extends(BinaryFileAssetTask, _super);
  101871. /**
  101872. * Creates a new BinaryFileAssetTask object
  101873. * @param name defines the name of the new task
  101874. * @param url defines the location of the file to load
  101875. */
  101876. function BinaryFileAssetTask(
  101877. /**
  101878. * Defines the name of the task
  101879. */
  101880. name,
  101881. /**
  101882. * Defines the location of the file to load
  101883. */
  101884. url) {
  101885. var _this = _super.call(this, name) || this;
  101886. _this.name = name;
  101887. _this.url = url;
  101888. return _this;
  101889. }
  101890. /**
  101891. * Execute the current task
  101892. * @param scene defines the scene where you want your assets to be loaded
  101893. * @param onSuccess is a callback called when the task is successfully executed
  101894. * @param onError is a callback called if an error occurs
  101895. */
  101896. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  101897. var _this = this;
  101898. scene._loadFile(this.url, function (data) {
  101899. _this.data = data;
  101900. onSuccess();
  101901. }, undefined, true, true, function (request, exception) {
  101902. if (request) {
  101903. onError(request.status + " " + request.statusText, exception);
  101904. }
  101905. });
  101906. };
  101907. return BinaryFileAssetTask;
  101908. }(AbstractAssetTask));
  101909. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  101910. /**
  101911. * Define a task used by {BABYLON.AssetsManager} to load images
  101912. */
  101913. var ImageAssetTask = /** @class */ (function (_super) {
  101914. __extends(ImageAssetTask, _super);
  101915. /**
  101916. * Creates a new ImageAssetTask
  101917. * @param name defines the name of the task
  101918. * @param url defines the location of the image to load
  101919. */
  101920. function ImageAssetTask(
  101921. /**
  101922. * Defines the name of the task
  101923. */
  101924. name,
  101925. /**
  101926. * Defines the location of the image to load
  101927. */
  101928. url) {
  101929. var _this = _super.call(this, name) || this;
  101930. _this.name = name;
  101931. _this.url = url;
  101932. return _this;
  101933. }
  101934. /**
  101935. * Execute the current task
  101936. * @param scene defines the scene where you want your assets to be loaded
  101937. * @param onSuccess is a callback called when the task is successfully executed
  101938. * @param onError is a callback called if an error occurs
  101939. */
  101940. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  101941. var _this = this;
  101942. var img = new Image();
  101943. BABYLON.Tools.SetCorsBehavior(this.url, img);
  101944. img.onload = function () {
  101945. _this.image = img;
  101946. onSuccess();
  101947. };
  101948. img.onerror = function (err) {
  101949. onError("Error loading image", err);
  101950. };
  101951. img.src = this.url;
  101952. };
  101953. return ImageAssetTask;
  101954. }(AbstractAssetTask));
  101955. BABYLON.ImageAssetTask = ImageAssetTask;
  101956. /**
  101957. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  101958. */
  101959. var TextureAssetTask = /** @class */ (function (_super) {
  101960. __extends(TextureAssetTask, _super);
  101961. /**
  101962. * Creates a new TextureAssetTask object
  101963. * @param name defines the name of the task
  101964. * @param url defines the location of the file to load
  101965. * @param noMipmap defines if mipmap should not be generated (default is false)
  101966. * @param invertY defines if texture must be inverted on Y axis (default is false)
  101967. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  101968. */
  101969. function TextureAssetTask(
  101970. /**
  101971. * Defines the name of the task
  101972. */
  101973. name,
  101974. /**
  101975. * Defines the location of the file to load
  101976. */
  101977. url,
  101978. /**
  101979. * Defines if mipmap should not be generated (default is false)
  101980. */
  101981. noMipmap,
  101982. /**
  101983. * Defines if texture must be inverted on Y axis (default is false)
  101984. */
  101985. invertY,
  101986. /**
  101987. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  101988. */
  101989. samplingMode) {
  101990. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  101991. var _this = _super.call(this, name) || this;
  101992. _this.name = name;
  101993. _this.url = url;
  101994. _this.noMipmap = noMipmap;
  101995. _this.invertY = invertY;
  101996. _this.samplingMode = samplingMode;
  101997. return _this;
  101998. }
  101999. /**
  102000. * Execute the current task
  102001. * @param scene defines the scene where you want your assets to be loaded
  102002. * @param onSuccess is a callback called when the task is successfully executed
  102003. * @param onError is a callback called if an error occurs
  102004. */
  102005. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  102006. var onload = function () {
  102007. onSuccess();
  102008. };
  102009. var onerror = function (message, exception) {
  102010. onError(message, exception);
  102011. };
  102012. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  102013. };
  102014. return TextureAssetTask;
  102015. }(AbstractAssetTask));
  102016. BABYLON.TextureAssetTask = TextureAssetTask;
  102017. /**
  102018. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  102019. */
  102020. var CubeTextureAssetTask = /** @class */ (function (_super) {
  102021. __extends(CubeTextureAssetTask, _super);
  102022. /**
  102023. * Creates a new CubeTextureAssetTask
  102024. * @param name defines the name of the task
  102025. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  102026. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  102027. * @param noMipmap defines if mipmaps should not be generated (default is false)
  102028. * @param files defines the explicit list of files (undefined by default)
  102029. */
  102030. function CubeTextureAssetTask(
  102031. /**
  102032. * Defines the name of the task
  102033. */
  102034. name,
  102035. /**
  102036. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  102037. */
  102038. url,
  102039. /**
  102040. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  102041. */
  102042. extensions,
  102043. /**
  102044. * Defines if mipmaps should not be generated (default is false)
  102045. */
  102046. noMipmap,
  102047. /**
  102048. * Defines the explicit list of files (undefined by default)
  102049. */
  102050. files) {
  102051. var _this = _super.call(this, name) || this;
  102052. _this.name = name;
  102053. _this.url = url;
  102054. _this.extensions = extensions;
  102055. _this.noMipmap = noMipmap;
  102056. _this.files = files;
  102057. return _this;
  102058. }
  102059. /**
  102060. * Execute the current task
  102061. * @param scene defines the scene where you want your assets to be loaded
  102062. * @param onSuccess is a callback called when the task is successfully executed
  102063. * @param onError is a callback called if an error occurs
  102064. */
  102065. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  102066. var onload = function () {
  102067. onSuccess();
  102068. };
  102069. var onerror = function (message, exception) {
  102070. onError(message, exception);
  102071. };
  102072. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  102073. };
  102074. return CubeTextureAssetTask;
  102075. }(AbstractAssetTask));
  102076. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  102077. /**
  102078. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  102079. */
  102080. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  102081. __extends(HDRCubeTextureAssetTask, _super);
  102082. /**
  102083. * Creates a new HDRCubeTextureAssetTask object
  102084. * @param name defines the name of the task
  102085. * @param url defines the location of the file to load
  102086. * @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.
  102087. * @param noMipmap defines if mipmaps should not be generated (default is false)
  102088. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  102089. * @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)
  102090. * @param reserved Internal use only
  102091. */
  102092. function HDRCubeTextureAssetTask(
  102093. /**
  102094. * Defines the name of the task
  102095. */
  102096. name,
  102097. /**
  102098. * Defines the location of the file to load
  102099. */
  102100. url,
  102101. /**
  102102. * Defines the desired size (the more it increases the longer the generation will be)
  102103. */
  102104. size,
  102105. /**
  102106. * Defines if mipmaps should not be generated (default is false)
  102107. */
  102108. noMipmap,
  102109. /**
  102110. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  102111. */
  102112. generateHarmonics,
  102113. /**
  102114. * 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)
  102115. */
  102116. gammaSpace,
  102117. /**
  102118. * Internal Use Only
  102119. */
  102120. reserved) {
  102121. if (noMipmap === void 0) { noMipmap = false; }
  102122. if (generateHarmonics === void 0) { generateHarmonics = true; }
  102123. if (gammaSpace === void 0) { gammaSpace = false; }
  102124. if (reserved === void 0) { reserved = false; }
  102125. var _this = _super.call(this, name) || this;
  102126. _this.name = name;
  102127. _this.url = url;
  102128. _this.size = size;
  102129. _this.noMipmap = noMipmap;
  102130. _this.generateHarmonics = generateHarmonics;
  102131. _this.gammaSpace = gammaSpace;
  102132. _this.reserved = reserved;
  102133. return _this;
  102134. }
  102135. /**
  102136. * Execute the current task
  102137. * @param scene defines the scene where you want your assets to be loaded
  102138. * @param onSuccess is a callback called when the task is successfully executed
  102139. * @param onError is a callback called if an error occurs
  102140. */
  102141. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  102142. var onload = function () {
  102143. onSuccess();
  102144. };
  102145. var onerror = function (message, exception) {
  102146. onError(message, exception);
  102147. };
  102148. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  102149. };
  102150. return HDRCubeTextureAssetTask;
  102151. }(AbstractAssetTask));
  102152. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  102153. /**
  102154. * This class can be used to easily import assets into a scene
  102155. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  102156. */
  102157. var AssetsManager = /** @class */ (function () {
  102158. /**
  102159. * Creates a new AssetsManager
  102160. * @param scene defines the scene to work on
  102161. */
  102162. function AssetsManager(scene) {
  102163. this._isLoading = false;
  102164. this._tasks = new Array();
  102165. this._waitingTasksCount = 0;
  102166. this._totalTasksCount = 0;
  102167. /**
  102168. * Observable called when all tasks are processed
  102169. */
  102170. this.onTaskSuccessObservable = new BABYLON.Observable();
  102171. /**
  102172. * Observable called when a task had an error
  102173. */
  102174. this.onTaskErrorObservable = new BABYLON.Observable();
  102175. /**
  102176. * Observable called when a task is successful
  102177. */
  102178. this.onTasksDoneObservable = new BABYLON.Observable();
  102179. /**
  102180. * Observable called when a task is done (whatever the result is)
  102181. */
  102182. this.onProgressObservable = new BABYLON.Observable();
  102183. /**
  102184. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  102185. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  102186. */
  102187. this.useDefaultLoadingScreen = true;
  102188. this._scene = scene;
  102189. }
  102190. /**
  102191. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  102192. * @param taskName defines the name of the new task
  102193. * @param meshesNames defines the name of meshes to load
  102194. * @param rootUrl defines the root url to use to locate files
  102195. * @param sceneFilename defines the filename of the scene file
  102196. * @returns a new {BABYLON.MeshAssetTask} object
  102197. */
  102198. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  102199. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  102200. this._tasks.push(task);
  102201. return task;
  102202. };
  102203. /**
  102204. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  102205. * @param taskName defines the name of the new task
  102206. * @param url defines the url of the file to load
  102207. * @returns a new {BABYLON.TextFileAssetTask} object
  102208. */
  102209. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  102210. var task = new TextFileAssetTask(taskName, url);
  102211. this._tasks.push(task);
  102212. return task;
  102213. };
  102214. /**
  102215. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  102216. * @param taskName defines the name of the new task
  102217. * @param url defines the url of the file to load
  102218. * @returns a new {BABYLON.BinaryFileAssetTask} object
  102219. */
  102220. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  102221. var task = new BinaryFileAssetTask(taskName, url);
  102222. this._tasks.push(task);
  102223. return task;
  102224. };
  102225. /**
  102226. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  102227. * @param taskName defines the name of the new task
  102228. * @param url defines the url of the file to load
  102229. * @returns a new {BABYLON.ImageAssetTask} object
  102230. */
  102231. AssetsManager.prototype.addImageTask = function (taskName, url) {
  102232. var task = new ImageAssetTask(taskName, url);
  102233. this._tasks.push(task);
  102234. return task;
  102235. };
  102236. /**
  102237. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  102238. * @param taskName defines the name of the new task
  102239. * @param url defines the url of the file to load
  102240. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  102241. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  102242. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  102243. * @returns a new {BABYLON.TextureAssetTask} object
  102244. */
  102245. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  102246. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  102247. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  102248. this._tasks.push(task);
  102249. return task;
  102250. };
  102251. /**
  102252. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  102253. * @param taskName defines the name of the new task
  102254. * @param url defines the url of the file to load
  102255. * @param extensions defines the extension to use to load the cube map (can be null)
  102256. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  102257. * @param files defines the list of files to load (can be null)
  102258. * @returns a new {BABYLON.CubeTextureAssetTask} object
  102259. */
  102260. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  102261. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  102262. this._tasks.push(task);
  102263. return task;
  102264. };
  102265. /**
  102266. *
  102267. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  102268. * @param taskName defines the name of the new task
  102269. * @param url defines the url of the file to load
  102270. * @param size defines the size you want for the cubemap (can be null)
  102271. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  102272. * @param generateHarmonics defines if you want to automatically generate (true by default)
  102273. * @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)
  102274. * @param reserved Internal use only
  102275. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  102276. */
  102277. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  102278. if (noMipmap === void 0) { noMipmap = false; }
  102279. if (generateHarmonics === void 0) { generateHarmonics = true; }
  102280. if (gammaSpace === void 0) { gammaSpace = false; }
  102281. if (reserved === void 0) { reserved = false; }
  102282. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  102283. this._tasks.push(task);
  102284. return task;
  102285. };
  102286. /**
  102287. * Remove a task from the assets manager.
  102288. * @param task the task to remove
  102289. */
  102290. AssetsManager.prototype.removeTask = function (task) {
  102291. var index = this._tasks.indexOf(task);
  102292. if (index > -1) {
  102293. this._tasks.splice(index, 1);
  102294. }
  102295. };
  102296. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  102297. this._waitingTasksCount--;
  102298. try {
  102299. if (this.onProgress) {
  102300. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  102301. }
  102302. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  102303. }
  102304. catch (e) {
  102305. BABYLON.Tools.Error("Error running progress callbacks.");
  102306. console.log(e);
  102307. }
  102308. if (this._waitingTasksCount === 0) {
  102309. try {
  102310. if (this.onFinish) {
  102311. this.onFinish(this._tasks);
  102312. }
  102313. // Let's remove successfull tasks
  102314. var currentTasks = this._tasks.slice();
  102315. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  102316. var task = currentTasks_1[_i];
  102317. if (task.taskState === AssetTaskState.DONE) {
  102318. var index = this._tasks.indexOf(task);
  102319. if (index > -1) {
  102320. this._tasks.splice(index, 1);
  102321. }
  102322. }
  102323. }
  102324. this.onTasksDoneObservable.notifyObservers(this._tasks);
  102325. }
  102326. catch (e) {
  102327. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  102328. console.log(e);
  102329. }
  102330. this._isLoading = false;
  102331. this._scene.getEngine().hideLoadingUI();
  102332. }
  102333. };
  102334. AssetsManager.prototype._runTask = function (task) {
  102335. var _this = this;
  102336. var done = function () {
  102337. try {
  102338. if (_this.onTaskSuccess) {
  102339. _this.onTaskSuccess(task);
  102340. }
  102341. _this.onTaskSuccessObservable.notifyObservers(task);
  102342. _this._decreaseWaitingTasksCount(task);
  102343. }
  102344. catch (e) {
  102345. error("Error executing task success callbacks", e);
  102346. }
  102347. };
  102348. var error = function (message, exception) {
  102349. task._setErrorObject(message, exception);
  102350. if (_this.onTaskError) {
  102351. _this.onTaskError(task);
  102352. }
  102353. _this.onTaskErrorObservable.notifyObservers(task);
  102354. _this._decreaseWaitingTasksCount(task);
  102355. };
  102356. task.run(this._scene, done, error);
  102357. };
  102358. /**
  102359. * Reset the {BABYLON.AssetsManager} and remove all tasks
  102360. * @return the current instance of the {BABYLON.AssetsManager}
  102361. */
  102362. AssetsManager.prototype.reset = function () {
  102363. this._isLoading = false;
  102364. this._tasks = new Array();
  102365. return this;
  102366. };
  102367. /**
  102368. * Start the loading process
  102369. * @return the current instance of the {BABYLON.AssetsManager}
  102370. */
  102371. AssetsManager.prototype.load = function () {
  102372. if (this._isLoading) {
  102373. return this;
  102374. }
  102375. this._isLoading = true;
  102376. this._waitingTasksCount = this._tasks.length;
  102377. this._totalTasksCount = this._tasks.length;
  102378. if (this._waitingTasksCount === 0) {
  102379. this._isLoading = false;
  102380. if (this.onFinish) {
  102381. this.onFinish(this._tasks);
  102382. }
  102383. this.onTasksDoneObservable.notifyObservers(this._tasks);
  102384. return this;
  102385. }
  102386. if (this.useDefaultLoadingScreen) {
  102387. this._scene.getEngine().displayLoadingUI();
  102388. }
  102389. for (var index = 0; index < this._tasks.length; index++) {
  102390. var task = this._tasks[index];
  102391. if (task.taskState === AssetTaskState.INIT) {
  102392. this._runTask(task);
  102393. }
  102394. }
  102395. return this;
  102396. };
  102397. return AssetsManager;
  102398. }());
  102399. BABYLON.AssetsManager = AssetsManager;
  102400. })(BABYLON || (BABYLON = {}));
  102401. //# sourceMappingURL=babylon.assetsManager.js.map
  102402. var BABYLON;
  102403. (function (BABYLON) {
  102404. var serializedGeometries = [];
  102405. var serializeGeometry = function (geometry, serializationGeometries) {
  102406. if (serializedGeometries[geometry.id]) {
  102407. return;
  102408. }
  102409. if (geometry.doNotSerialize) {
  102410. return;
  102411. }
  102412. if (geometry instanceof BABYLON.BoxGeometry) {
  102413. serializationGeometries.boxes.push(geometry.serialize());
  102414. }
  102415. else if (geometry instanceof BABYLON.SphereGeometry) {
  102416. serializationGeometries.spheres.push(geometry.serialize());
  102417. }
  102418. else if (geometry instanceof BABYLON.CylinderGeometry) {
  102419. serializationGeometries.cylinders.push(geometry.serialize());
  102420. }
  102421. else if (geometry instanceof BABYLON.TorusGeometry) {
  102422. serializationGeometries.toruses.push(geometry.serialize());
  102423. }
  102424. else if (geometry instanceof BABYLON.GroundGeometry) {
  102425. serializationGeometries.grounds.push(geometry.serialize());
  102426. }
  102427. else if (geometry instanceof BABYLON.Plane) {
  102428. serializationGeometries.planes.push(geometry.serialize());
  102429. }
  102430. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  102431. serializationGeometries.torusKnots.push(geometry.serialize());
  102432. }
  102433. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  102434. throw new Error("Unknown primitive type");
  102435. }
  102436. else {
  102437. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  102438. }
  102439. serializedGeometries[geometry.id] = true;
  102440. };
  102441. var serializeMesh = function (mesh, serializationScene) {
  102442. var serializationObject = {};
  102443. // Geometry
  102444. var geometry = mesh._geometry;
  102445. if (geometry) {
  102446. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  102447. // 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
  102448. serializeGeometry(geometry, serializationScene.geometries);
  102449. }
  102450. }
  102451. // Custom
  102452. if (mesh.serialize) {
  102453. mesh.serialize(serializationObject);
  102454. }
  102455. return serializationObject;
  102456. };
  102457. var finalizeSingleMesh = function (mesh, serializationObject) {
  102458. //only works if the mesh is already loaded
  102459. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  102460. //serialize material
  102461. if (mesh.material) {
  102462. if (mesh.material instanceof BABYLON.MultiMaterial) {
  102463. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  102464. serializationObject.materials = serializationObject.materials || [];
  102465. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  102466. serializationObject.multiMaterials.push(mesh.material.serialize());
  102467. var _loop_1 = function (submaterial) {
  102468. if (submaterial) {
  102469. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  102470. serializationObject.materials.push(submaterial.serialize());
  102471. }
  102472. }
  102473. };
  102474. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  102475. var submaterial = _a[_i];
  102476. _loop_1(submaterial);
  102477. }
  102478. }
  102479. }
  102480. else {
  102481. serializationObject.materials = serializationObject.materials || [];
  102482. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  102483. serializationObject.materials.push(mesh.material.serialize());
  102484. }
  102485. }
  102486. }
  102487. //serialize geometry
  102488. var geometry = mesh._geometry;
  102489. if (geometry) {
  102490. if (!serializationObject.geometries) {
  102491. serializationObject.geometries = {};
  102492. serializationObject.geometries.boxes = [];
  102493. serializationObject.geometries.spheres = [];
  102494. serializationObject.geometries.cylinders = [];
  102495. serializationObject.geometries.toruses = [];
  102496. serializationObject.geometries.grounds = [];
  102497. serializationObject.geometries.planes = [];
  102498. serializationObject.geometries.torusKnots = [];
  102499. serializationObject.geometries.vertexData = [];
  102500. }
  102501. serializeGeometry(geometry, serializationObject.geometries);
  102502. }
  102503. // Skeletons
  102504. if (mesh.skeleton) {
  102505. serializationObject.skeletons = serializationObject.skeletons || [];
  102506. serializationObject.skeletons.push(mesh.skeleton.serialize());
  102507. }
  102508. //serialize the actual mesh
  102509. serializationObject.meshes = serializationObject.meshes || [];
  102510. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  102511. }
  102512. };
  102513. var SceneSerializer = /** @class */ (function () {
  102514. function SceneSerializer() {
  102515. }
  102516. SceneSerializer.ClearCache = function () {
  102517. serializedGeometries = [];
  102518. };
  102519. SceneSerializer.Serialize = function (scene) {
  102520. var serializationObject = {};
  102521. SceneSerializer.ClearCache();
  102522. // Scene
  102523. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  102524. serializationObject.autoClear = scene.autoClear;
  102525. serializationObject.clearColor = scene.clearColor.asArray();
  102526. serializationObject.ambientColor = scene.ambientColor.asArray();
  102527. serializationObject.gravity = scene.gravity.asArray();
  102528. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  102529. serializationObject.workerCollisions = scene.workerCollisions;
  102530. // Fog
  102531. if (scene.fogMode && scene.fogMode !== 0) {
  102532. serializationObject.fogMode = scene.fogMode;
  102533. serializationObject.fogColor = scene.fogColor.asArray();
  102534. serializationObject.fogStart = scene.fogStart;
  102535. serializationObject.fogEnd = scene.fogEnd;
  102536. serializationObject.fogDensity = scene.fogDensity;
  102537. }
  102538. //Physics
  102539. if (scene.isPhysicsEnabled()) {
  102540. var physicEngine = scene.getPhysicsEngine();
  102541. if (physicEngine) {
  102542. serializationObject.physicsEnabled = true;
  102543. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  102544. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  102545. }
  102546. }
  102547. // Metadata
  102548. if (scene.metadata) {
  102549. serializationObject.metadata = scene.metadata;
  102550. }
  102551. // Morph targets
  102552. serializationObject.morphTargetManagers = [];
  102553. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  102554. var abstractMesh = _a[_i];
  102555. var manager = abstractMesh.morphTargetManager;
  102556. if (manager) {
  102557. serializationObject.morphTargetManagers.push(manager.serialize());
  102558. }
  102559. }
  102560. // Lights
  102561. serializationObject.lights = [];
  102562. var index;
  102563. var light;
  102564. for (index = 0; index < scene.lights.length; index++) {
  102565. light = scene.lights[index];
  102566. if (!light.doNotSerialize) {
  102567. serializationObject.lights.push(light.serialize());
  102568. }
  102569. }
  102570. // Cameras
  102571. serializationObject.cameras = [];
  102572. for (index = 0; index < scene.cameras.length; index++) {
  102573. var camera = scene.cameras[index];
  102574. if (!camera.doNotSerialize) {
  102575. serializationObject.cameras.push(camera.serialize());
  102576. }
  102577. }
  102578. if (scene.activeCamera) {
  102579. serializationObject.activeCameraID = scene.activeCamera.id;
  102580. }
  102581. // Animations
  102582. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  102583. // Materials
  102584. serializationObject.materials = [];
  102585. serializationObject.multiMaterials = [];
  102586. var material;
  102587. for (index = 0; index < scene.materials.length; index++) {
  102588. material = scene.materials[index];
  102589. if (!material.doNotSerialize) {
  102590. serializationObject.materials.push(material.serialize());
  102591. }
  102592. }
  102593. // MultiMaterials
  102594. serializationObject.multiMaterials = [];
  102595. for (index = 0; index < scene.multiMaterials.length; index++) {
  102596. var multiMaterial = scene.multiMaterials[index];
  102597. serializationObject.multiMaterials.push(multiMaterial.serialize());
  102598. }
  102599. // Environment texture
  102600. if (scene.environmentTexture) {
  102601. serializationObject.environmentTexture = scene.environmentTexture.name;
  102602. }
  102603. // Skeletons
  102604. serializationObject.skeletons = [];
  102605. for (index = 0; index < scene.skeletons.length; index++) {
  102606. var skeleton = scene.skeletons[index];
  102607. if (!skeleton.doNotSerialize) {
  102608. serializationObject.skeletons.push(skeleton.serialize());
  102609. }
  102610. }
  102611. // Transform nodes
  102612. serializationObject.transformNodes = [];
  102613. for (index = 0; index < scene.transformNodes.length; index++) {
  102614. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  102615. }
  102616. // Geometries
  102617. serializationObject.geometries = {};
  102618. serializationObject.geometries.boxes = [];
  102619. serializationObject.geometries.spheres = [];
  102620. serializationObject.geometries.cylinders = [];
  102621. serializationObject.geometries.toruses = [];
  102622. serializationObject.geometries.grounds = [];
  102623. serializationObject.geometries.planes = [];
  102624. serializationObject.geometries.torusKnots = [];
  102625. serializationObject.geometries.vertexData = [];
  102626. serializedGeometries = [];
  102627. var geometries = scene.getGeometries();
  102628. for (index = 0; index < geometries.length; index++) {
  102629. var geometry = geometries[index];
  102630. if (geometry.isReady()) {
  102631. serializeGeometry(geometry, serializationObject.geometries);
  102632. }
  102633. }
  102634. // Meshes
  102635. serializationObject.meshes = [];
  102636. for (index = 0; index < scene.meshes.length; index++) {
  102637. var abstractMesh = scene.meshes[index];
  102638. if (abstractMesh instanceof BABYLON.Mesh) {
  102639. var mesh = abstractMesh;
  102640. if (!mesh.doNotSerialize) {
  102641. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  102642. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  102643. }
  102644. }
  102645. }
  102646. }
  102647. // Particles Systems
  102648. serializationObject.particleSystems = [];
  102649. for (index = 0; index < scene.particleSystems.length; index++) {
  102650. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  102651. }
  102652. // Shadows
  102653. serializationObject.shadowGenerators = [];
  102654. for (index = 0; index < scene.lights.length; index++) {
  102655. light = scene.lights[index];
  102656. var shadowGenerator = light.getShadowGenerator();
  102657. if (shadowGenerator) {
  102658. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  102659. }
  102660. }
  102661. // Action Manager
  102662. if (scene.actionManager) {
  102663. serializationObject.actions = scene.actionManager.serialize("scene");
  102664. }
  102665. // Audio
  102666. serializationObject.sounds = [];
  102667. for (index = 0; index < scene.soundTracks.length; index++) {
  102668. var soundtrack = scene.soundTracks[index];
  102669. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  102670. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  102671. }
  102672. }
  102673. // Components
  102674. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  102675. var component = _c[_b];
  102676. component.serialize(serializationObject);
  102677. }
  102678. return serializationObject;
  102679. };
  102680. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  102681. if (withParents === void 0) { withParents = false; }
  102682. if (withChildren === void 0) { withChildren = false; }
  102683. var serializationObject = {};
  102684. SceneSerializer.ClearCache();
  102685. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  102686. if (withParents || withChildren) {
  102687. //deliberate for loop! not for each, appended should be processed as well.
  102688. for (var i = 0; i < toSerialize.length; ++i) {
  102689. if (withChildren) {
  102690. toSerialize[i].getDescendants().forEach(function (node) {
  102691. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  102692. toSerialize.push(node);
  102693. }
  102694. });
  102695. }
  102696. //make sure the array doesn't contain the object already
  102697. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  102698. toSerialize.push(toSerialize[i].parent);
  102699. }
  102700. }
  102701. }
  102702. toSerialize.forEach(function (mesh) {
  102703. finalizeSingleMesh(mesh, serializationObject);
  102704. });
  102705. return serializationObject;
  102706. };
  102707. return SceneSerializer;
  102708. }());
  102709. BABYLON.SceneSerializer = SceneSerializer;
  102710. })(BABYLON || (BABYLON = {}));
  102711. //# sourceMappingURL=babylon.sceneSerializer.js.map
  102712. var BABYLON;
  102713. (function (BABYLON) {
  102714. /**
  102715. * Class used to generate realtime reflection / refraction cube textures
  102716. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  102717. */
  102718. var ReflectionProbe = /** @class */ (function () {
  102719. /**
  102720. * Creates a new reflection probe
  102721. * @param name defines the name of the probe
  102722. * @param size defines the texture resolution (for each face)
  102723. * @param scene defines the hosting scene
  102724. * @param generateMipMaps defines if mip maps should be generated automatically (true by default)
  102725. * @param useFloat defines if HDR data (flaot data) should be used to store colors (false by default)
  102726. */
  102727. function ReflectionProbe(
  102728. /** defines the name of the probe */
  102729. name, size, scene, generateMipMaps, useFloat) {
  102730. if (generateMipMaps === void 0) { generateMipMaps = true; }
  102731. if (useFloat === void 0) { useFloat = false; }
  102732. var _this = this;
  102733. this.name = name;
  102734. this._viewMatrix = BABYLON.Matrix.Identity();
  102735. this._target = BABYLON.Vector3.Zero();
  102736. this._add = BABYLON.Vector3.Zero();
  102737. this._invertYAxis = false;
  102738. /** Gets or sets probe position (center of the cube map) */
  102739. this.position = BABYLON.Vector3.Zero();
  102740. this._scene = scene;
  102741. this._scene.reflectionProbes.push(this);
  102742. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, useFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  102743. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  102744. switch (faceIndex) {
  102745. case 0:
  102746. _this._add.copyFromFloats(1, 0, 0);
  102747. break;
  102748. case 1:
  102749. _this._add.copyFromFloats(-1, 0, 0);
  102750. break;
  102751. case 2:
  102752. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  102753. break;
  102754. case 3:
  102755. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  102756. break;
  102757. case 4:
  102758. _this._add.copyFromFloats(0, 0, 1);
  102759. break;
  102760. case 5:
  102761. _this._add.copyFromFloats(0, 0, -1);
  102762. break;
  102763. }
  102764. if (_this._attachedMesh) {
  102765. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  102766. }
  102767. _this.position.addToRef(_this._add, _this._target);
  102768. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  102769. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  102770. scene._forcedViewPosition = _this.position;
  102771. });
  102772. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  102773. scene._forcedViewPosition = null;
  102774. scene.updateTransformMatrix(true);
  102775. });
  102776. if (scene.activeCamera) {
  102777. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  102778. }
  102779. }
  102780. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  102781. /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */
  102782. get: function () {
  102783. return this._renderTargetTexture.samples;
  102784. },
  102785. set: function (value) {
  102786. this._renderTargetTexture.samples = value;
  102787. },
  102788. enumerable: true,
  102789. configurable: true
  102790. });
  102791. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  102792. /** Gets or sets the refresh rate to use (on every frame by default) */
  102793. get: function () {
  102794. return this._renderTargetTexture.refreshRate;
  102795. },
  102796. set: function (value) {
  102797. this._renderTargetTexture.refreshRate = value;
  102798. },
  102799. enumerable: true,
  102800. configurable: true
  102801. });
  102802. /**
  102803. * Gets the hosting scene
  102804. * @returns a Scene
  102805. */
  102806. ReflectionProbe.prototype.getScene = function () {
  102807. return this._scene;
  102808. };
  102809. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  102810. /** Gets the internal CubeTexture used to render to */
  102811. get: function () {
  102812. return this._renderTargetTexture;
  102813. },
  102814. enumerable: true,
  102815. configurable: true
  102816. });
  102817. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  102818. /** Gets the list of meshes to render */
  102819. get: function () {
  102820. return this._renderTargetTexture.renderList;
  102821. },
  102822. enumerable: true,
  102823. configurable: true
  102824. });
  102825. /**
  102826. * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)
  102827. * @param mesh defines the mesh to attach to
  102828. */
  102829. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  102830. this._attachedMesh = mesh;
  102831. };
  102832. /**
  102833. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups
  102834. * @param renderingGroupId The rendering group id corresponding to its index
  102835. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  102836. */
  102837. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  102838. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  102839. };
  102840. /**
  102841. * Clean all associated resources
  102842. */
  102843. ReflectionProbe.prototype.dispose = function () {
  102844. var index = this._scene.reflectionProbes.indexOf(this);
  102845. if (index !== -1) {
  102846. // Remove from the scene if found
  102847. this._scene.reflectionProbes.splice(index, 1);
  102848. }
  102849. if (this._renderTargetTexture) {
  102850. this._renderTargetTexture.dispose();
  102851. this._renderTargetTexture = null;
  102852. }
  102853. };
  102854. return ReflectionProbe;
  102855. }());
  102856. BABYLON.ReflectionProbe = ReflectionProbe;
  102857. })(BABYLON || (BABYLON = {}));
  102858. //# sourceMappingURL=babylon.reflectionProbe.js.map
  102859. var BABYLON;
  102860. (function (BABYLON) {
  102861. /**
  102862. * Defines the layer scene component responsible to manage any layers
  102863. * in a given scene.
  102864. */
  102865. var LayerSceneComponent = /** @class */ (function () {
  102866. /**
  102867. * Creates a new instance of the component for the given scene
  102868. * @param scene Defines the scene to register the component in
  102869. */
  102870. function LayerSceneComponent(scene) {
  102871. /**
  102872. * The component name helpfull to identify the component in the list of scene components.
  102873. */
  102874. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  102875. this.scene = scene;
  102876. this._engine = scene.getEngine();
  102877. scene.layers = new Array();
  102878. }
  102879. /**
  102880. * Registers the component in a given scene
  102881. */
  102882. LayerSceneComponent.prototype.register = function () {
  102883. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  102884. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  102885. };
  102886. /**
  102887. * Rebuilds the elements related to this component in case of
  102888. * context lost for instance.
  102889. */
  102890. LayerSceneComponent.prototype.rebuild = function () {
  102891. var layers = this.scene.layers;
  102892. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  102893. var layer = layers_1[_i];
  102894. layer._rebuild();
  102895. }
  102896. };
  102897. /**
  102898. * Disposes the component and the associated ressources.
  102899. */
  102900. LayerSceneComponent.prototype.dispose = function () {
  102901. var layers = this.scene.layers;
  102902. while (layers.length) {
  102903. layers[0].dispose();
  102904. }
  102905. };
  102906. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  102907. var layers = this.scene.layers;
  102908. if (layers.length) {
  102909. this._engine.setDepthBuffer(false);
  102910. var cameraLayerMask = camera.layerMask;
  102911. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  102912. var layer = layers_2[_i];
  102913. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  102914. layer.render();
  102915. }
  102916. }
  102917. this._engine.setDepthBuffer(true);
  102918. }
  102919. };
  102920. LayerSceneComponent.prototype._drawBackground = function (camera) {
  102921. this._draw(camera, true);
  102922. };
  102923. LayerSceneComponent.prototype._drawForeground = function (camera) {
  102924. this._draw(camera, false);
  102925. };
  102926. return LayerSceneComponent;
  102927. }());
  102928. BABYLON.LayerSceneComponent = LayerSceneComponent;
  102929. })(BABYLON || (BABYLON = {}));
  102930. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  102931. var BABYLON;
  102932. (function (BABYLON) {
  102933. var Layer = /** @class */ (function () {
  102934. function Layer(name, imgUrl, scene, isBackground, color) {
  102935. this.name = name;
  102936. this.scale = new BABYLON.Vector2(1, 1);
  102937. this.offset = new BABYLON.Vector2(0, 0);
  102938. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  102939. this.layerMask = 0x0FFFFFFF;
  102940. this._vertexBuffers = {};
  102941. // Events
  102942. /**
  102943. * An event triggered when the layer is disposed.
  102944. */
  102945. this.onDisposeObservable = new BABYLON.Observable();
  102946. /**
  102947. * An event triggered before rendering the scene
  102948. */
  102949. this.onBeforeRenderObservable = new BABYLON.Observable();
  102950. /**
  102951. * An event triggered after rendering the scene
  102952. */
  102953. this.onAfterRenderObservable = new BABYLON.Observable();
  102954. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  102955. this.isBackground = isBackground === undefined ? true : isBackground;
  102956. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  102957. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  102958. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  102959. if (!layerComponent) {
  102960. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  102961. this._scene._addComponent(layerComponent);
  102962. }
  102963. this._scene.layers.push(this);
  102964. var engine = this._scene.getEngine();
  102965. // VBO
  102966. var vertices = [];
  102967. vertices.push(1, 1);
  102968. vertices.push(-1, 1);
  102969. vertices.push(-1, -1);
  102970. vertices.push(1, -1);
  102971. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  102972. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  102973. this._createIndexBuffer();
  102974. // Effects
  102975. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  102976. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  102977. }
  102978. Object.defineProperty(Layer.prototype, "onDispose", {
  102979. set: function (callback) {
  102980. if (this._onDisposeObserver) {
  102981. this.onDisposeObservable.remove(this._onDisposeObserver);
  102982. }
  102983. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  102984. },
  102985. enumerable: true,
  102986. configurable: true
  102987. });
  102988. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  102989. set: function (callback) {
  102990. if (this._onBeforeRenderObserver) {
  102991. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  102992. }
  102993. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  102994. },
  102995. enumerable: true,
  102996. configurable: true
  102997. });
  102998. Object.defineProperty(Layer.prototype, "onAfterRender", {
  102999. set: function (callback) {
  103000. if (this._onAfterRenderObserver) {
  103001. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  103002. }
  103003. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  103004. },
  103005. enumerable: true,
  103006. configurable: true
  103007. });
  103008. Layer.prototype._createIndexBuffer = function () {
  103009. var engine = this._scene.getEngine();
  103010. // Indices
  103011. var indices = [];
  103012. indices.push(0);
  103013. indices.push(1);
  103014. indices.push(2);
  103015. indices.push(0);
  103016. indices.push(2);
  103017. indices.push(3);
  103018. this._indexBuffer = engine.createIndexBuffer(indices);
  103019. };
  103020. /** @hidden */
  103021. Layer.prototype._rebuild = function () {
  103022. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  103023. if (vb) {
  103024. vb._rebuild();
  103025. }
  103026. this._createIndexBuffer();
  103027. };
  103028. Layer.prototype.render = function () {
  103029. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  103030. // Check
  103031. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  103032. return;
  103033. var engine = this._scene.getEngine();
  103034. this.onBeforeRenderObservable.notifyObservers(this);
  103035. // Render
  103036. engine.enableEffect(currentEffect);
  103037. engine.setState(false);
  103038. // Texture
  103039. currentEffect.setTexture("textureSampler", this.texture);
  103040. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  103041. // Color
  103042. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  103043. // Scale / offset
  103044. currentEffect.setVector2("offset", this.offset);
  103045. currentEffect.setVector2("scale", this.scale);
  103046. // VBOs
  103047. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  103048. // Draw order
  103049. if (!this.alphaTest) {
  103050. engine.setAlphaMode(this.alphaBlendingMode);
  103051. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  103052. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  103053. }
  103054. else {
  103055. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  103056. }
  103057. this.onAfterRenderObservable.notifyObservers(this);
  103058. };
  103059. Layer.prototype.dispose = function () {
  103060. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  103061. if (vertexBuffer) {
  103062. vertexBuffer.dispose();
  103063. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  103064. }
  103065. if (this._indexBuffer) {
  103066. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  103067. this._indexBuffer = null;
  103068. }
  103069. if (this.texture) {
  103070. this.texture.dispose();
  103071. this.texture = null;
  103072. }
  103073. // Remove from scene
  103074. var index = this._scene.layers.indexOf(this);
  103075. this._scene.layers.splice(index, 1);
  103076. // Callback
  103077. this.onDisposeObservable.notifyObservers(this);
  103078. this.onDisposeObservable.clear();
  103079. this.onAfterRenderObservable.clear();
  103080. this.onBeforeRenderObservable.clear();
  103081. };
  103082. return Layer;
  103083. }());
  103084. BABYLON.Layer = Layer;
  103085. })(BABYLON || (BABYLON = {}));
  103086. //# sourceMappingURL=babylon.layer.js.map
  103087. var BABYLON;
  103088. (function (BABYLON) {
  103089. var TextureTools = /** @class */ (function () {
  103090. function TextureTools() {
  103091. }
  103092. /**
  103093. * Uses the GPU to create a copy texture rescaled at a given size
  103094. * @param texture Texture to copy from
  103095. * @param width Desired width
  103096. * @param height Desired height
  103097. * @return Generated texture
  103098. */
  103099. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  103100. if (useBilinearMode === void 0) { useBilinearMode = true; }
  103101. var scene = texture.getScene();
  103102. var engine = scene.getEngine();
  103103. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  103104. rtt.wrapU = texture.wrapU;
  103105. rtt.wrapV = texture.wrapV;
  103106. rtt.uOffset = texture.uOffset;
  103107. rtt.vOffset = texture.vOffset;
  103108. rtt.uScale = texture.uScale;
  103109. rtt.vScale = texture.vScale;
  103110. rtt.uAng = texture.uAng;
  103111. rtt.vAng = texture.vAng;
  103112. rtt.wAng = texture.wAng;
  103113. rtt.coordinatesIndex = texture.coordinatesIndex;
  103114. rtt.level = texture.level;
  103115. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  103116. rtt._texture.isReady = false;
  103117. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103118. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103119. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  103120. passPostProcess.getEffect().executeWhenCompiled(function () {
  103121. passPostProcess.onApply = function (effect) {
  103122. effect.setTexture("textureSampler", texture);
  103123. };
  103124. var internalTexture = rtt.getInternalTexture();
  103125. if (internalTexture) {
  103126. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  103127. engine.unBindFramebuffer(internalTexture);
  103128. rtt.disposeFramebufferObjects();
  103129. passPostProcess.dispose();
  103130. internalTexture.isReady = true;
  103131. }
  103132. });
  103133. return rtt;
  103134. };
  103135. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  103136. if (!scene._environmentBRDFTexture) {
  103137. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  103138. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103139. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103140. scene._environmentBRDFTexture = texture;
  103141. }
  103142. return scene._environmentBRDFTexture;
  103143. };
  103144. 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=";
  103145. return TextureTools;
  103146. }());
  103147. BABYLON.TextureTools = TextureTools;
  103148. })(BABYLON || (BABYLON = {}));
  103149. //# sourceMappingURL=babylon.textureTools.js.map
  103150. var BABYLON;
  103151. (function (BABYLON) {
  103152. var FramingBehavior = /** @class */ (function () {
  103153. function FramingBehavior() {
  103154. this._mode = FramingBehavior.FitFrustumSidesMode;
  103155. this._radiusScale = 1.0;
  103156. this._positionScale = 0.5;
  103157. this._defaultElevation = 0.3;
  103158. this._elevationReturnTime = 1500;
  103159. this._elevationReturnWaitTime = 1000;
  103160. this._zoomStopsAnimation = false;
  103161. this._framingTime = 1500;
  103162. this._isPointerDown = false;
  103163. this._lastInteractionTime = -Infinity;
  103164. // Framing control
  103165. this._animatables = new Array();
  103166. this._betaIsAnimating = false;
  103167. }
  103168. Object.defineProperty(FramingBehavior.prototype, "name", {
  103169. get: function () {
  103170. return "Framing";
  103171. },
  103172. enumerable: true,
  103173. configurable: true
  103174. });
  103175. Object.defineProperty(FramingBehavior.prototype, "mode", {
  103176. /**
  103177. * Gets current mode used by the behavior.
  103178. */
  103179. get: function () {
  103180. return this._mode;
  103181. },
  103182. /**
  103183. * Sets the current mode used by the behavior
  103184. */
  103185. set: function (mode) {
  103186. this._mode = mode;
  103187. },
  103188. enumerable: true,
  103189. configurable: true
  103190. });
  103191. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  103192. /**
  103193. * Gets the scale applied to the radius
  103194. */
  103195. get: function () {
  103196. return this._radiusScale;
  103197. },
  103198. /**
  103199. * Sets the scale applied to the radius (1 by default)
  103200. */
  103201. set: function (radius) {
  103202. this._radiusScale = radius;
  103203. },
  103204. enumerable: true,
  103205. configurable: true
  103206. });
  103207. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  103208. /**
  103209. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  103210. */
  103211. get: function () {
  103212. return this._positionScale;
  103213. },
  103214. /**
  103215. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  103216. */
  103217. set: function (scale) {
  103218. this._positionScale = scale;
  103219. },
  103220. enumerable: true,
  103221. configurable: true
  103222. });
  103223. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  103224. /**
  103225. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  103226. * behaviour is triggered, in radians.
  103227. */
  103228. get: function () {
  103229. return this._defaultElevation;
  103230. },
  103231. /**
  103232. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  103233. * behaviour is triggered, in radians.
  103234. */
  103235. set: function (elevation) {
  103236. this._defaultElevation = elevation;
  103237. },
  103238. enumerable: true,
  103239. configurable: true
  103240. });
  103241. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  103242. /**
  103243. * Gets the time (in milliseconds) taken to return to the default beta position.
  103244. * Negative value indicates camera should not return to default.
  103245. */
  103246. get: function () {
  103247. return this._elevationReturnTime;
  103248. },
  103249. /**
  103250. * Sets the time (in milliseconds) taken to return to the default beta position.
  103251. * Negative value indicates camera should not return to default.
  103252. */
  103253. set: function (speed) {
  103254. this._elevationReturnTime = speed;
  103255. },
  103256. enumerable: true,
  103257. configurable: true
  103258. });
  103259. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  103260. /**
  103261. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  103262. */
  103263. get: function () {
  103264. return this._elevationReturnWaitTime;
  103265. },
  103266. /**
  103267. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  103268. */
  103269. set: function (time) {
  103270. this._elevationReturnWaitTime = time;
  103271. },
  103272. enumerable: true,
  103273. configurable: true
  103274. });
  103275. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  103276. /**
  103277. * Gets the flag that indicates if user zooming should stop animation.
  103278. */
  103279. get: function () {
  103280. return this._zoomStopsAnimation;
  103281. },
  103282. /**
  103283. * Sets the flag that indicates if user zooming should stop animation.
  103284. */
  103285. set: function (flag) {
  103286. this._zoomStopsAnimation = flag;
  103287. },
  103288. enumerable: true,
  103289. configurable: true
  103290. });
  103291. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  103292. /**
  103293. * Gets the transition time when framing the mesh, in milliseconds
  103294. */
  103295. get: function () {
  103296. return this._framingTime;
  103297. },
  103298. /**
  103299. * Sets the transition time when framing the mesh, in milliseconds
  103300. */
  103301. set: function (time) {
  103302. this._framingTime = time;
  103303. },
  103304. enumerable: true,
  103305. configurable: true
  103306. });
  103307. FramingBehavior.prototype.init = function () {
  103308. // Do notihng
  103309. };
  103310. FramingBehavior.prototype.attach = function (camera) {
  103311. var _this = this;
  103312. this._attachedCamera = camera;
  103313. var scene = this._attachedCamera.getScene();
  103314. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  103315. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  103316. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  103317. _this._isPointerDown = true;
  103318. return;
  103319. }
  103320. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  103321. _this._isPointerDown = false;
  103322. }
  103323. });
  103324. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  103325. if (mesh) {
  103326. _this.zoomOnMesh(mesh);
  103327. }
  103328. });
  103329. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  103330. // Stop the animation if there is user interaction and the animation should stop for this interaction
  103331. _this._applyUserInteraction();
  103332. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  103333. // back to the default position after a given timeout
  103334. _this._maintainCameraAboveGround();
  103335. });
  103336. };
  103337. FramingBehavior.prototype.detach = function () {
  103338. if (!this._attachedCamera) {
  103339. return;
  103340. }
  103341. var scene = this._attachedCamera.getScene();
  103342. if (this._onPrePointerObservableObserver) {
  103343. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  103344. }
  103345. if (this._onAfterCheckInputsObserver) {
  103346. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  103347. }
  103348. if (this._onMeshTargetChangedObserver) {
  103349. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  103350. }
  103351. this._attachedCamera = null;
  103352. };
  103353. /**
  103354. * Targets the given mesh and updates zoom level accordingly.
  103355. * @param mesh The mesh to target.
  103356. * @param radius Optional. If a cached radius position already exists, overrides default.
  103357. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  103358. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  103359. * @param onAnimationEnd Callback triggered at the end of the framing animation
  103360. */
  103361. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  103362. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  103363. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  103364. mesh.computeWorldMatrix(true);
  103365. var boundingBox = mesh.getBoundingInfo().boundingBox;
  103366. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  103367. };
  103368. /**
  103369. * Targets the given mesh with its children and updates zoom level accordingly.
  103370. * @param mesh The mesh to target.
  103371. * @param radius Optional. If a cached radius position already exists, overrides default.
  103372. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  103373. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  103374. * @param onAnimationEnd Callback triggered at the end of the framing animation
  103375. */
  103376. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  103377. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  103378. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  103379. mesh.computeWorldMatrix(true);
  103380. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  103381. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  103382. };
  103383. /**
  103384. * Targets the given meshes with their children and updates zoom level accordingly.
  103385. * @param meshes The mesh to target.
  103386. * @param radius Optional. If a cached radius position already exists, overrides default.
  103387. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  103388. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  103389. * @param onAnimationEnd Callback triggered at the end of the framing animation
  103390. */
  103391. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  103392. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  103393. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  103394. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  103395. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  103396. for (var i = 0; i < meshes.length; i++) {
  103397. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  103398. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  103399. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  103400. }
  103401. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  103402. };
  103403. /**
  103404. * Targets the given mesh and updates zoom level accordingly.
  103405. * @param mesh The mesh to target.
  103406. * @param radius Optional. If a cached radius position already exists, overrides default.
  103407. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  103408. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  103409. * @param onAnimationEnd Callback triggered at the end of the framing animation
  103410. */
  103411. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  103412. var _this = this;
  103413. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  103414. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  103415. var zoomTarget;
  103416. if (!this._attachedCamera) {
  103417. return;
  103418. }
  103419. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  103420. var bottom = minimumWorld.y;
  103421. var top = maximumWorld.y;
  103422. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  103423. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  103424. if (focusOnOriginXZ) {
  103425. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  103426. }
  103427. else {
  103428. var centerWorld = minimumWorld.add(radiusWorld);
  103429. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  103430. }
  103431. if (!this._vectorTransition) {
  103432. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  103433. }
  103434. this._betaIsAnimating = true;
  103435. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  103436. if (animatable) {
  103437. this._animatables.push(animatable);
  103438. }
  103439. // sets the radius and lower radius bounds
  103440. // Small delta ensures camera is not always at lower zoom limit.
  103441. var radius = 0;
  103442. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  103443. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  103444. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  103445. radius = position;
  103446. }
  103447. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  103448. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  103449. if (this._attachedCamera.lowerRadiusLimit === null) {
  103450. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  103451. }
  103452. }
  103453. // Set sensibilities
  103454. var extend = maximumWorld.subtract(minimumWorld).length();
  103455. this._attachedCamera.panningSensibility = 5000 / extend;
  103456. this._attachedCamera.wheelPrecision = 100 / radius;
  103457. // transition to new radius
  103458. if (!this._radiusTransition) {
  103459. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  103460. }
  103461. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  103462. _this.stopAllAnimations();
  103463. if (onAnimationEnd) {
  103464. onAnimationEnd();
  103465. }
  103466. if (_this._attachedCamera) {
  103467. _this._attachedCamera.storeState();
  103468. }
  103469. });
  103470. if (animatable) {
  103471. this._animatables.push(animatable);
  103472. }
  103473. };
  103474. /**
  103475. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  103476. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  103477. * frustum width.
  103478. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  103479. * to fully enclose the mesh in the viewing frustum.
  103480. */
  103481. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  103482. var size = maximumWorld.subtract(minimumWorld);
  103483. var boxVectorGlobalDiagonal = size.length();
  103484. var frustumSlope = this._getFrustumSlope();
  103485. // Formula for setting distance
  103486. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  103487. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  103488. // Horizon distance
  103489. var radius = radiusWithoutFraming * this._radiusScale;
  103490. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  103491. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  103492. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  103493. var camera = this._attachedCamera;
  103494. if (!camera) {
  103495. return 0;
  103496. }
  103497. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  103498. // Don't exceed the requested limit
  103499. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  103500. }
  103501. // Don't exceed the upper radius limit
  103502. if (camera.upperRadiusLimit) {
  103503. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  103504. }
  103505. return distance;
  103506. };
  103507. /**
  103508. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  103509. * is automatically returned to its default position (expected to be above ground plane).
  103510. */
  103511. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  103512. var _this = this;
  103513. if (this._elevationReturnTime < 0) {
  103514. return;
  103515. }
  103516. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  103517. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  103518. var limitBeta = Math.PI * 0.5;
  103519. // Bring the camera back up if below the ground plane
  103520. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  103521. this._betaIsAnimating = true;
  103522. //Transition to new position
  103523. this.stopAllAnimations();
  103524. if (!this._betaTransition) {
  103525. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  103526. }
  103527. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  103528. _this._clearAnimationLocks();
  103529. _this.stopAllAnimations();
  103530. });
  103531. if (animatabe) {
  103532. this._animatables.push(animatabe);
  103533. }
  103534. }
  103535. };
  103536. /**
  103537. * Returns the frustum slope based on the canvas ratio and camera FOV
  103538. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  103539. */
  103540. FramingBehavior.prototype._getFrustumSlope = function () {
  103541. // Calculate the viewport ratio
  103542. // Aspect Ratio is Height/Width.
  103543. var camera = this._attachedCamera;
  103544. if (!camera) {
  103545. return BABYLON.Vector2.Zero();
  103546. }
  103547. var engine = camera.getScene().getEngine();
  103548. var aspectRatio = engine.getAspectRatio(camera);
  103549. // Camera FOV is the vertical field of view (top-bottom) in radians.
  103550. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  103551. var frustumSlopeY = Math.tan(camera.fov / 2);
  103552. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  103553. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  103554. // along the forward vector.
  103555. var frustumSlopeX = frustumSlopeY * aspectRatio;
  103556. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  103557. };
  103558. /**
  103559. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  103560. */
  103561. FramingBehavior.prototype._clearAnimationLocks = function () {
  103562. this._betaIsAnimating = false;
  103563. };
  103564. /**
  103565. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  103566. */
  103567. FramingBehavior.prototype._applyUserInteraction = function () {
  103568. if (this.isUserIsMoving) {
  103569. this._lastInteractionTime = BABYLON.Tools.Now;
  103570. this.stopAllAnimations();
  103571. this._clearAnimationLocks();
  103572. }
  103573. };
  103574. /**
  103575. * Stops and removes all animations that have been applied to the camera
  103576. */
  103577. FramingBehavior.prototype.stopAllAnimations = function () {
  103578. if (this._attachedCamera) {
  103579. this._attachedCamera.animations = [];
  103580. }
  103581. while (this._animatables.length) {
  103582. if (this._animatables[0]) {
  103583. this._animatables[0].onAnimationEnd = null;
  103584. this._animatables[0].stop();
  103585. }
  103586. this._animatables.shift();
  103587. }
  103588. };
  103589. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  103590. /**
  103591. * Gets a value indicating if the user is moving the camera
  103592. */
  103593. get: function () {
  103594. if (!this._attachedCamera) {
  103595. return false;
  103596. }
  103597. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  103598. this._attachedCamera.inertialBetaOffset !== 0 ||
  103599. this._attachedCamera.inertialRadiusOffset !== 0 ||
  103600. this._attachedCamera.inertialPanningX !== 0 ||
  103601. this._attachedCamera.inertialPanningY !== 0 ||
  103602. this._isPointerDown;
  103603. },
  103604. enumerable: true,
  103605. configurable: true
  103606. });
  103607. /**
  103608. * The easing function used by animations
  103609. */
  103610. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  103611. /**
  103612. * The easing mode used by animations
  103613. */
  103614. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  103615. // Statics
  103616. /**
  103617. * The camera can move all the way towards the mesh.
  103618. */
  103619. FramingBehavior.IgnoreBoundsSizeMode = 0;
  103620. /**
  103621. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  103622. */
  103623. FramingBehavior.FitFrustumSidesMode = 1;
  103624. return FramingBehavior;
  103625. }());
  103626. BABYLON.FramingBehavior = FramingBehavior;
  103627. })(BABYLON || (BABYLON = {}));
  103628. //# sourceMappingURL=babylon.framingBehavior.js.map
  103629. var BABYLON;
  103630. (function (BABYLON) {
  103631. /**
  103632. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  103633. */
  103634. var BouncingBehavior = /** @class */ (function () {
  103635. function BouncingBehavior() {
  103636. /**
  103637. * The duration of the animation, in milliseconds
  103638. */
  103639. this.transitionDuration = 450;
  103640. /**
  103641. * Length of the distance animated by the transition when lower radius is reached
  103642. */
  103643. this.lowerRadiusTransitionRange = 2;
  103644. /**
  103645. * Length of the distance animated by the transition when upper radius is reached
  103646. */
  103647. this.upperRadiusTransitionRange = -2;
  103648. this._autoTransitionRange = false;
  103649. // Animations
  103650. this._radiusIsAnimating = false;
  103651. this._radiusBounceTransition = null;
  103652. this._animatables = new Array();
  103653. }
  103654. Object.defineProperty(BouncingBehavior.prototype, "name", {
  103655. get: function () {
  103656. return "Bouncing";
  103657. },
  103658. enumerable: true,
  103659. configurable: true
  103660. });
  103661. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  103662. /**
  103663. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  103664. */
  103665. get: function () {
  103666. return this._autoTransitionRange;
  103667. },
  103668. /**
  103669. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  103670. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  103671. */
  103672. set: function (value) {
  103673. var _this = this;
  103674. if (this._autoTransitionRange === value) {
  103675. return;
  103676. }
  103677. this._autoTransitionRange = value;
  103678. var camera = this._attachedCamera;
  103679. if (!camera) {
  103680. return;
  103681. }
  103682. if (value) {
  103683. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  103684. if (!mesh) {
  103685. return;
  103686. }
  103687. mesh.computeWorldMatrix(true);
  103688. var diagonal = mesh.getBoundingInfo().diagonalLength;
  103689. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  103690. _this.upperRadiusTransitionRange = diagonal * 0.05;
  103691. });
  103692. }
  103693. else if (this._onMeshTargetChangedObserver) {
  103694. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  103695. }
  103696. },
  103697. enumerable: true,
  103698. configurable: true
  103699. });
  103700. BouncingBehavior.prototype.init = function () {
  103701. // Do notihng
  103702. };
  103703. BouncingBehavior.prototype.attach = function (camera) {
  103704. var _this = this;
  103705. this._attachedCamera = camera;
  103706. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  103707. if (!_this._attachedCamera) {
  103708. return;
  103709. }
  103710. // Add the bounce animation to the lower radius limit
  103711. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  103712. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  103713. }
  103714. // Add the bounce animation to the upper radius limit
  103715. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  103716. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  103717. }
  103718. });
  103719. };
  103720. BouncingBehavior.prototype.detach = function () {
  103721. if (!this._attachedCamera) {
  103722. return;
  103723. }
  103724. if (this._onAfterCheckInputsObserver) {
  103725. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  103726. }
  103727. if (this._onMeshTargetChangedObserver) {
  103728. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  103729. }
  103730. this._attachedCamera = null;
  103731. };
  103732. /**
  103733. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  103734. * @param radiusLimit The limit to check against.
  103735. * @return Bool to indicate if at limit.
  103736. */
  103737. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  103738. if (!this._attachedCamera) {
  103739. return false;
  103740. }
  103741. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  103742. return true;
  103743. }
  103744. return false;
  103745. };
  103746. /**
  103747. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  103748. * @param radiusDelta The delta by which to animate to. Can be negative.
  103749. */
  103750. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  103751. var _this = this;
  103752. if (!this._attachedCamera) {
  103753. return;
  103754. }
  103755. if (!this._radiusBounceTransition) {
  103756. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  103757. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  103758. }
  103759. // Prevent zoom until bounce has completed
  103760. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  103761. this._attachedCamera.wheelPrecision = Infinity;
  103762. this._attachedCamera.inertialRadiusOffset = 0;
  103763. // Animate to the radius limit
  103764. this.stopAllAnimations();
  103765. this._radiusIsAnimating = true;
  103766. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  103767. if (animatable) {
  103768. this._animatables.push(animatable);
  103769. }
  103770. };
  103771. /**
  103772. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  103773. */
  103774. BouncingBehavior.prototype._clearAnimationLocks = function () {
  103775. this._radiusIsAnimating = false;
  103776. if (this._attachedCamera) {
  103777. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  103778. }
  103779. };
  103780. /**
  103781. * Stops and removes all animations that have been applied to the camera
  103782. */
  103783. BouncingBehavior.prototype.stopAllAnimations = function () {
  103784. if (this._attachedCamera) {
  103785. this._attachedCamera.animations = [];
  103786. }
  103787. while (this._animatables.length) {
  103788. this._animatables[0].onAnimationEnd = null;
  103789. this._animatables[0].stop();
  103790. this._animatables.shift();
  103791. }
  103792. };
  103793. /**
  103794. * The easing function used by animations
  103795. */
  103796. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  103797. /**
  103798. * The easing mode used by animations
  103799. */
  103800. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  103801. return BouncingBehavior;
  103802. }());
  103803. BABYLON.BouncingBehavior = BouncingBehavior;
  103804. })(BABYLON || (BABYLON = {}));
  103805. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  103806. var BABYLON;
  103807. (function (BABYLON) {
  103808. var AutoRotationBehavior = /** @class */ (function () {
  103809. function AutoRotationBehavior() {
  103810. this._zoomStopsAnimation = false;
  103811. this._idleRotationSpeed = 0.05;
  103812. this._idleRotationWaitTime = 2000;
  103813. this._idleRotationSpinupTime = 2000;
  103814. this._isPointerDown = false;
  103815. this._lastFrameTime = null;
  103816. this._lastInteractionTime = -Infinity;
  103817. this._cameraRotationSpeed = 0;
  103818. this._lastFrameRadius = 0;
  103819. }
  103820. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  103821. get: function () {
  103822. return "AutoRotation";
  103823. },
  103824. enumerable: true,
  103825. configurable: true
  103826. });
  103827. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  103828. /**
  103829. * Gets the flag that indicates if user zooming should stop animation.
  103830. */
  103831. get: function () {
  103832. return this._zoomStopsAnimation;
  103833. },
  103834. /**
  103835. * Sets the flag that indicates if user zooming should stop animation.
  103836. */
  103837. set: function (flag) {
  103838. this._zoomStopsAnimation = flag;
  103839. },
  103840. enumerable: true,
  103841. configurable: true
  103842. });
  103843. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  103844. /**
  103845. * Gets the default speed at which the camera rotates around the model.
  103846. */
  103847. get: function () {
  103848. return this._idleRotationSpeed;
  103849. },
  103850. /**
  103851. * Sets the default speed at which the camera rotates around the model.
  103852. */
  103853. set: function (speed) {
  103854. this._idleRotationSpeed = speed;
  103855. },
  103856. enumerable: true,
  103857. configurable: true
  103858. });
  103859. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  103860. /**
  103861. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  103862. */
  103863. get: function () {
  103864. return this._idleRotationWaitTime;
  103865. },
  103866. /**
  103867. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  103868. */
  103869. set: function (time) {
  103870. this._idleRotationWaitTime = time;
  103871. },
  103872. enumerable: true,
  103873. configurable: true
  103874. });
  103875. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  103876. /**
  103877. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  103878. */
  103879. get: function () {
  103880. return this._idleRotationSpinupTime;
  103881. },
  103882. /**
  103883. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  103884. */
  103885. set: function (time) {
  103886. this._idleRotationSpinupTime = time;
  103887. },
  103888. enumerable: true,
  103889. configurable: true
  103890. });
  103891. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  103892. /**
  103893. * Gets a value indicating if the camera is currently rotating because of this behavior
  103894. */
  103895. get: function () {
  103896. return Math.abs(this._cameraRotationSpeed) > 0;
  103897. },
  103898. enumerable: true,
  103899. configurable: true
  103900. });
  103901. AutoRotationBehavior.prototype.init = function () {
  103902. // Do notihng
  103903. };
  103904. AutoRotationBehavior.prototype.attach = function (camera) {
  103905. var _this = this;
  103906. this._attachedCamera = camera;
  103907. var scene = this._attachedCamera.getScene();
  103908. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  103909. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  103910. _this._isPointerDown = true;
  103911. return;
  103912. }
  103913. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  103914. _this._isPointerDown = false;
  103915. }
  103916. });
  103917. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  103918. var now = BABYLON.Tools.Now;
  103919. var dt = 0;
  103920. if (_this._lastFrameTime != null) {
  103921. dt = now - _this._lastFrameTime;
  103922. }
  103923. _this._lastFrameTime = now;
  103924. // Stop the animation if there is user interaction and the animation should stop for this interaction
  103925. _this._applyUserInteraction();
  103926. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  103927. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  103928. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  103929. // Step camera rotation by rotation speed
  103930. if (_this._attachedCamera) {
  103931. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  103932. }
  103933. });
  103934. };
  103935. AutoRotationBehavior.prototype.detach = function () {
  103936. if (!this._attachedCamera) {
  103937. return;
  103938. }
  103939. var scene = this._attachedCamera.getScene();
  103940. if (this._onPrePointerObservableObserver) {
  103941. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  103942. }
  103943. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  103944. this._attachedCamera = null;
  103945. };
  103946. /**
  103947. * Returns true if user is scrolling.
  103948. * @return true if user is scrolling.
  103949. */
  103950. AutoRotationBehavior.prototype._userIsZooming = function () {
  103951. if (!this._attachedCamera) {
  103952. return false;
  103953. }
  103954. return this._attachedCamera.inertialRadiusOffset !== 0;
  103955. };
  103956. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  103957. if (!this._attachedCamera) {
  103958. return false;
  103959. }
  103960. var zoomHasHitLimit = false;
  103961. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  103962. zoomHasHitLimit = true;
  103963. }
  103964. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  103965. this._lastFrameRadius = this._attachedCamera.radius;
  103966. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  103967. };
  103968. /**
  103969. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  103970. */
  103971. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  103972. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  103973. this._lastInteractionTime = BABYLON.Tools.Now;
  103974. }
  103975. };
  103976. // Tools
  103977. AutoRotationBehavior.prototype._userIsMoving = function () {
  103978. if (!this._attachedCamera) {
  103979. return false;
  103980. }
  103981. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  103982. this._attachedCamera.inertialBetaOffset !== 0 ||
  103983. this._attachedCamera.inertialRadiusOffset !== 0 ||
  103984. this._attachedCamera.inertialPanningX !== 0 ||
  103985. this._attachedCamera.inertialPanningY !== 0 ||
  103986. this._isPointerDown;
  103987. };
  103988. return AutoRotationBehavior;
  103989. }());
  103990. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  103991. })(BABYLON || (BABYLON = {}));
  103992. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  103993. var BABYLON;
  103994. (function (BABYLON) {
  103995. var NullEngineOptions = /** @class */ (function () {
  103996. function NullEngineOptions() {
  103997. this.renderWidth = 512;
  103998. this.renderHeight = 256;
  103999. this.textureSize = 512;
  104000. this.deterministicLockstep = false;
  104001. this.lockstepMaxSteps = 4;
  104002. }
  104003. return NullEngineOptions;
  104004. }());
  104005. BABYLON.NullEngineOptions = NullEngineOptions;
  104006. /**
  104007. * The null engine class provides support for headless version of babylon.js.
  104008. * This can be used in server side scenario or for testing purposes
  104009. */
  104010. var NullEngine = /** @class */ (function (_super) {
  104011. __extends(NullEngine, _super);
  104012. function NullEngine(options) {
  104013. if (options === void 0) { options = new NullEngineOptions(); }
  104014. var _this = _super.call(this, null) || this;
  104015. if (options.deterministicLockstep === undefined) {
  104016. options.deterministicLockstep = false;
  104017. }
  104018. if (options.lockstepMaxSteps === undefined) {
  104019. options.lockstepMaxSteps = 4;
  104020. }
  104021. _this._options = options;
  104022. // Init caps
  104023. // We consider we are on a webgl1 capable device
  104024. _this._caps = new BABYLON.EngineCapabilities();
  104025. _this._caps.maxTexturesImageUnits = 16;
  104026. _this._caps.maxVertexTextureImageUnits = 16;
  104027. _this._caps.maxTextureSize = 512;
  104028. _this._caps.maxCubemapTextureSize = 512;
  104029. _this._caps.maxRenderTextureSize = 512;
  104030. _this._caps.maxVertexAttribs = 16;
  104031. _this._caps.maxVaryingVectors = 16;
  104032. _this._caps.maxFragmentUniformVectors = 16;
  104033. _this._caps.maxVertexUniformVectors = 16;
  104034. // Extensions
  104035. _this._caps.standardDerivatives = false;
  104036. _this._caps.astc = null;
  104037. _this._caps.s3tc = null;
  104038. _this._caps.pvrtc = null;
  104039. _this._caps.etc1 = null;
  104040. _this._caps.etc2 = null;
  104041. _this._caps.textureAnisotropicFilterExtension = null;
  104042. _this._caps.maxAnisotropy = 0;
  104043. _this._caps.uintIndices = false;
  104044. _this._caps.fragmentDepthSupported = false;
  104045. _this._caps.highPrecisionShaderSupported = true;
  104046. _this._caps.colorBufferFloat = false;
  104047. _this._caps.textureFloat = false;
  104048. _this._caps.textureFloatLinearFiltering = false;
  104049. _this._caps.textureFloatRender = false;
  104050. _this._caps.textureHalfFloat = false;
  104051. _this._caps.textureHalfFloatLinearFiltering = false;
  104052. _this._caps.textureHalfFloatRender = false;
  104053. _this._caps.textureLOD = false;
  104054. _this._caps.drawBuffersExtension = false;
  104055. _this._caps.depthTextureExtension = false;
  104056. _this._caps.vertexArrayObject = false;
  104057. _this._caps.instancedArrays = false;
  104058. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  104059. // Wrappers
  104060. if (typeof URL === "undefined") {
  104061. URL = {
  104062. createObjectURL: function () { },
  104063. revokeObjectURL: function () { }
  104064. };
  104065. }
  104066. if (typeof Blob === "undefined") {
  104067. Blob = function () { };
  104068. }
  104069. return _this;
  104070. }
  104071. NullEngine.prototype.isDeterministicLockStep = function () {
  104072. return this._options.deterministicLockstep;
  104073. };
  104074. NullEngine.prototype.getLockstepMaxSteps = function () {
  104075. return this._options.lockstepMaxSteps;
  104076. };
  104077. NullEngine.prototype.getHardwareScalingLevel = function () {
  104078. return 1.0;
  104079. };
  104080. NullEngine.prototype.createVertexBuffer = function (vertices) {
  104081. return {
  104082. capacity: 0,
  104083. references: 1,
  104084. is32Bits: false
  104085. };
  104086. };
  104087. NullEngine.prototype.createIndexBuffer = function (indices) {
  104088. return {
  104089. capacity: 0,
  104090. references: 1,
  104091. is32Bits: false
  104092. };
  104093. };
  104094. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  104095. if (stencil === void 0) { stencil = false; }
  104096. };
  104097. NullEngine.prototype.getRenderWidth = function (useScreen) {
  104098. if (useScreen === void 0) { useScreen = false; }
  104099. if (!useScreen && this._currentRenderTarget) {
  104100. return this._currentRenderTarget.width;
  104101. }
  104102. return this._options.renderWidth;
  104103. };
  104104. NullEngine.prototype.getRenderHeight = function (useScreen) {
  104105. if (useScreen === void 0) { useScreen = false; }
  104106. if (!useScreen && this._currentRenderTarget) {
  104107. return this._currentRenderTarget.height;
  104108. }
  104109. return this._options.renderHeight;
  104110. };
  104111. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  104112. this._cachedViewport = viewport;
  104113. };
  104114. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  104115. return {
  104116. transformFeedback: null,
  104117. __SPECTOR_rebuildProgram: null
  104118. };
  104119. };
  104120. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  104121. return [];
  104122. };
  104123. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  104124. return [];
  104125. };
  104126. NullEngine.prototype.bindSamplers = function (effect) {
  104127. this._currentEffect = null;
  104128. };
  104129. NullEngine.prototype.enableEffect = function (effect) {
  104130. this._currentEffect = effect;
  104131. if (effect.onBind) {
  104132. effect.onBind(effect);
  104133. }
  104134. if (effect._onBindObservable) {
  104135. effect._onBindObservable.notifyObservers(effect);
  104136. }
  104137. };
  104138. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  104139. if (zOffset === void 0) { zOffset = 0; }
  104140. if (reverseSide === void 0) { reverseSide = false; }
  104141. };
  104142. NullEngine.prototype.setIntArray = function (uniform, array) {
  104143. };
  104144. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  104145. };
  104146. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  104147. };
  104148. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  104149. };
  104150. NullEngine.prototype.setFloatArray = function (uniform, array) {
  104151. };
  104152. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  104153. };
  104154. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  104155. };
  104156. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  104157. };
  104158. NullEngine.prototype.setArray = function (uniform, array) {
  104159. };
  104160. NullEngine.prototype.setArray2 = function (uniform, array) {
  104161. };
  104162. NullEngine.prototype.setArray3 = function (uniform, array) {
  104163. };
  104164. NullEngine.prototype.setArray4 = function (uniform, array) {
  104165. };
  104166. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  104167. };
  104168. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  104169. };
  104170. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  104171. };
  104172. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  104173. };
  104174. NullEngine.prototype.setFloat = function (uniform, value) {
  104175. };
  104176. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  104177. };
  104178. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  104179. };
  104180. NullEngine.prototype.setBool = function (uniform, bool) {
  104181. };
  104182. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  104183. };
  104184. NullEngine.prototype.setColor3 = function (uniform, color3) {
  104185. };
  104186. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  104187. };
  104188. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  104189. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  104190. if (this._alphaMode === mode) {
  104191. return;
  104192. }
  104193. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  104194. if (!noDepthWriteChange) {
  104195. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  104196. }
  104197. this._alphaMode = mode;
  104198. };
  104199. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  104200. };
  104201. NullEngine.prototype.wipeCaches = function (bruteForce) {
  104202. if (this.preventCacheWipeBetweenFrames) {
  104203. return;
  104204. }
  104205. this.resetTextureCache();
  104206. this._currentEffect = null;
  104207. if (bruteForce) {
  104208. this._currentProgram = null;
  104209. this._stencilState.reset();
  104210. this._depthCullingState.reset();
  104211. this._alphaState.reset();
  104212. }
  104213. this._cachedVertexBuffers = null;
  104214. this._cachedIndexBuffer = null;
  104215. this._cachedEffectForVertexBuffers = null;
  104216. };
  104217. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  104218. };
  104219. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  104220. };
  104221. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  104222. };
  104223. /** @hidden */
  104224. NullEngine.prototype._createTexture = function () {
  104225. return {};
  104226. };
  104227. /** @hidden */
  104228. NullEngine.prototype._releaseTexture = function (texture) {
  104229. };
  104230. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  104231. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  104232. if (onLoad === void 0) { onLoad = null; }
  104233. if (onError === void 0) { onError = null; }
  104234. if (buffer === void 0) { buffer = null; }
  104235. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  104236. var url = String(urlArg);
  104237. texture.url = url;
  104238. texture.generateMipMaps = !noMipmap;
  104239. texture.samplingMode = samplingMode;
  104240. texture.invertY = invertY;
  104241. texture.baseWidth = this._options.textureSize;
  104242. texture.baseHeight = this._options.textureSize;
  104243. texture.width = this._options.textureSize;
  104244. texture.height = this._options.textureSize;
  104245. if (format) {
  104246. texture.format = format;
  104247. }
  104248. texture.isReady = true;
  104249. if (onLoad) {
  104250. onLoad();
  104251. }
  104252. this._internalTexturesCache.push(texture);
  104253. return texture;
  104254. };
  104255. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  104256. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  104257. if (options !== undefined && typeof options === "object") {
  104258. fullOptions.generateMipMaps = options.generateMipMaps;
  104259. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  104260. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  104261. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  104262. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  104263. }
  104264. else {
  104265. fullOptions.generateMipMaps = options;
  104266. fullOptions.generateDepthBuffer = true;
  104267. fullOptions.generateStencilBuffer = false;
  104268. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  104269. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  104270. }
  104271. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  104272. var width = size.width || size;
  104273. var height = size.height || size;
  104274. texture._depthStencilBuffer = {};
  104275. texture._framebuffer = {};
  104276. texture.baseWidth = width;
  104277. texture.baseHeight = height;
  104278. texture.width = width;
  104279. texture.height = height;
  104280. texture.isReady = true;
  104281. texture.samples = 1;
  104282. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  104283. texture.samplingMode = fullOptions.samplingMode;
  104284. texture.type = fullOptions.type;
  104285. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  104286. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  104287. this._internalTexturesCache.push(texture);
  104288. return texture;
  104289. };
  104290. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  104291. texture.samplingMode = samplingMode;
  104292. };
  104293. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  104294. if (this._currentRenderTarget) {
  104295. this.unBindFramebuffer(this._currentRenderTarget);
  104296. }
  104297. this._currentRenderTarget = texture;
  104298. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  104299. if (this._cachedViewport && !forceFullscreenViewport) {
  104300. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  104301. }
  104302. };
  104303. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  104304. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  104305. this._currentRenderTarget = null;
  104306. if (onBeforeUnbind) {
  104307. if (texture._MSAAFramebuffer) {
  104308. this._currentFramebuffer = texture._framebuffer;
  104309. }
  104310. onBeforeUnbind();
  104311. }
  104312. this._currentFramebuffer = null;
  104313. };
  104314. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  104315. var vbo = {
  104316. capacity: 1,
  104317. references: 1,
  104318. is32Bits: false
  104319. };
  104320. return vbo;
  104321. };
  104322. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  104323. if (premulAlpha === void 0) { premulAlpha = false; }
  104324. };
  104325. /**
  104326. * @hidden
  104327. * Get the current error code of the webGL context
  104328. * @returns the error code
  104329. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  104330. */
  104331. NullEngine.prototype.getError = function () {
  104332. return 0;
  104333. };
  104334. /** @hidden */
  104335. NullEngine.prototype._getUnpackAlignement = function () {
  104336. return 1;
  104337. };
  104338. /** @hidden */
  104339. NullEngine.prototype._unpackFlipY = function (value) {
  104340. };
  104341. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  104342. if (offset === void 0) { offset = 0; }
  104343. };
  104344. /**
  104345. * Updates a dynamic vertex buffer.
  104346. * @param vertexBuffer the vertex buffer to update
  104347. * @param data the data used to update the vertex buffer
  104348. * @param byteOffset the byte offset of the data (optional)
  104349. * @param byteLength the byte length of the data (optional)
  104350. */
  104351. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  104352. };
  104353. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  104354. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  104355. this._boundTexturesCache[this._activeChannel] = texture;
  104356. return true;
  104357. }
  104358. return false;
  104359. };
  104360. /** @hidden */
  104361. NullEngine.prototype._bindTexture = function (channel, texture) {
  104362. if (channel < 0) {
  104363. return;
  104364. }
  104365. this._bindTextureDirectly(0, texture);
  104366. };
  104367. /** @hidden */
  104368. NullEngine.prototype._releaseBuffer = function (buffer) {
  104369. buffer.references--;
  104370. if (buffer.references === 0) {
  104371. return true;
  104372. }
  104373. return false;
  104374. };
  104375. NullEngine.prototype.releaseEffects = function () {
  104376. };
  104377. NullEngine.prototype.displayLoadingUI = function () {
  104378. };
  104379. NullEngine.prototype.hideLoadingUI = function () {
  104380. };
  104381. /** @hidden */
  104382. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  104383. if (faceIndex === void 0) { faceIndex = 0; }
  104384. if (lod === void 0) { lod = 0; }
  104385. };
  104386. /** @hidden */
  104387. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  104388. if (faceIndex === void 0) { faceIndex = 0; }
  104389. if (lod === void 0) { lod = 0; }
  104390. };
  104391. /** @hidden */
  104392. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  104393. if (faceIndex === void 0) { faceIndex = 0; }
  104394. if (lod === void 0) { lod = 0; }
  104395. };
  104396. /** @hidden */
  104397. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  104398. if (faceIndex === void 0) { faceIndex = 0; }
  104399. if (lod === void 0) { lod = 0; }
  104400. };
  104401. return NullEngine;
  104402. }(BABYLON.Engine));
  104403. BABYLON.NullEngine = NullEngine;
  104404. })(BABYLON || (BABYLON = {}));
  104405. //# sourceMappingURL=babylon.nullEngine.js.map
  104406. var BABYLON;
  104407. (function (BABYLON) {
  104408. /**
  104409. * This class can be used to get instrumentation data from a Babylon engine
  104410. */
  104411. var EngineInstrumentation = /** @class */ (function () {
  104412. function EngineInstrumentation(engine) {
  104413. this.engine = engine;
  104414. this._captureGPUFrameTime = false;
  104415. this._gpuFrameTime = new BABYLON.PerfCounter();
  104416. this._captureShaderCompilationTime = false;
  104417. this._shaderCompilationTime = new BABYLON.PerfCounter();
  104418. // Observers
  104419. this._onBeginFrameObserver = null;
  104420. this._onEndFrameObserver = null;
  104421. this._onBeforeShaderCompilationObserver = null;
  104422. this._onAfterShaderCompilationObserver = null;
  104423. }
  104424. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  104425. // Properties
  104426. /**
  104427. * Gets the perf counter used for GPU frame time
  104428. */
  104429. get: function () {
  104430. return this._gpuFrameTime;
  104431. },
  104432. enumerable: true,
  104433. configurable: true
  104434. });
  104435. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  104436. /**
  104437. * Gets the GPU frame time capture status
  104438. */
  104439. get: function () {
  104440. return this._captureGPUFrameTime;
  104441. },
  104442. /**
  104443. * Enable or disable the GPU frame time capture
  104444. */
  104445. set: function (value) {
  104446. var _this = this;
  104447. if (value === this._captureGPUFrameTime) {
  104448. return;
  104449. }
  104450. this._captureGPUFrameTime = value;
  104451. if (value) {
  104452. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  104453. if (!_this._gpuFrameTimeToken) {
  104454. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  104455. }
  104456. });
  104457. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  104458. if (!_this._gpuFrameTimeToken) {
  104459. return;
  104460. }
  104461. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  104462. if (time > -1) {
  104463. _this._gpuFrameTimeToken = null;
  104464. _this._gpuFrameTime.fetchNewFrame();
  104465. _this._gpuFrameTime.addCount(time, true);
  104466. }
  104467. });
  104468. }
  104469. else {
  104470. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  104471. this._onBeginFrameObserver = null;
  104472. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  104473. this._onEndFrameObserver = null;
  104474. }
  104475. },
  104476. enumerable: true,
  104477. configurable: true
  104478. });
  104479. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  104480. /**
  104481. * Gets the perf counter used for shader compilation time
  104482. */
  104483. get: function () {
  104484. return this._shaderCompilationTime;
  104485. },
  104486. enumerable: true,
  104487. configurable: true
  104488. });
  104489. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  104490. /**
  104491. * Gets the shader compilation time capture status
  104492. */
  104493. get: function () {
  104494. return this._captureShaderCompilationTime;
  104495. },
  104496. /**
  104497. * Enable or disable the shader compilation time capture
  104498. */
  104499. set: function (value) {
  104500. var _this = this;
  104501. if (value === this._captureShaderCompilationTime) {
  104502. return;
  104503. }
  104504. this._captureShaderCompilationTime = value;
  104505. if (value) {
  104506. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  104507. _this._shaderCompilationTime.fetchNewFrame();
  104508. _this._shaderCompilationTime.beginMonitoring();
  104509. });
  104510. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  104511. _this._shaderCompilationTime.endMonitoring();
  104512. });
  104513. }
  104514. else {
  104515. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  104516. this._onBeforeShaderCompilationObserver = null;
  104517. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  104518. this._onAfterShaderCompilationObserver = null;
  104519. }
  104520. },
  104521. enumerable: true,
  104522. configurable: true
  104523. });
  104524. EngineInstrumentation.prototype.dispose = function () {
  104525. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  104526. this._onBeginFrameObserver = null;
  104527. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  104528. this._onEndFrameObserver = null;
  104529. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  104530. this._onBeforeShaderCompilationObserver = null;
  104531. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  104532. this._onAfterShaderCompilationObserver = null;
  104533. this.engine = null;
  104534. };
  104535. return EngineInstrumentation;
  104536. }());
  104537. BABYLON.EngineInstrumentation = EngineInstrumentation;
  104538. })(BABYLON || (BABYLON = {}));
  104539. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  104540. var BABYLON;
  104541. (function (BABYLON) {
  104542. /**
  104543. * This class can be used to get instrumentation data from a Babylon engine
  104544. */
  104545. var SceneInstrumentation = /** @class */ (function () {
  104546. function SceneInstrumentation(scene) {
  104547. var _this = this;
  104548. this.scene = scene;
  104549. this._captureActiveMeshesEvaluationTime = false;
  104550. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  104551. this._captureRenderTargetsRenderTime = false;
  104552. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  104553. this._captureFrameTime = false;
  104554. this._frameTime = new BABYLON.PerfCounter();
  104555. this._captureRenderTime = false;
  104556. this._renderTime = new BABYLON.PerfCounter();
  104557. this._captureInterFrameTime = false;
  104558. this._interFrameTime = new BABYLON.PerfCounter();
  104559. this._captureParticlesRenderTime = false;
  104560. this._particlesRenderTime = new BABYLON.PerfCounter();
  104561. this._captureSpritesRenderTime = false;
  104562. this._spritesRenderTime = new BABYLON.PerfCounter();
  104563. this._capturePhysicsTime = false;
  104564. this._physicsTime = new BABYLON.PerfCounter();
  104565. this._captureAnimationsTime = false;
  104566. this._animationsTime = new BABYLON.PerfCounter();
  104567. this._captureCameraRenderTime = false;
  104568. this._cameraRenderTime = new BABYLON.PerfCounter();
  104569. // Observers
  104570. this._onBeforeActiveMeshesEvaluationObserver = null;
  104571. this._onAfterActiveMeshesEvaluationObserver = null;
  104572. this._onBeforeRenderTargetsRenderObserver = null;
  104573. this._onAfterRenderTargetsRenderObserver = null;
  104574. this._onAfterRenderObserver = null;
  104575. this._onBeforeDrawPhaseObserver = null;
  104576. this._onAfterDrawPhaseObserver = null;
  104577. this._onBeforeAnimationsObserver = null;
  104578. this._onBeforeParticlesRenderingObserver = null;
  104579. this._onAfterParticlesRenderingObserver = null;
  104580. this._onBeforeSpritesRenderingObserver = null;
  104581. this._onAfterSpritesRenderingObserver = null;
  104582. this._onBeforePhysicsObserver = null;
  104583. this._onAfterPhysicsObserver = null;
  104584. this._onAfterAnimationsObserver = null;
  104585. this._onBeforeCameraRenderObserver = null;
  104586. this._onAfterCameraRenderObserver = null;
  104587. // Before render
  104588. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  104589. if (_this._captureActiveMeshesEvaluationTime) {
  104590. _this._activeMeshesEvaluationTime.fetchNewFrame();
  104591. }
  104592. if (_this._captureRenderTargetsRenderTime) {
  104593. _this._renderTargetsRenderTime.fetchNewFrame();
  104594. }
  104595. if (_this._captureFrameTime) {
  104596. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  104597. _this._frameTime.beginMonitoring();
  104598. }
  104599. if (_this._captureInterFrameTime) {
  104600. _this._interFrameTime.endMonitoring();
  104601. }
  104602. if (_this._captureParticlesRenderTime) {
  104603. _this._particlesRenderTime.fetchNewFrame();
  104604. }
  104605. if (_this._captureSpritesRenderTime) {
  104606. _this._spritesRenderTime.fetchNewFrame();
  104607. }
  104608. if (_this._captureAnimationsTime) {
  104609. _this._animationsTime.beginMonitoring();
  104610. }
  104611. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  104612. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  104613. });
  104614. // After render
  104615. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  104616. if (_this._captureFrameTime) {
  104617. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  104618. _this._frameTime.endMonitoring();
  104619. }
  104620. if (_this._captureRenderTime) {
  104621. _this._renderTime.endMonitoring(false);
  104622. }
  104623. if (_this._captureInterFrameTime) {
  104624. _this._interFrameTime.beginMonitoring();
  104625. }
  104626. });
  104627. }
  104628. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  104629. // Properties
  104630. /**
  104631. * Gets the perf counter used for active meshes evaluation time
  104632. */
  104633. get: function () {
  104634. return this._activeMeshesEvaluationTime;
  104635. },
  104636. enumerable: true,
  104637. configurable: true
  104638. });
  104639. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  104640. /**
  104641. * Gets the active meshes evaluation time capture status
  104642. */
  104643. get: function () {
  104644. return this._captureActiveMeshesEvaluationTime;
  104645. },
  104646. /**
  104647. * Enable or disable the active meshes evaluation time capture
  104648. */
  104649. set: function (value) {
  104650. var _this = this;
  104651. if (value === this._captureActiveMeshesEvaluationTime) {
  104652. return;
  104653. }
  104654. this._captureActiveMeshesEvaluationTime = value;
  104655. if (value) {
  104656. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  104657. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  104658. _this._activeMeshesEvaluationTime.beginMonitoring();
  104659. });
  104660. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  104661. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  104662. _this._activeMeshesEvaluationTime.endMonitoring();
  104663. });
  104664. }
  104665. else {
  104666. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  104667. this._onBeforeActiveMeshesEvaluationObserver = null;
  104668. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  104669. this._onAfterActiveMeshesEvaluationObserver = null;
  104670. }
  104671. },
  104672. enumerable: true,
  104673. configurable: true
  104674. });
  104675. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  104676. /**
  104677. * Gets the perf counter used for render targets render time
  104678. */
  104679. get: function () {
  104680. return this._renderTargetsRenderTime;
  104681. },
  104682. enumerable: true,
  104683. configurable: true
  104684. });
  104685. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  104686. /**
  104687. * Gets the render targets render time capture status
  104688. */
  104689. get: function () {
  104690. return this._captureRenderTargetsRenderTime;
  104691. },
  104692. /**
  104693. * Enable or disable the render targets render time capture
  104694. */
  104695. set: function (value) {
  104696. var _this = this;
  104697. if (value === this._captureRenderTargetsRenderTime) {
  104698. return;
  104699. }
  104700. this._captureRenderTargetsRenderTime = value;
  104701. if (value) {
  104702. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  104703. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  104704. _this._renderTargetsRenderTime.beginMonitoring();
  104705. });
  104706. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  104707. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  104708. _this._renderTargetsRenderTime.endMonitoring(false);
  104709. });
  104710. }
  104711. else {
  104712. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  104713. this._onBeforeRenderTargetsRenderObserver = null;
  104714. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  104715. this._onAfterRenderTargetsRenderObserver = null;
  104716. }
  104717. },
  104718. enumerable: true,
  104719. configurable: true
  104720. });
  104721. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  104722. /**
  104723. * Gets the perf counter used for particles render time
  104724. */
  104725. get: function () {
  104726. return this._particlesRenderTime;
  104727. },
  104728. enumerable: true,
  104729. configurable: true
  104730. });
  104731. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  104732. /**
  104733. * Gets the particles render time capture status
  104734. */
  104735. get: function () {
  104736. return this._captureParticlesRenderTime;
  104737. },
  104738. /**
  104739. * Enable or disable the particles render time capture
  104740. */
  104741. set: function (value) {
  104742. var _this = this;
  104743. if (value === this._captureParticlesRenderTime) {
  104744. return;
  104745. }
  104746. this._captureParticlesRenderTime = value;
  104747. if (value) {
  104748. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  104749. BABYLON.Tools.StartPerformanceCounter("Particles");
  104750. _this._particlesRenderTime.beginMonitoring();
  104751. });
  104752. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  104753. BABYLON.Tools.EndPerformanceCounter("Particles");
  104754. _this._particlesRenderTime.endMonitoring(false);
  104755. });
  104756. }
  104757. else {
  104758. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  104759. this._onBeforeParticlesRenderingObserver = null;
  104760. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  104761. this._onAfterParticlesRenderingObserver = null;
  104762. }
  104763. },
  104764. enumerable: true,
  104765. configurable: true
  104766. });
  104767. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  104768. /**
  104769. * Gets the perf counter used for sprites render time
  104770. */
  104771. get: function () {
  104772. return this._spritesRenderTime;
  104773. },
  104774. enumerable: true,
  104775. configurable: true
  104776. });
  104777. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  104778. /**
  104779. * Gets the sprites render time capture status
  104780. */
  104781. get: function () {
  104782. return this._captureSpritesRenderTime;
  104783. },
  104784. /**
  104785. * Enable or disable the sprites render time capture
  104786. */
  104787. set: function (value) {
  104788. var _this = this;
  104789. if (value === this._captureSpritesRenderTime) {
  104790. return;
  104791. }
  104792. this._captureSpritesRenderTime = value;
  104793. if (value) {
  104794. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  104795. BABYLON.Tools.StartPerformanceCounter("Sprites");
  104796. _this._spritesRenderTime.beginMonitoring();
  104797. });
  104798. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  104799. BABYLON.Tools.EndPerformanceCounter("Sprites");
  104800. _this._spritesRenderTime.endMonitoring(false);
  104801. });
  104802. }
  104803. else {
  104804. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  104805. this._onBeforeSpritesRenderingObserver = null;
  104806. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  104807. this._onAfterSpritesRenderingObserver = null;
  104808. }
  104809. },
  104810. enumerable: true,
  104811. configurable: true
  104812. });
  104813. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  104814. /**
  104815. * Gets the perf counter used for physics time
  104816. */
  104817. get: function () {
  104818. return this._physicsTime;
  104819. },
  104820. enumerable: true,
  104821. configurable: true
  104822. });
  104823. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  104824. /**
  104825. * Gets the physics time capture status
  104826. */
  104827. get: function () {
  104828. return this._capturePhysicsTime;
  104829. },
  104830. /**
  104831. * Enable or disable the physics time capture
  104832. */
  104833. set: function (value) {
  104834. var _this = this;
  104835. if (value === this._capturePhysicsTime) {
  104836. return;
  104837. }
  104838. this._capturePhysicsTime = value;
  104839. if (value) {
  104840. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  104841. BABYLON.Tools.StartPerformanceCounter("Physics");
  104842. _this._physicsTime.beginMonitoring();
  104843. });
  104844. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  104845. BABYLON.Tools.EndPerformanceCounter("Physics");
  104846. _this._physicsTime.endMonitoring();
  104847. });
  104848. }
  104849. else {
  104850. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  104851. this._onBeforePhysicsObserver = null;
  104852. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  104853. this._onAfterPhysicsObserver = null;
  104854. }
  104855. },
  104856. enumerable: true,
  104857. configurable: true
  104858. });
  104859. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  104860. /**
  104861. * Gets the perf counter used for animations time
  104862. */
  104863. get: function () {
  104864. return this._animationsTime;
  104865. },
  104866. enumerable: true,
  104867. configurable: true
  104868. });
  104869. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  104870. /**
  104871. * Gets the animations time capture status
  104872. */
  104873. get: function () {
  104874. return this._captureAnimationsTime;
  104875. },
  104876. /**
  104877. * Enable or disable the animations time capture
  104878. */
  104879. set: function (value) {
  104880. var _this = this;
  104881. if (value === this._captureAnimationsTime) {
  104882. return;
  104883. }
  104884. this._captureAnimationsTime = value;
  104885. if (value) {
  104886. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  104887. _this._animationsTime.endMonitoring();
  104888. });
  104889. }
  104890. else {
  104891. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  104892. this._onAfterAnimationsObserver = null;
  104893. }
  104894. },
  104895. enumerable: true,
  104896. configurable: true
  104897. });
  104898. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  104899. /**
  104900. * Gets the perf counter used for frame time capture
  104901. */
  104902. get: function () {
  104903. return this._frameTime;
  104904. },
  104905. enumerable: true,
  104906. configurable: true
  104907. });
  104908. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  104909. /**
  104910. * Gets the frame time capture status
  104911. */
  104912. get: function () {
  104913. return this._captureFrameTime;
  104914. },
  104915. /**
  104916. * Enable or disable the frame time capture
  104917. */
  104918. set: function (value) {
  104919. this._captureFrameTime = value;
  104920. },
  104921. enumerable: true,
  104922. configurable: true
  104923. });
  104924. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  104925. /**
  104926. * Gets the perf counter used for inter-frames time capture
  104927. */
  104928. get: function () {
  104929. return this._interFrameTime;
  104930. },
  104931. enumerable: true,
  104932. configurable: true
  104933. });
  104934. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  104935. /**
  104936. * Gets the inter-frames time capture status
  104937. */
  104938. get: function () {
  104939. return this._captureInterFrameTime;
  104940. },
  104941. /**
  104942. * Enable or disable the inter-frames time capture
  104943. */
  104944. set: function (value) {
  104945. this._captureInterFrameTime = value;
  104946. },
  104947. enumerable: true,
  104948. configurable: true
  104949. });
  104950. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  104951. /**
  104952. * Gets the perf counter used for render time capture
  104953. */
  104954. get: function () {
  104955. return this._renderTime;
  104956. },
  104957. enumerable: true,
  104958. configurable: true
  104959. });
  104960. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  104961. /**
  104962. * Gets the render time capture status
  104963. */
  104964. get: function () {
  104965. return this._captureRenderTime;
  104966. },
  104967. /**
  104968. * Enable or disable the render time capture
  104969. */
  104970. set: function (value) {
  104971. var _this = this;
  104972. if (value === this._captureRenderTime) {
  104973. return;
  104974. }
  104975. this._captureRenderTime = value;
  104976. if (value) {
  104977. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  104978. _this._renderTime.beginMonitoring();
  104979. BABYLON.Tools.StartPerformanceCounter("Main render");
  104980. });
  104981. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  104982. _this._renderTime.endMonitoring(false);
  104983. BABYLON.Tools.EndPerformanceCounter("Main render");
  104984. });
  104985. }
  104986. else {
  104987. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  104988. this._onBeforeDrawPhaseObserver = null;
  104989. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  104990. this._onAfterDrawPhaseObserver = null;
  104991. }
  104992. },
  104993. enumerable: true,
  104994. configurable: true
  104995. });
  104996. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  104997. /**
  104998. * Gets the perf counter used for camera render time capture
  104999. */
  105000. get: function () {
  105001. return this._cameraRenderTime;
  105002. },
  105003. enumerable: true,
  105004. configurable: true
  105005. });
  105006. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  105007. /**
  105008. * Gets the camera render time capture status
  105009. */
  105010. get: function () {
  105011. return this._captureCameraRenderTime;
  105012. },
  105013. /**
  105014. * Enable or disable the camera render time capture
  105015. */
  105016. set: function (value) {
  105017. var _this = this;
  105018. if (value === this._captureCameraRenderTime) {
  105019. return;
  105020. }
  105021. this._captureCameraRenderTime = value;
  105022. if (value) {
  105023. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  105024. _this._cameraRenderTime.beginMonitoring();
  105025. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  105026. });
  105027. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  105028. _this._cameraRenderTime.endMonitoring(false);
  105029. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  105030. });
  105031. }
  105032. else {
  105033. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  105034. this._onBeforeCameraRenderObserver = null;
  105035. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  105036. this._onAfterCameraRenderObserver = null;
  105037. }
  105038. },
  105039. enumerable: true,
  105040. configurable: true
  105041. });
  105042. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  105043. /**
  105044. * Gets the perf counter used for draw calls
  105045. */
  105046. get: function () {
  105047. return this.scene.getEngine()._drawCalls;
  105048. },
  105049. enumerable: true,
  105050. configurable: true
  105051. });
  105052. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  105053. /**
  105054. * Gets the perf counter used for texture collisions
  105055. */
  105056. get: function () {
  105057. return this.scene.getEngine()._textureCollisions;
  105058. },
  105059. enumerable: true,
  105060. configurable: true
  105061. });
  105062. SceneInstrumentation.prototype.dispose = function () {
  105063. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  105064. this._onAfterRenderObserver = null;
  105065. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  105066. this._onBeforeActiveMeshesEvaluationObserver = null;
  105067. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  105068. this._onAfterActiveMeshesEvaluationObserver = null;
  105069. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  105070. this._onBeforeRenderTargetsRenderObserver = null;
  105071. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  105072. this._onAfterRenderTargetsRenderObserver = null;
  105073. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  105074. this._onBeforeAnimationsObserver = null;
  105075. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  105076. this._onBeforeParticlesRenderingObserver = null;
  105077. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  105078. this._onAfterParticlesRenderingObserver = null;
  105079. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  105080. this._onBeforeSpritesRenderingObserver = null;
  105081. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  105082. this._onAfterSpritesRenderingObserver = null;
  105083. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  105084. this._onBeforeDrawPhaseObserver = null;
  105085. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  105086. this._onAfterDrawPhaseObserver = null;
  105087. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  105088. this._onBeforePhysicsObserver = null;
  105089. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  105090. this._onAfterPhysicsObserver = null;
  105091. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  105092. this._onAfterAnimationsObserver = null;
  105093. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  105094. this._onBeforeCameraRenderObserver = null;
  105095. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  105096. this._onAfterCameraRenderObserver = null;
  105097. this.scene = null;
  105098. };
  105099. return SceneInstrumentation;
  105100. }());
  105101. BABYLON.SceneInstrumentation = SceneInstrumentation;
  105102. })(BABYLON || (BABYLON = {}));
  105103. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  105104. var BABYLON;
  105105. (function (BABYLON) {
  105106. /**
  105107. * @hidden
  105108. **/
  105109. var _TimeToken = /** @class */ (function () {
  105110. function _TimeToken() {
  105111. this._timeElapsedQueryEnded = false;
  105112. }
  105113. return _TimeToken;
  105114. }());
  105115. BABYLON._TimeToken = _TimeToken;
  105116. })(BABYLON || (BABYLON = {}));
  105117. //# sourceMappingURL=babylon.timeToken.js.map
  105118. var BABYLON;
  105119. (function (BABYLON) {
  105120. /**
  105121. * Background material defines definition.
  105122. * @hidden Mainly internal Use
  105123. */
  105124. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  105125. __extends(BackgroundMaterialDefines, _super);
  105126. /**
  105127. * Constructor of the defines.
  105128. */
  105129. function BackgroundMaterialDefines() {
  105130. var _this = _super.call(this) || this;
  105131. /**
  105132. * True if the diffuse texture is in use.
  105133. */
  105134. _this.DIFFUSE = false;
  105135. /**
  105136. * The direct UV channel to use.
  105137. */
  105138. _this.DIFFUSEDIRECTUV = 0;
  105139. /**
  105140. * True if the diffuse texture is in gamma space.
  105141. */
  105142. _this.GAMMADIFFUSE = false;
  105143. /**
  105144. * True if the diffuse texture has opacity in the alpha channel.
  105145. */
  105146. _this.DIFFUSEHASALPHA = false;
  105147. /**
  105148. * True if you want the material to fade to transparent at grazing angle.
  105149. */
  105150. _this.OPACITYFRESNEL = false;
  105151. /**
  105152. * True if an extra blur needs to be added in the reflection.
  105153. */
  105154. _this.REFLECTIONBLUR = false;
  105155. /**
  105156. * True if you want the material to fade to reflection at grazing angle.
  105157. */
  105158. _this.REFLECTIONFRESNEL = false;
  105159. /**
  105160. * True if you want the material to falloff as far as you move away from the scene center.
  105161. */
  105162. _this.REFLECTIONFALLOFF = false;
  105163. /**
  105164. * False if the current Webgl implementation does not support the texture lod extension.
  105165. */
  105166. _this.TEXTURELODSUPPORT = false;
  105167. /**
  105168. * True to ensure the data are premultiplied.
  105169. */
  105170. _this.PREMULTIPLYALPHA = false;
  105171. /**
  105172. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  105173. */
  105174. _this.USERGBCOLOR = false;
  105175. /**
  105176. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  105177. * stays aligned with the desired configuration.
  105178. */
  105179. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  105180. /**
  105181. * True to add noise in order to reduce the banding effect.
  105182. */
  105183. _this.NOISE = false;
  105184. /**
  105185. * is the reflection texture in BGR color scheme?
  105186. * Mainly used to solve a bug in ios10 video tag
  105187. */
  105188. _this.REFLECTIONBGR = false;
  105189. _this.IMAGEPROCESSING = false;
  105190. _this.VIGNETTE = false;
  105191. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  105192. _this.VIGNETTEBLENDMODEOPAQUE = false;
  105193. _this.TONEMAPPING = false;
  105194. _this.TONEMAPPING_ACES = false;
  105195. _this.CONTRAST = false;
  105196. _this.COLORCURVES = false;
  105197. _this.COLORGRADING = false;
  105198. _this.COLORGRADING3D = false;
  105199. _this.SAMPLER3DGREENDEPTH = false;
  105200. _this.SAMPLER3DBGRMAP = false;
  105201. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  105202. _this.EXPOSURE = false;
  105203. // Reflection.
  105204. _this.REFLECTION = false;
  105205. _this.REFLECTIONMAP_3D = false;
  105206. _this.REFLECTIONMAP_SPHERICAL = false;
  105207. _this.REFLECTIONMAP_PLANAR = false;
  105208. _this.REFLECTIONMAP_CUBIC = false;
  105209. _this.REFLECTIONMAP_PROJECTION = false;
  105210. _this.REFLECTIONMAP_SKYBOX = false;
  105211. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  105212. _this.REFLECTIONMAP_EXPLICIT = false;
  105213. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  105214. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  105215. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  105216. _this.INVERTCUBICMAP = false;
  105217. _this.REFLECTIONMAP_OPPOSITEZ = false;
  105218. _this.LODINREFLECTIONALPHA = false;
  105219. _this.GAMMAREFLECTION = false;
  105220. _this.RGBDREFLECTION = false;
  105221. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  105222. // Default BJS.
  105223. _this.MAINUV1 = false;
  105224. _this.MAINUV2 = false;
  105225. _this.UV1 = false;
  105226. _this.UV2 = false;
  105227. _this.CLIPPLANE = false;
  105228. _this.CLIPPLANE2 = false;
  105229. _this.CLIPPLANE3 = false;
  105230. _this.CLIPPLANE4 = false;
  105231. _this.POINTSIZE = false;
  105232. _this.FOG = false;
  105233. _this.NORMAL = false;
  105234. _this.NUM_BONE_INFLUENCERS = 0;
  105235. _this.BonesPerMesh = 0;
  105236. _this.INSTANCES = false;
  105237. _this.SHADOWFLOAT = false;
  105238. _this.rebuild();
  105239. return _this;
  105240. }
  105241. return BackgroundMaterialDefines;
  105242. }(BABYLON.MaterialDefines));
  105243. /**
  105244. * Background material used to create an efficient environement around your scene.
  105245. */
  105246. var BackgroundMaterial = /** @class */ (function (_super) {
  105247. __extends(BackgroundMaterial, _super);
  105248. /**
  105249. * Instantiates a Background Material in the given scene
  105250. * @param name The friendly name of the material
  105251. * @param scene The scene to add the material to
  105252. */
  105253. function BackgroundMaterial(name, scene) {
  105254. var _this = _super.call(this, name, scene) || this;
  105255. /**
  105256. * Key light Color (multiply against the environement texture)
  105257. */
  105258. _this.primaryColor = BABYLON.Color3.White();
  105259. _this._primaryColorShadowLevel = 0;
  105260. _this._primaryColorHighlightLevel = 0;
  105261. /**
  105262. * Reflection Texture used in the material.
  105263. * Should be author in a specific way for the best result (refer to the documentation).
  105264. */
  105265. _this.reflectionTexture = null;
  105266. /**
  105267. * Reflection Texture level of blur.
  105268. *
  105269. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  105270. * texture twice.
  105271. */
  105272. _this.reflectionBlur = 0;
  105273. /**
  105274. * Diffuse Texture used in the material.
  105275. * Should be author in a specific way for the best result (refer to the documentation).
  105276. */
  105277. _this.diffuseTexture = null;
  105278. _this._shadowLights = null;
  105279. /**
  105280. * Specify the list of lights casting shadow on the material.
  105281. * All scene shadow lights will be included if null.
  105282. */
  105283. _this.shadowLights = null;
  105284. /**
  105285. * Helps adjusting the shadow to a softer level if required.
  105286. * 0 means black shadows and 1 means no shadows.
  105287. */
  105288. _this.shadowLevel = 0;
  105289. /**
  105290. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  105291. * It is usually zero but might be interesting to modify according to your setup.
  105292. */
  105293. _this.sceneCenter = BABYLON.Vector3.Zero();
  105294. /**
  105295. * This helps specifying that the material is falling off to the sky box at grazing angle.
  105296. * This helps ensuring a nice transition when the camera goes under the ground.
  105297. */
  105298. _this.opacityFresnel = true;
  105299. /**
  105300. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  105301. * This helps adding a mirror texture on the ground.
  105302. */
  105303. _this.reflectionFresnel = false;
  105304. /**
  105305. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  105306. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  105307. */
  105308. _this.reflectionFalloffDistance = 0.0;
  105309. /**
  105310. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  105311. */
  105312. _this.reflectionAmount = 1.0;
  105313. /**
  105314. * This specifies the weight of the reflection at grazing angle.
  105315. */
  105316. _this.reflectionReflectance0 = 0.05;
  105317. /**
  105318. * This specifies the weight of the reflection at a perpendicular point of view.
  105319. */
  105320. _this.reflectionReflectance90 = 0.5;
  105321. /**
  105322. * Helps to directly use the maps channels instead of their level.
  105323. */
  105324. _this.useRGBColor = true;
  105325. /**
  105326. * This helps reducing the banding effect that could occur on the background.
  105327. */
  105328. _this.enableNoise = false;
  105329. _this._fovMultiplier = 1.0;
  105330. /**
  105331. * Enable the FOV adjustment feature controlled by fovMultiplier.
  105332. */
  105333. _this.useEquirectangularFOV = false;
  105334. _this._maxSimultaneousLights = 4;
  105335. /**
  105336. * Number of Simultaneous lights allowed on the material.
  105337. */
  105338. _this.maxSimultaneousLights = 4;
  105339. /**
  105340. * Keep track of the image processing observer to allow dispose and replace.
  105341. */
  105342. _this._imageProcessingObserver = null;
  105343. /**
  105344. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  105345. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  105346. */
  105347. _this.switchToBGR = false;
  105348. // Temp values kept as cache in the material.
  105349. _this._renderTargets = new BABYLON.SmartArray(16);
  105350. _this._reflectionControls = BABYLON.Vector4.Zero();
  105351. _this._white = BABYLON.Color3.White();
  105352. _this._primaryShadowColor = BABYLON.Color3.Black();
  105353. _this._primaryHighlightColor = BABYLON.Color3.Black();
  105354. // Setup the default processing configuration to the scene.
  105355. _this._attachImageProcessingConfiguration(null);
  105356. _this.getRenderTargetTextures = function () {
  105357. _this._renderTargets.reset();
  105358. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  105359. _this._renderTargets.push(_this._diffuseTexture);
  105360. }
  105361. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  105362. _this._renderTargets.push(_this._reflectionTexture);
  105363. }
  105364. return _this._renderTargets;
  105365. };
  105366. return _this;
  105367. }
  105368. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  105369. /**
  105370. * Experimental Internal Use Only.
  105371. *
  105372. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  105373. * This acts as a helper to set the primary color to a more "human friendly" value.
  105374. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  105375. * output color as close as possible from the chosen value.
  105376. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  105377. * part of lighting setup.)
  105378. */
  105379. get: function () {
  105380. return this.__perceptualColor;
  105381. },
  105382. set: function (value) {
  105383. this.__perceptualColor = value;
  105384. this._computePrimaryColorFromPerceptualColor();
  105385. this._markAllSubMeshesAsLightsDirty();
  105386. },
  105387. enumerable: true,
  105388. configurable: true
  105389. });
  105390. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  105391. /**
  105392. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  105393. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  105394. */
  105395. get: function () {
  105396. return this._primaryColorShadowLevel;
  105397. },
  105398. set: function (value) {
  105399. this._primaryColorShadowLevel = value;
  105400. this._computePrimaryColors();
  105401. this._markAllSubMeshesAsLightsDirty();
  105402. },
  105403. enumerable: true,
  105404. configurable: true
  105405. });
  105406. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  105407. /**
  105408. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  105409. * The primary color is used at the level chosen to define what the white area would look.
  105410. */
  105411. get: function () {
  105412. return this._primaryColorHighlightLevel;
  105413. },
  105414. set: function (value) {
  105415. this._primaryColorHighlightLevel = value;
  105416. this._computePrimaryColors();
  105417. this._markAllSubMeshesAsLightsDirty();
  105418. },
  105419. enumerable: true,
  105420. configurable: true
  105421. });
  105422. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  105423. /**
  105424. * Sets the reflection reflectance fresnel values according to the default standard
  105425. * empirically know to work well :-)
  105426. */
  105427. set: function (value) {
  105428. var reflectionWeight = value;
  105429. if (reflectionWeight < 0.5) {
  105430. reflectionWeight = reflectionWeight * 2.0;
  105431. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  105432. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  105433. }
  105434. else {
  105435. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  105436. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  105437. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  105438. }
  105439. },
  105440. enumerable: true,
  105441. configurable: true
  105442. });
  105443. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  105444. /**
  105445. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  105446. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  105447. * Recommended to be keep at 1.0 except for special cases.
  105448. */
  105449. get: function () {
  105450. return this._fovMultiplier;
  105451. },
  105452. set: function (value) {
  105453. if (isNaN(value)) {
  105454. value = 1.0;
  105455. }
  105456. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  105457. },
  105458. enumerable: true,
  105459. configurable: true
  105460. });
  105461. /**
  105462. * Attaches a new image processing configuration to the PBR Material.
  105463. * @param configuration (if null the scene configuration will be use)
  105464. */
  105465. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  105466. var _this = this;
  105467. if (configuration === this._imageProcessingConfiguration) {
  105468. return;
  105469. }
  105470. // Detaches observer.
  105471. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  105472. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  105473. }
  105474. // Pick the scene configuration if needed.
  105475. if (!configuration) {
  105476. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  105477. }
  105478. else {
  105479. this._imageProcessingConfiguration = configuration;
  105480. }
  105481. // Attaches observer.
  105482. if (this._imageProcessingConfiguration) {
  105483. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  105484. _this._computePrimaryColorFromPerceptualColor();
  105485. _this._markAllSubMeshesAsImageProcessingDirty();
  105486. });
  105487. }
  105488. };
  105489. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  105490. /**
  105491. * Gets the image processing configuration used either in this material.
  105492. */
  105493. get: function () {
  105494. return this._imageProcessingConfiguration;
  105495. },
  105496. /**
  105497. * Sets the Default image processing configuration used either in the this material.
  105498. *
  105499. * If sets to null, the scene one is in use.
  105500. */
  105501. set: function (value) {
  105502. this._attachImageProcessingConfiguration(value);
  105503. // Ensure the effect will be rebuilt.
  105504. this._markAllSubMeshesAsTexturesDirty();
  105505. },
  105506. enumerable: true,
  105507. configurable: true
  105508. });
  105509. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  105510. /**
  105511. * Gets wether the color curves effect is enabled.
  105512. */
  105513. get: function () {
  105514. return this.imageProcessingConfiguration.colorCurvesEnabled;
  105515. },
  105516. /**
  105517. * Sets wether the color curves effect is enabled.
  105518. */
  105519. set: function (value) {
  105520. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  105521. },
  105522. enumerable: true,
  105523. configurable: true
  105524. });
  105525. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  105526. /**
  105527. * Gets wether the color grading effect is enabled.
  105528. */
  105529. get: function () {
  105530. return this.imageProcessingConfiguration.colorGradingEnabled;
  105531. },
  105532. /**
  105533. * Gets wether the color grading effect is enabled.
  105534. */
  105535. set: function (value) {
  105536. this.imageProcessingConfiguration.colorGradingEnabled = value;
  105537. },
  105538. enumerable: true,
  105539. configurable: true
  105540. });
  105541. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  105542. /**
  105543. * Gets wether tonemapping is enabled or not.
  105544. */
  105545. get: function () {
  105546. return this._imageProcessingConfiguration.toneMappingEnabled;
  105547. },
  105548. /**
  105549. * Sets wether tonemapping is enabled or not
  105550. */
  105551. set: function (value) {
  105552. this._imageProcessingConfiguration.toneMappingEnabled = value;
  105553. },
  105554. enumerable: true,
  105555. configurable: true
  105556. });
  105557. ;
  105558. ;
  105559. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  105560. /**
  105561. * The camera exposure used on this material.
  105562. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  105563. * This corresponds to a photographic exposure.
  105564. */
  105565. get: function () {
  105566. return this._imageProcessingConfiguration.exposure;
  105567. },
  105568. /**
  105569. * The camera exposure used on this material.
  105570. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  105571. * This corresponds to a photographic exposure.
  105572. */
  105573. set: function (value) {
  105574. this._imageProcessingConfiguration.exposure = value;
  105575. },
  105576. enumerable: true,
  105577. configurable: true
  105578. });
  105579. ;
  105580. ;
  105581. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  105582. /**
  105583. * Gets The camera contrast used on this material.
  105584. */
  105585. get: function () {
  105586. return this._imageProcessingConfiguration.contrast;
  105587. },
  105588. /**
  105589. * Sets The camera contrast used on this material.
  105590. */
  105591. set: function (value) {
  105592. this._imageProcessingConfiguration.contrast = value;
  105593. },
  105594. enumerable: true,
  105595. configurable: true
  105596. });
  105597. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  105598. /**
  105599. * Gets the Color Grading 2D Lookup Texture.
  105600. */
  105601. get: function () {
  105602. return this._imageProcessingConfiguration.colorGradingTexture;
  105603. },
  105604. /**
  105605. * Sets the Color Grading 2D Lookup Texture.
  105606. */
  105607. set: function (value) {
  105608. this.imageProcessingConfiguration.colorGradingTexture = value;
  105609. },
  105610. enumerable: true,
  105611. configurable: true
  105612. });
  105613. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  105614. /**
  105615. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  105616. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  105617. * 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;
  105618. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  105619. */
  105620. get: function () {
  105621. return this.imageProcessingConfiguration.colorCurves;
  105622. },
  105623. /**
  105624. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  105625. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  105626. * 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;
  105627. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  105628. */
  105629. set: function (value) {
  105630. this.imageProcessingConfiguration.colorCurves = value;
  105631. },
  105632. enumerable: true,
  105633. configurable: true
  105634. });
  105635. /**
  105636. * The entire material has been created in order to prevent overdraw.
  105637. * @returns false
  105638. */
  105639. BackgroundMaterial.prototype.needAlphaTesting = function () {
  105640. return true;
  105641. };
  105642. /**
  105643. * The entire material has been created in order to prevent overdraw.
  105644. * @returns true if blending is enable
  105645. */
  105646. BackgroundMaterial.prototype.needAlphaBlending = function () {
  105647. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  105648. };
  105649. /**
  105650. * Checks wether the material is ready to be rendered for a given mesh.
  105651. * @param mesh The mesh to render
  105652. * @param subMesh The submesh to check against
  105653. * @param useInstances Specify wether or not the material is used with instances
  105654. * @returns true if all the dependencies are ready (Textures, Effects...)
  105655. */
  105656. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  105657. var _this = this;
  105658. if (useInstances === void 0) { useInstances = false; }
  105659. if (subMesh.effect && this.isFrozen) {
  105660. if (this._wasPreviouslyReady) {
  105661. return true;
  105662. }
  105663. }
  105664. if (!subMesh._materialDefines) {
  105665. subMesh._materialDefines = new BackgroundMaterialDefines();
  105666. }
  105667. var scene = this.getScene();
  105668. var defines = subMesh._materialDefines;
  105669. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  105670. if (defines._renderId === scene.getRenderId()) {
  105671. return true;
  105672. }
  105673. }
  105674. var engine = scene.getEngine();
  105675. // Lights
  105676. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  105677. defines._needNormals = true;
  105678. // Textures
  105679. if (defines._areTexturesDirty) {
  105680. defines._needUVs = false;
  105681. if (scene.texturesEnabled) {
  105682. if (scene.getEngine().getCaps().textureLOD) {
  105683. defines.TEXTURELODSUPPORT = true;
  105684. }
  105685. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  105686. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  105687. return false;
  105688. }
  105689. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  105690. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  105691. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  105692. defines.OPACITYFRESNEL = this._opacityFresnel;
  105693. }
  105694. else {
  105695. defines.DIFFUSE = false;
  105696. defines.DIFFUSEHASALPHA = false;
  105697. defines.GAMMADIFFUSE = false;
  105698. defines.OPACITYFRESNEL = false;
  105699. }
  105700. var reflectionTexture = this._reflectionTexture;
  105701. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  105702. if (!reflectionTexture.isReadyOrNotBlocking()) {
  105703. return false;
  105704. }
  105705. defines.REFLECTION = true;
  105706. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  105707. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  105708. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  105709. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  105710. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  105711. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  105712. defines.REFLECTIONBGR = this.switchToBGR;
  105713. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  105714. defines.INVERTCUBICMAP = true;
  105715. }
  105716. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  105717. switch (reflectionTexture.coordinatesMode) {
  105718. case BABYLON.Texture.EXPLICIT_MODE:
  105719. defines.REFLECTIONMAP_EXPLICIT = true;
  105720. break;
  105721. case BABYLON.Texture.PLANAR_MODE:
  105722. defines.REFLECTIONMAP_PLANAR = true;
  105723. break;
  105724. case BABYLON.Texture.PROJECTION_MODE:
  105725. defines.REFLECTIONMAP_PROJECTION = true;
  105726. break;
  105727. case BABYLON.Texture.SKYBOX_MODE:
  105728. defines.REFLECTIONMAP_SKYBOX = true;
  105729. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  105730. break;
  105731. case BABYLON.Texture.SPHERICAL_MODE:
  105732. defines.REFLECTIONMAP_SPHERICAL = true;
  105733. break;
  105734. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  105735. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  105736. break;
  105737. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  105738. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  105739. break;
  105740. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  105741. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  105742. break;
  105743. case BABYLON.Texture.CUBIC_MODE:
  105744. case BABYLON.Texture.INVCUBIC_MODE:
  105745. default:
  105746. defines.REFLECTIONMAP_CUBIC = true;
  105747. break;
  105748. }
  105749. if (this.reflectionFresnel) {
  105750. defines.REFLECTIONFRESNEL = true;
  105751. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  105752. this._reflectionControls.x = this.reflectionAmount;
  105753. this._reflectionControls.y = this.reflectionReflectance0;
  105754. this._reflectionControls.z = this.reflectionReflectance90;
  105755. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  105756. }
  105757. else {
  105758. defines.REFLECTIONFRESNEL = false;
  105759. defines.REFLECTIONFALLOFF = false;
  105760. }
  105761. }
  105762. else {
  105763. defines.REFLECTION = false;
  105764. defines.REFLECTIONFRESNEL = false;
  105765. defines.REFLECTIONFALLOFF = false;
  105766. defines.REFLECTIONBLUR = false;
  105767. defines.REFLECTIONMAP_3D = false;
  105768. defines.REFLECTIONMAP_SPHERICAL = false;
  105769. defines.REFLECTIONMAP_PLANAR = false;
  105770. defines.REFLECTIONMAP_CUBIC = false;
  105771. defines.REFLECTIONMAP_PROJECTION = false;
  105772. defines.REFLECTIONMAP_SKYBOX = false;
  105773. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  105774. defines.REFLECTIONMAP_EXPLICIT = false;
  105775. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  105776. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  105777. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  105778. defines.INVERTCUBICMAP = false;
  105779. defines.REFLECTIONMAP_OPPOSITEZ = false;
  105780. defines.LODINREFLECTIONALPHA = false;
  105781. defines.GAMMAREFLECTION = false;
  105782. defines.RGBDREFLECTION = false;
  105783. }
  105784. }
  105785. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  105786. defines.USERGBCOLOR = this._useRGBColor;
  105787. defines.NOISE = this._enableNoise;
  105788. }
  105789. if (defines._areLightsDirty) {
  105790. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  105791. }
  105792. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  105793. if (!this._imageProcessingConfiguration.isReady()) {
  105794. return false;
  105795. }
  105796. this._imageProcessingConfiguration.prepareDefines(defines);
  105797. }
  105798. // Misc.
  105799. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  105800. // Values that need to be evaluated on every frame
  105801. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  105802. // Attribs
  105803. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  105804. if (mesh) {
  105805. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  105806. mesh.createNormals(true);
  105807. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  105808. }
  105809. }
  105810. }
  105811. // Get correct effect
  105812. if (defines.isDirty) {
  105813. defines.markAsProcessed();
  105814. scene.resetCachedMaterial();
  105815. // Fallbacks
  105816. var fallbacks = new BABYLON.EffectFallbacks();
  105817. if (defines.FOG) {
  105818. fallbacks.addFallback(0, "FOG");
  105819. }
  105820. if (defines.POINTSIZE) {
  105821. fallbacks.addFallback(1, "POINTSIZE");
  105822. }
  105823. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  105824. if (defines.NUM_BONE_INFLUENCERS > 0) {
  105825. fallbacks.addCPUSkinningFallback(0, mesh);
  105826. }
  105827. //Attributes
  105828. var attribs = [BABYLON.VertexBuffer.PositionKind];
  105829. if (defines.NORMAL) {
  105830. attribs.push(BABYLON.VertexBuffer.NormalKind);
  105831. }
  105832. if (defines.UV1) {
  105833. attribs.push(BABYLON.VertexBuffer.UVKind);
  105834. }
  105835. if (defines.UV2) {
  105836. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  105837. }
  105838. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  105839. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  105840. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  105841. "vFogInfos", "vFogColor", "pointSize",
  105842. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "mBones",
  105843. "vPrimaryColor", "vPrimaryColorShadow",
  105844. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  105845. "shadowLevel", "alpha",
  105846. "vBackgroundCenter", "vReflectionControl",
  105847. "vDiffuseInfos", "diffuseMatrix",
  105848. ];
  105849. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  105850. var uniformBuffers = ["Material", "Scene"];
  105851. if (BABYLON.ImageProcessingConfiguration) {
  105852. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  105853. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  105854. }
  105855. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  105856. uniformsNames: uniforms,
  105857. uniformBuffersNames: uniformBuffers,
  105858. samplers: samplers,
  105859. defines: defines,
  105860. maxSimultaneousLights: this._maxSimultaneousLights
  105861. });
  105862. var onCompiled = function (effect) {
  105863. if (_this.onCompiled) {
  105864. _this.onCompiled(effect);
  105865. }
  105866. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  105867. };
  105868. var join = defines.toString();
  105869. subMesh.setEffect(scene.getEngine().createEffect("background", {
  105870. attributes: attribs,
  105871. uniformsNames: uniforms,
  105872. uniformBuffersNames: uniformBuffers,
  105873. samplers: samplers,
  105874. defines: join,
  105875. fallbacks: fallbacks,
  105876. onCompiled: onCompiled,
  105877. onError: this.onError,
  105878. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  105879. }, engine), defines);
  105880. this.buildUniformLayout();
  105881. }
  105882. if (!subMesh.effect || !subMesh.effect.isReady()) {
  105883. return false;
  105884. }
  105885. defines._renderId = scene.getRenderId();
  105886. this._wasPreviouslyReady = true;
  105887. return true;
  105888. };
  105889. /**
  105890. * Compute the primary color according to the chosen perceptual color.
  105891. */
  105892. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  105893. if (!this.__perceptualColor) {
  105894. return;
  105895. }
  105896. this._primaryColor.copyFrom(this.__perceptualColor);
  105897. // Revert gamma space.
  105898. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  105899. // Revert image processing configuration.
  105900. if (this._imageProcessingConfiguration) {
  105901. // Revert Exposure.
  105902. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  105903. }
  105904. this._computePrimaryColors();
  105905. };
  105906. /**
  105907. * Compute the highlights and shadow colors according to their chosen levels.
  105908. */
  105909. BackgroundMaterial.prototype._computePrimaryColors = function () {
  105910. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  105911. return;
  105912. }
  105913. // Find the highlight color based on the configuration.
  105914. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  105915. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  105916. // Find the shadow color based on the configuration.
  105917. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  105918. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  105919. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  105920. };
  105921. /**
  105922. * Build the uniform buffer used in the material.
  105923. */
  105924. BackgroundMaterial.prototype.buildUniformLayout = function () {
  105925. // Order is important !
  105926. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  105927. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  105928. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  105929. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  105930. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  105931. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  105932. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  105933. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  105934. this._uniformBuffer.addUniform("pointSize", 1);
  105935. this._uniformBuffer.addUniform("shadowLevel", 1);
  105936. this._uniformBuffer.addUniform("alpha", 1);
  105937. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  105938. this._uniformBuffer.addUniform("vReflectionControl", 4);
  105939. this._uniformBuffer.create();
  105940. };
  105941. /**
  105942. * Unbind the material.
  105943. */
  105944. BackgroundMaterial.prototype.unbind = function () {
  105945. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  105946. this._uniformBuffer.setTexture("diffuseSampler", null);
  105947. }
  105948. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  105949. this._uniformBuffer.setTexture("reflectionSampler", null);
  105950. }
  105951. _super.prototype.unbind.call(this);
  105952. };
  105953. /**
  105954. * Bind only the world matrix to the material.
  105955. * @param world The world matrix to bind.
  105956. */
  105957. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  105958. this._activeEffect.setMatrix("world", world);
  105959. };
  105960. /**
  105961. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  105962. * @param world The world matrix to bind.
  105963. * @param subMesh The submesh to bind for.
  105964. */
  105965. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  105966. var scene = this.getScene();
  105967. var defines = subMesh._materialDefines;
  105968. if (!defines) {
  105969. return;
  105970. }
  105971. var effect = subMesh.effect;
  105972. if (!effect) {
  105973. return;
  105974. }
  105975. this._activeEffect = effect;
  105976. // Matrices
  105977. this.bindOnlyWorldMatrix(world);
  105978. // Bones
  105979. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  105980. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  105981. if (mustRebind) {
  105982. this._uniformBuffer.bindToEffect(effect, "Material");
  105983. this.bindViewProjection(effect);
  105984. var reflectionTexture = this._reflectionTexture;
  105985. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  105986. // Texture uniforms
  105987. if (scene.texturesEnabled) {
  105988. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  105989. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  105990. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  105991. }
  105992. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  105993. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  105994. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  105995. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  105996. }
  105997. }
  105998. if (this.shadowLevel > 0) {
  105999. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  106000. }
  106001. this._uniformBuffer.updateFloat("alpha", this.alpha);
  106002. // Point size
  106003. if (this.pointsCloud) {
  106004. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  106005. }
  106006. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  106007. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  106008. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  106009. }
  106010. else {
  106011. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  106012. }
  106013. }
  106014. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  106015. // Textures
  106016. if (scene.texturesEnabled) {
  106017. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  106018. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  106019. }
  106020. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  106021. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  106022. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  106023. }
  106024. else if (!defines.REFLECTIONBLUR) {
  106025. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  106026. }
  106027. else {
  106028. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  106029. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  106030. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  106031. }
  106032. if (defines.REFLECTIONFRESNEL) {
  106033. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  106034. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  106035. }
  106036. }
  106037. }
  106038. // Clip plane
  106039. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  106040. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  106041. }
  106042. if (mustRebind || !this.isFrozen) {
  106043. if (scene.lightsEnabled) {
  106044. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  106045. }
  106046. // View
  106047. this.bindView(effect);
  106048. // Fog
  106049. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  106050. // image processing
  106051. if (this._imageProcessingConfiguration) {
  106052. this._imageProcessingConfiguration.bind(this._activeEffect);
  106053. }
  106054. }
  106055. this._uniformBuffer.update();
  106056. this._afterBind(mesh, this._activeEffect);
  106057. };
  106058. /**
  106059. * Dispose the material.
  106060. * @param forceDisposeEffect Force disposal of the associated effect.
  106061. * @param forceDisposeTextures Force disposal of the associated textures.
  106062. */
  106063. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  106064. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  106065. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  106066. if (forceDisposeTextures) {
  106067. if (this.diffuseTexture) {
  106068. this.diffuseTexture.dispose();
  106069. }
  106070. if (this.reflectionTexture) {
  106071. this.reflectionTexture.dispose();
  106072. }
  106073. }
  106074. this._renderTargets.dispose();
  106075. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  106076. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  106077. }
  106078. _super.prototype.dispose.call(this, forceDisposeEffect);
  106079. };
  106080. /**
  106081. * Clones the material.
  106082. * @param name The cloned name.
  106083. * @returns The cloned material.
  106084. */
  106085. BackgroundMaterial.prototype.clone = function (name) {
  106086. var _this = this;
  106087. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  106088. };
  106089. /**
  106090. * Serializes the current material to its JSON representation.
  106091. * @returns The JSON representation.
  106092. */
  106093. BackgroundMaterial.prototype.serialize = function () {
  106094. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  106095. serializationObject.customType = "BABYLON.BackgroundMaterial";
  106096. return serializationObject;
  106097. };
  106098. /**
  106099. * Gets the class name of the material
  106100. * @returns "BackgroundMaterial"
  106101. */
  106102. BackgroundMaterial.prototype.getClassName = function () {
  106103. return "BackgroundMaterial";
  106104. };
  106105. /**
  106106. * Parse a JSON input to create back a background material.
  106107. * @param source The JSON data to parse
  106108. * @param scene The scene to create the parsed material in
  106109. * @param rootUrl The root url of the assets the material depends upon
  106110. * @returns the instantiated BackgroundMaterial.
  106111. */
  106112. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  106113. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  106114. };
  106115. /**
  106116. * Standard reflectance value at parallel view angle.
  106117. */
  106118. BackgroundMaterial.StandardReflectance0 = 0.05;
  106119. /**
  106120. * Standard reflectance value at grazing angle.
  106121. */
  106122. BackgroundMaterial.StandardReflectance90 = 0.5;
  106123. __decorate([
  106124. BABYLON.serializeAsColor3()
  106125. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  106126. __decorate([
  106127. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  106128. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  106129. __decorate([
  106130. BABYLON.serializeAsColor3()
  106131. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  106132. __decorate([
  106133. BABYLON.serialize()
  106134. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  106135. __decorate([
  106136. BABYLON.serialize()
  106137. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  106138. __decorate([
  106139. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  106140. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  106141. __decorate([
  106142. BABYLON.serializeAsTexture()
  106143. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  106144. __decorate([
  106145. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106146. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  106147. __decorate([
  106148. BABYLON.serialize()
  106149. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  106150. __decorate([
  106151. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106152. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  106153. __decorate([
  106154. BABYLON.serializeAsTexture()
  106155. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  106156. __decorate([
  106157. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106158. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  106159. __decorate([
  106160. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106161. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  106162. __decorate([
  106163. BABYLON.serialize()
  106164. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  106165. __decorate([
  106166. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106167. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  106168. __decorate([
  106169. BABYLON.serializeAsVector3()
  106170. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  106171. __decorate([
  106172. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106173. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  106174. __decorate([
  106175. BABYLON.serialize()
  106176. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  106177. __decorate([
  106178. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106179. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  106180. __decorate([
  106181. BABYLON.serialize()
  106182. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  106183. __decorate([
  106184. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106185. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  106186. __decorate([
  106187. BABYLON.serialize()
  106188. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  106189. __decorate([
  106190. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106191. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  106192. __decorate([
  106193. BABYLON.serialize()
  106194. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  106195. __decorate([
  106196. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106197. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  106198. __decorate([
  106199. BABYLON.serialize()
  106200. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  106201. __decorate([
  106202. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106203. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  106204. __decorate([
  106205. BABYLON.serialize()
  106206. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  106207. __decorate([
  106208. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106209. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  106210. __decorate([
  106211. BABYLON.serialize()
  106212. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  106213. __decorate([
  106214. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106215. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  106216. __decorate([
  106217. BABYLON.serialize()
  106218. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  106219. __decorate([
  106220. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106221. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  106222. __decorate([
  106223. BABYLON.serialize()
  106224. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  106225. __decorate([
  106226. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106227. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  106228. __decorate([
  106229. BABYLON.serializeAsImageProcessingConfiguration()
  106230. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  106231. return BackgroundMaterial;
  106232. }(BABYLON.PushMaterial));
  106233. BABYLON.BackgroundMaterial = BackgroundMaterial;
  106234. })(BABYLON || (BABYLON = {}));
  106235. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  106236. var __assign = (this && this.__assign) || function () {
  106237. __assign = Object.assign || function(t) {
  106238. for (var s, i = 1, n = arguments.length; i < n; i++) {
  106239. s = arguments[i];
  106240. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  106241. t[p] = s[p];
  106242. }
  106243. return t;
  106244. };
  106245. return __assign.apply(this, arguments);
  106246. };
  106247. var BABYLON;
  106248. (function (BABYLON) {
  106249. /**
  106250. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  106251. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  106252. * It also helps with the default setup of your imageProcessing configuration.
  106253. */
  106254. var EnvironmentHelper = /** @class */ (function () {
  106255. /**
  106256. * constructor
  106257. * @param options
  106258. * @param scene The scene to add the material to
  106259. */
  106260. function EnvironmentHelper(options, scene) {
  106261. var _this = this;
  106262. this._errorHandler = function (message, exception) {
  106263. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  106264. };
  106265. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  106266. this._scene = scene;
  106267. this.onErrorObservable = new BABYLON.Observable();
  106268. this._setupBackground();
  106269. this._setupImageProcessing();
  106270. }
  106271. /**
  106272. * Creates the default options for the helper.
  106273. */
  106274. EnvironmentHelper._getDefaultOptions = function () {
  106275. return {
  106276. createGround: true,
  106277. groundSize: 15,
  106278. groundTexture: this._groundTextureCDNUrl,
  106279. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  106280. groundOpacity: 0.9,
  106281. enableGroundShadow: true,
  106282. groundShadowLevel: 0.5,
  106283. enableGroundMirror: false,
  106284. groundMirrorSizeRatio: 0.3,
  106285. groundMirrorBlurKernel: 64,
  106286. groundMirrorAmount: 1,
  106287. groundMirrorFresnelWeight: 1,
  106288. groundMirrorFallOffDistance: 0,
  106289. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  106290. groundYBias: 0.00001,
  106291. createSkybox: true,
  106292. skyboxSize: 20,
  106293. skyboxTexture: this._skyboxTextureCDNUrl,
  106294. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  106295. backgroundYRotation: 0,
  106296. sizeAuto: true,
  106297. rootPosition: BABYLON.Vector3.Zero(),
  106298. setupImageProcessing: true,
  106299. environmentTexture: this._environmentTextureCDNUrl,
  106300. cameraExposure: 0.8,
  106301. cameraContrast: 1.2,
  106302. toneMappingEnabled: true,
  106303. };
  106304. };
  106305. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  106306. /**
  106307. * Gets the root mesh created by the helper.
  106308. */
  106309. get: function () {
  106310. return this._rootMesh;
  106311. },
  106312. enumerable: true,
  106313. configurable: true
  106314. });
  106315. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  106316. /**
  106317. * Gets the skybox created by the helper.
  106318. */
  106319. get: function () {
  106320. return this._skybox;
  106321. },
  106322. enumerable: true,
  106323. configurable: true
  106324. });
  106325. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  106326. /**
  106327. * Gets the skybox texture created by the helper.
  106328. */
  106329. get: function () {
  106330. return this._skyboxTexture;
  106331. },
  106332. enumerable: true,
  106333. configurable: true
  106334. });
  106335. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  106336. /**
  106337. * Gets the skybox material created by the helper.
  106338. */
  106339. get: function () {
  106340. return this._skyboxMaterial;
  106341. },
  106342. enumerable: true,
  106343. configurable: true
  106344. });
  106345. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  106346. /**
  106347. * Gets the ground mesh created by the helper.
  106348. */
  106349. get: function () {
  106350. return this._ground;
  106351. },
  106352. enumerable: true,
  106353. configurable: true
  106354. });
  106355. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  106356. /**
  106357. * Gets the ground texture created by the helper.
  106358. */
  106359. get: function () {
  106360. return this._groundTexture;
  106361. },
  106362. enumerable: true,
  106363. configurable: true
  106364. });
  106365. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  106366. /**
  106367. * Gets the ground mirror created by the helper.
  106368. */
  106369. get: function () {
  106370. return this._groundMirror;
  106371. },
  106372. enumerable: true,
  106373. configurable: true
  106374. });
  106375. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  106376. /**
  106377. * Gets the ground mirror render list to helps pushing the meshes
  106378. * you wish in the ground reflection.
  106379. */
  106380. get: function () {
  106381. if (this._groundMirror) {
  106382. return this._groundMirror.renderList;
  106383. }
  106384. return null;
  106385. },
  106386. enumerable: true,
  106387. configurable: true
  106388. });
  106389. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  106390. /**
  106391. * Gets the ground material created by the helper.
  106392. */
  106393. get: function () {
  106394. return this._groundMaterial;
  106395. },
  106396. enumerable: true,
  106397. configurable: true
  106398. });
  106399. /**
  106400. * Updates the background according to the new options
  106401. * @param options
  106402. */
  106403. EnvironmentHelper.prototype.updateOptions = function (options) {
  106404. var newOptions = __assign({}, this._options, options);
  106405. if (this._ground && !newOptions.createGround) {
  106406. this._ground.dispose();
  106407. this._ground = null;
  106408. }
  106409. if (this._groundMaterial && !newOptions.createGround) {
  106410. this._groundMaterial.dispose();
  106411. this._groundMaterial = null;
  106412. }
  106413. if (this._groundTexture) {
  106414. if (this._options.groundTexture != newOptions.groundTexture) {
  106415. this._groundTexture.dispose();
  106416. this._groundTexture = null;
  106417. }
  106418. }
  106419. if (this._skybox && !newOptions.createSkybox) {
  106420. this._skybox.dispose();
  106421. this._skybox = null;
  106422. }
  106423. if (this._skyboxMaterial && !newOptions.createSkybox) {
  106424. this._skyboxMaterial.dispose();
  106425. this._skyboxMaterial = null;
  106426. }
  106427. if (this._skyboxTexture) {
  106428. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  106429. this._skyboxTexture.dispose();
  106430. this._skyboxTexture = null;
  106431. }
  106432. }
  106433. if (this._groundMirror && !newOptions.enableGroundMirror) {
  106434. this._groundMirror.dispose();
  106435. this._groundMirror = null;
  106436. }
  106437. if (this._scene.environmentTexture) {
  106438. if (this._options.environmentTexture != newOptions.environmentTexture) {
  106439. this._scene.environmentTexture.dispose();
  106440. }
  106441. }
  106442. this._options = newOptions;
  106443. this._setupBackground();
  106444. this._setupImageProcessing();
  106445. };
  106446. /**
  106447. * Sets the primary color of all the available elements.
  106448. * @param color the main color to affect to the ground and the background
  106449. */
  106450. EnvironmentHelper.prototype.setMainColor = function (color) {
  106451. if (this.groundMaterial) {
  106452. this.groundMaterial.primaryColor = color;
  106453. }
  106454. if (this.skyboxMaterial) {
  106455. this.skyboxMaterial.primaryColor = color;
  106456. }
  106457. if (this.groundMirror) {
  106458. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  106459. }
  106460. };
  106461. /**
  106462. * Setup the image processing according to the specified options.
  106463. */
  106464. EnvironmentHelper.prototype._setupImageProcessing = function () {
  106465. if (this._options.setupImageProcessing) {
  106466. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  106467. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  106468. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  106469. this._setupEnvironmentTexture();
  106470. }
  106471. };
  106472. /**
  106473. * Setup the environment texture according to the specified options.
  106474. */
  106475. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  106476. if (this._scene.environmentTexture) {
  106477. return;
  106478. }
  106479. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  106480. this._scene.environmentTexture = this._options.environmentTexture;
  106481. return;
  106482. }
  106483. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  106484. this._scene.environmentTexture = environmentTexture;
  106485. };
  106486. /**
  106487. * Setup the background according to the specified options.
  106488. */
  106489. EnvironmentHelper.prototype._setupBackground = function () {
  106490. if (!this._rootMesh) {
  106491. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  106492. }
  106493. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  106494. var sceneSize = this._getSceneSize();
  106495. if (this._options.createGround) {
  106496. this._setupGround(sceneSize);
  106497. this._setupGroundMaterial();
  106498. this._setupGroundDiffuseTexture();
  106499. if (this._options.enableGroundMirror) {
  106500. this._setupGroundMirrorTexture(sceneSize);
  106501. }
  106502. this._setupMirrorInGroundMaterial();
  106503. }
  106504. if (this._options.createSkybox) {
  106505. this._setupSkybox(sceneSize);
  106506. this._setupSkyboxMaterial();
  106507. this._setupSkyboxReflectionTexture();
  106508. }
  106509. this._rootMesh.position.x = sceneSize.rootPosition.x;
  106510. this._rootMesh.position.z = sceneSize.rootPosition.z;
  106511. this._rootMesh.position.y = sceneSize.rootPosition.y;
  106512. };
  106513. /**
  106514. * Get the scene sizes according to the setup.
  106515. */
  106516. EnvironmentHelper.prototype._getSceneSize = function () {
  106517. var _this = this;
  106518. var groundSize = this._options.groundSize;
  106519. var skyboxSize = this._options.skyboxSize;
  106520. var rootPosition = this._options.rootPosition;
  106521. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  106522. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  106523. }
  106524. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  106525. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  106526. });
  106527. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  106528. if (this._options.sizeAuto) {
  106529. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  106530. this._scene.activeCamera.upperRadiusLimit) {
  106531. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  106532. skyboxSize = groundSize;
  106533. }
  106534. var sceneDiagonalLenght = sceneDiagonal.length();
  106535. if (sceneDiagonalLenght > groundSize) {
  106536. groundSize = sceneDiagonalLenght * 2;
  106537. skyboxSize = groundSize;
  106538. }
  106539. // 10 % bigger.
  106540. groundSize *= 1.1;
  106541. skyboxSize *= 1.5;
  106542. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  106543. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  106544. }
  106545. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  106546. };
  106547. /**
  106548. * Setup the ground according to the specified options.
  106549. */
  106550. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  106551. var _this = this;
  106552. if (!this._ground || this._ground.isDisposed()) {
  106553. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  106554. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  106555. this._ground.parent = this._rootMesh;
  106556. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  106557. }
  106558. this._ground.receiveShadows = this._options.enableGroundShadow;
  106559. };
  106560. /**
  106561. * Setup the ground material according to the specified options.
  106562. */
  106563. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  106564. if (!this._groundMaterial) {
  106565. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  106566. }
  106567. this._groundMaterial.alpha = this._options.groundOpacity;
  106568. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  106569. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  106570. this._groundMaterial.primaryColor = this._options.groundColor;
  106571. this._groundMaterial.useRGBColor = false;
  106572. this._groundMaterial.enableNoise = true;
  106573. if (this._ground) {
  106574. this._ground.material = this._groundMaterial;
  106575. }
  106576. };
  106577. /**
  106578. * Setup the ground diffuse texture according to the specified options.
  106579. */
  106580. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  106581. if (!this._groundMaterial) {
  106582. return;
  106583. }
  106584. if (this._groundTexture) {
  106585. return;
  106586. }
  106587. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  106588. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  106589. return;
  106590. }
  106591. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  106592. diffuseTexture.gammaSpace = false;
  106593. diffuseTexture.hasAlpha = true;
  106594. this._groundMaterial.diffuseTexture = diffuseTexture;
  106595. };
  106596. /**
  106597. * Setup the ground mirror texture according to the specified options.
  106598. */
  106599. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  106600. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106601. if (!this._groundMirror) {
  106602. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  106603. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  106604. this._groundMirror.anisotropicFilteringLevel = 1;
  106605. this._groundMirror.wrapU = wrapping;
  106606. this._groundMirror.wrapV = wrapping;
  106607. this._groundMirror.gammaSpace = false;
  106608. if (this._groundMirror.renderList) {
  106609. for (var i = 0; i < this._scene.meshes.length; i++) {
  106610. var mesh = this._scene.meshes[i];
  106611. if (mesh !== this._ground &&
  106612. mesh !== this._skybox &&
  106613. mesh !== this._rootMesh) {
  106614. this._groundMirror.renderList.push(mesh);
  106615. }
  106616. }
  106617. }
  106618. }
  106619. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  106620. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  106621. };
  106622. /**
  106623. * Setup the ground to receive the mirror texture.
  106624. */
  106625. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  106626. if (this._groundMaterial) {
  106627. this._groundMaterial.reflectionTexture = this._groundMirror;
  106628. this._groundMaterial.reflectionFresnel = true;
  106629. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  106630. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  106631. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  106632. }
  106633. };
  106634. /**
  106635. * Setup the skybox according to the specified options.
  106636. */
  106637. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  106638. var _this = this;
  106639. if (!this._skybox || this._skybox.isDisposed()) {
  106640. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  106641. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  106642. }
  106643. this._skybox.parent = this._rootMesh;
  106644. };
  106645. /**
  106646. * Setup the skybox material according to the specified options.
  106647. */
  106648. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  106649. if (!this._skybox) {
  106650. return;
  106651. }
  106652. if (!this._skyboxMaterial) {
  106653. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  106654. }
  106655. this._skyboxMaterial.useRGBColor = false;
  106656. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  106657. this._skyboxMaterial.enableNoise = true;
  106658. this._skybox.material = this._skyboxMaterial;
  106659. };
  106660. /**
  106661. * Setup the skybox reflection texture according to the specified options.
  106662. */
  106663. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  106664. if (!this._skyboxMaterial) {
  106665. return;
  106666. }
  106667. if (this._skyboxTexture) {
  106668. return;
  106669. }
  106670. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  106671. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  106672. return;
  106673. }
  106674. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  106675. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  106676. this._skyboxTexture.gammaSpace = false;
  106677. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  106678. };
  106679. /**
  106680. * Dispose all the elements created by the Helper.
  106681. */
  106682. EnvironmentHelper.prototype.dispose = function () {
  106683. if (this._groundMaterial) {
  106684. this._groundMaterial.dispose(true, true);
  106685. }
  106686. if (this._skyboxMaterial) {
  106687. this._skyboxMaterial.dispose(true, true);
  106688. }
  106689. this._rootMesh.dispose(false);
  106690. };
  106691. /**
  106692. * Default ground texture URL.
  106693. */
  106694. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  106695. /**
  106696. * Default skybox texture URL.
  106697. */
  106698. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  106699. /**
  106700. * Default environment texture URL.
  106701. */
  106702. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  106703. return EnvironmentHelper;
  106704. }());
  106705. BABYLON.EnvironmentHelper = EnvironmentHelper;
  106706. })(BABYLON || (BABYLON = {}));
  106707. //# sourceMappingURL=babylon.environmentHelper.js.map
  106708. var BABYLON;
  106709. (function (BABYLON) {
  106710. /** Internal class used to store shapes for emitters */
  106711. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  106712. function ParticleSystemSetEmitterCreationOptions() {
  106713. }
  106714. return ParticleSystemSetEmitterCreationOptions;
  106715. }());
  106716. /**
  106717. * Represents a set of particle systems working together to create a specific effect
  106718. */
  106719. var ParticleSystemSet = /** @class */ (function () {
  106720. function ParticleSystemSet() {
  106721. /**
  106722. * Gets the particle system list
  106723. */
  106724. this.systems = new Array();
  106725. }
  106726. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  106727. /**
  106728. * Gets the emitter node used with this set
  106729. */
  106730. get: function () {
  106731. return this._emitterNode;
  106732. },
  106733. enumerable: true,
  106734. configurable: true
  106735. });
  106736. /**
  106737. * Creates a new emitter mesh as a sphere
  106738. * @param options defines the options used to create the sphere
  106739. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  106740. * @param scene defines the hosting scene
  106741. */
  106742. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  106743. if (this._emitterNode) {
  106744. this._emitterNode.dispose();
  106745. }
  106746. this._emitterCreationOptions = {
  106747. kind: "Sphere",
  106748. options: options,
  106749. renderingGroupId: renderingGroupId
  106750. };
  106751. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  106752. emitterMesh.renderingGroupId = renderingGroupId;
  106753. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  106754. material.emissiveColor = options.color;
  106755. emitterMesh.material = material;
  106756. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  106757. var system = _a[_i];
  106758. system.emitter = emitterMesh;
  106759. }
  106760. this._emitterNode = emitterMesh;
  106761. };
  106762. /**
  106763. * Starts all particle systems of the set
  106764. * @param emitter defines an optional mesh to use as emitter for the particle systems
  106765. */
  106766. ParticleSystemSet.prototype.start = function (emitter) {
  106767. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  106768. var system = _a[_i];
  106769. if (emitter) {
  106770. system.emitter = emitter;
  106771. }
  106772. system.start();
  106773. }
  106774. };
  106775. /**
  106776. * Release all associated resources
  106777. */
  106778. ParticleSystemSet.prototype.dispose = function () {
  106779. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  106780. var system = _a[_i];
  106781. system.dispose();
  106782. }
  106783. this.systems = [];
  106784. if (this._emitterNode) {
  106785. this._emitterNode.dispose();
  106786. this._emitterNode = null;
  106787. }
  106788. };
  106789. /**
  106790. * Serialize the set into a JSON compatible object
  106791. * @returns a JSON compatible representation of the set
  106792. */
  106793. ParticleSystemSet.prototype.serialize = function () {
  106794. var result = {};
  106795. result.systems = [];
  106796. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  106797. var system = _a[_i];
  106798. result.systems.push(system.serialize());
  106799. }
  106800. if (this._emitterNode) {
  106801. result.emitter = this._emitterCreationOptions;
  106802. }
  106803. return result;
  106804. };
  106805. /**
  106806. * Parse a new ParticleSystemSet from a serialized source
  106807. * @param data defines a JSON compatible representation of the set
  106808. * @param scene defines the hosting scene
  106809. * @param gpu defines if we want GPU particles or CPU particles
  106810. * @returns a new ParticleSystemSet
  106811. */
  106812. ParticleSystemSet.Parse = function (data, scene, gpu) {
  106813. if (gpu === void 0) { gpu = false; }
  106814. var result = new ParticleSystemSet();
  106815. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  106816. scene = scene || BABYLON.Engine.LastCreatedScene;
  106817. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  106818. var system = _a[_i];
  106819. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  106820. }
  106821. if (data.emitter) {
  106822. var options = data.emitter.options;
  106823. switch (data.emitter.kind) {
  106824. case "Sphere":
  106825. result.setEmitterAsSphere({
  106826. diameter: options.diameter,
  106827. segments: options.segments,
  106828. color: BABYLON.Color3.FromArray(options.color)
  106829. }, data.emitter.renderingGroupId, scene);
  106830. break;
  106831. }
  106832. }
  106833. return result;
  106834. };
  106835. return ParticleSystemSet;
  106836. }());
  106837. BABYLON.ParticleSystemSet = ParticleSystemSet;
  106838. })(BABYLON || (BABYLON = {}));
  106839. //# sourceMappingURL=babylon.particleSystemSet.js.map
  106840. var BABYLON;
  106841. (function (BABYLON) {
  106842. /**
  106843. * This class is made for on one-liner static method to help creating particle system set.
  106844. */
  106845. var ParticleHelper = /** @class */ (function () {
  106846. function ParticleHelper() {
  106847. }
  106848. /**
  106849. * Create a default particle system that you can tweak
  106850. * @param emitter defines the emitter to use
  106851. * @param capacity defines the system capacity (default is 500 particles)
  106852. * @param scene defines the hosting scene
  106853. * @returns the new Particle system
  106854. */
  106855. ParticleHelper.CreateDefault = function (emitter, capacity, scene) {
  106856. if (capacity === void 0) { capacity = 500; }
  106857. var system = new BABYLON.ParticleSystem("default system", capacity, scene);
  106858. system.emitter = emitter;
  106859. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  106860. system.createConeEmitter(0.1, Math.PI / 4);
  106861. // Particle color
  106862. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  106863. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  106864. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  106865. // Particle Size
  106866. system.minSize = 0.1;
  106867. system.maxSize = 0.1;
  106868. // Emission speed
  106869. system.minEmitPower = 2;
  106870. system.maxEmitPower = 2;
  106871. // Update speed
  106872. system.updateSpeed = 1 / 60;
  106873. system.emitRate = 30;
  106874. return system;
  106875. };
  106876. /**
  106877. * This is the main static method (one-liner) of this helper to create different particle systems
  106878. * @param type This string represents the type to the particle system to create
  106879. * @param scene The scene where the particle system should live
  106880. * @param gpu If the system will use gpu
  106881. * @returns the ParticleSystemSet created
  106882. */
  106883. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  106884. if (gpu === void 0) { gpu = false; }
  106885. if (!scene) {
  106886. scene = BABYLON.Engine.LastCreatedScene;
  106887. ;
  106888. }
  106889. var token = {};
  106890. scene._addPendingData(token);
  106891. return new Promise(function (resolve, reject) {
  106892. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  106893. scene._removePendingData(token);
  106894. return reject("Particle system with GPU is not supported.");
  106895. }
  106896. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  106897. scene._removePendingData(token);
  106898. var newData = JSON.parse(data.toString());
  106899. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  106900. }, undefined, undefined, undefined, function (req, exception) {
  106901. scene._removePendingData(token);
  106902. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  106903. });
  106904. });
  106905. };
  106906. /**
  106907. * Static function used to export a particle system to a ParticleSystemSet variable.
  106908. * Please note that the emitter shape is not exported
  106909. * @param system defines the particle systems to export
  106910. */
  106911. ParticleHelper.ExportSet = function (systems) {
  106912. var set = new BABYLON.ParticleSystemSet();
  106913. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  106914. var system = systems_1[_i];
  106915. set.systems.push(system);
  106916. }
  106917. return set;
  106918. };
  106919. /**
  106920. * Gets or sets base Assets URL
  106921. */
  106922. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  106923. return ParticleHelper;
  106924. }());
  106925. BABYLON.ParticleHelper = ParticleHelper;
  106926. })(BABYLON || (BABYLON = {}));
  106927. //# sourceMappingURL=babylon.particleHelper.js.map
  106928. var BABYLON;
  106929. (function (BABYLON) {
  106930. /**
  106931. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  106932. * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.
  106933. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  106934. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  106935. */
  106936. var VideoDome = /** @class */ (function (_super) {
  106937. __extends(VideoDome, _super);
  106938. /**
  106939. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  106940. * @param name Element's name, child elements will append suffixes for their own names.
  106941. * @param urlsOrVideo defines the url(s) or the video element to use
  106942. * @param options An object containing optional or exposed sub element properties
  106943. */
  106944. function VideoDome(name, urlsOrVideo, options, scene) {
  106945. var _this = _super.call(this, name, scene) || this;
  106946. _this._useDirectMapping = false;
  106947. // set defaults and manage values
  106948. name = name || "videoDome";
  106949. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  106950. options.clickToPlay = Boolean(options.clickToPlay);
  106951. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  106952. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  106953. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  106954. if (options.useDirectMapping === undefined) {
  106955. _this._useDirectMapping = true;
  106956. }
  106957. else {
  106958. _this._useDirectMapping = options.useDirectMapping;
  106959. }
  106960. _this._setReady(false);
  106961. // create
  106962. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  106963. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  106964. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  106965. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  106966. texture.onLoadObservable.addOnce(function () {
  106967. _this._setReady(true);
  106968. });
  106969. // configure material
  106970. material.useEquirectangularFOV = true;
  106971. material.fovMultiplier = 1.0;
  106972. material.opacityFresnel = false;
  106973. if (_this._useDirectMapping) {
  106974. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106975. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106976. material.diffuseTexture = texture;
  106977. }
  106978. else {
  106979. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  106980. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106981. material.reflectionTexture = texture;
  106982. }
  106983. // configure mesh
  106984. _this._mesh.material = material;
  106985. _this._mesh.parent = _this;
  106986. // optional configuration
  106987. if (options.clickToPlay) {
  106988. scene.onPointerUp = function () {
  106989. _this._videoTexture.video.play();
  106990. };
  106991. }
  106992. return _this;
  106993. }
  106994. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  106995. /**
  106996. * Gets the video texture being displayed on the sphere
  106997. */
  106998. get: function () {
  106999. return this._videoTexture;
  107000. },
  107001. enumerable: true,
  107002. configurable: true
  107003. });
  107004. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  107005. /**
  107006. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  107007. * Also see the options.resolution property.
  107008. */
  107009. get: function () {
  107010. return this._material.fovMultiplier;
  107011. },
  107012. set: function (value) {
  107013. this._material.fovMultiplier = value;
  107014. },
  107015. enumerable: true,
  107016. configurable: true
  107017. });
  107018. /**
  107019. * Releases resources associated with this node.
  107020. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  107021. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  107022. */
  107023. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  107024. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  107025. this._videoTexture.dispose();
  107026. this._mesh.dispose();
  107027. this._material.dispose();
  107028. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  107029. };
  107030. return VideoDome;
  107031. }(BABYLON.TransformNode));
  107032. BABYLON.VideoDome = VideoDome;
  107033. })(BABYLON || (BABYLON = {}));
  107034. //# sourceMappingURL=babylon.videoDome.js.map
  107035. var BABYLON;
  107036. (function (BABYLON) {
  107037. /**
  107038. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  107039. * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.
  107040. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  107041. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  107042. */
  107043. var PhotoDome = /** @class */ (function (_super) {
  107044. __extends(PhotoDome, _super);
  107045. /**
  107046. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  107047. * @param name Element's name, child elements will append suffixes for their own names.
  107048. * @param urlsOfPhoto defines the url of the photo to display
  107049. * @param options defines an object containing optional or exposed sub element properties
  107050. * @param onError defines a callback called when an error occured while loading the texture
  107051. */
  107052. function PhotoDome(name, urlOfPhoto, options, scene, onError) {
  107053. if (onError === void 0) { onError = null; }
  107054. var _this = _super.call(this, name, scene) || this;
  107055. _this._useDirectMapping = false;
  107056. /**
  107057. * Observable raised when an error occured while loading the 360 image
  107058. */
  107059. _this.onLoadErrorObservable = new BABYLON.Observable();
  107060. // set defaults and manage values
  107061. name = name || "photoDome";
  107062. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  107063. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  107064. if (options.useDirectMapping === undefined) {
  107065. _this._useDirectMapping = true;
  107066. }
  107067. else {
  107068. _this._useDirectMapping = options.useDirectMapping;
  107069. }
  107070. _this._setReady(false);
  107071. // create
  107072. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  107073. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  107074. // configure material
  107075. material.opacityFresnel = false;
  107076. material.useEquirectangularFOV = true;
  107077. material.fovMultiplier = 1.0;
  107078. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping, undefined, undefined, function (message, exception) {
  107079. _this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured");
  107080. if (onError) {
  107081. onError(message, exception);
  107082. }
  107083. });
  107084. _this.photoTexture.onLoadObservable.addOnce(function () {
  107085. _this._setReady(true);
  107086. });
  107087. // configure mesh
  107088. _this._mesh.material = material;
  107089. _this._mesh.parent = _this;
  107090. return _this;
  107091. }
  107092. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  107093. /**
  107094. * Gets or sets the texture being displayed on the sphere
  107095. */
  107096. get: function () {
  107097. return this._photoTexture;
  107098. },
  107099. set: function (value) {
  107100. if (this._photoTexture === value) {
  107101. return;
  107102. }
  107103. this._photoTexture = value;
  107104. if (this._useDirectMapping) {
  107105. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107106. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107107. this._material.diffuseTexture = this._photoTexture;
  107108. }
  107109. else {
  107110. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  107111. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107112. this._material.reflectionTexture = this._photoTexture;
  107113. }
  107114. },
  107115. enumerable: true,
  107116. configurable: true
  107117. });
  107118. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  107119. /**
  107120. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  107121. * Also see the options.resolution property.
  107122. */
  107123. get: function () {
  107124. return this._material.fovMultiplier;
  107125. },
  107126. set: function (value) {
  107127. this._material.fovMultiplier = value;
  107128. },
  107129. enumerable: true,
  107130. configurable: true
  107131. });
  107132. /**
  107133. * Releases resources associated with this node.
  107134. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  107135. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  107136. */
  107137. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  107138. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  107139. this._photoTexture.dispose();
  107140. this._mesh.dispose();
  107141. this._material.dispose();
  107142. this.onLoadErrorObservable.clear();
  107143. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  107144. };
  107145. return PhotoDome;
  107146. }(BABYLON.TransformNode));
  107147. BABYLON.PhotoDome = PhotoDome;
  107148. })(BABYLON || (BABYLON = {}));
  107149. //# sourceMappingURL=babylon.photoDome.js.map
  107150. var BABYLON;
  107151. (function (BABYLON) {
  107152. BABYLON.Engine.prototype.createQuery = function () {
  107153. return this._gl.createQuery();
  107154. };
  107155. BABYLON.Engine.prototype.deleteQuery = function (query) {
  107156. this._gl.deleteQuery(query);
  107157. return this;
  107158. };
  107159. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  107160. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  107161. };
  107162. BABYLON.Engine.prototype.getQueryResult = function (query) {
  107163. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  107164. };
  107165. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  107166. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  107167. this._gl.beginQuery(glAlgorithm, query);
  107168. return this;
  107169. };
  107170. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  107171. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  107172. this._gl.endQuery(glAlgorithm);
  107173. return this;
  107174. };
  107175. BABYLON.Engine.prototype._createTimeQuery = function () {
  107176. var timerQuery = this.getCaps().timerQuery;
  107177. if (timerQuery.createQueryEXT) {
  107178. return timerQuery.createQueryEXT();
  107179. }
  107180. return this.createQuery();
  107181. };
  107182. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  107183. var timerQuery = this.getCaps().timerQuery;
  107184. if (timerQuery.deleteQueryEXT) {
  107185. timerQuery.deleteQueryEXT(query);
  107186. return;
  107187. }
  107188. this.deleteQuery(query);
  107189. };
  107190. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  107191. var timerQuery = this.getCaps().timerQuery;
  107192. if (timerQuery.getQueryObjectEXT) {
  107193. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  107194. }
  107195. return this.getQueryResult(query);
  107196. };
  107197. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  107198. var timerQuery = this.getCaps().timerQuery;
  107199. if (timerQuery.getQueryObjectEXT) {
  107200. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  107201. }
  107202. return this.isQueryResultAvailable(query);
  107203. };
  107204. BABYLON.Engine.prototype.startTimeQuery = function () {
  107205. var caps = this.getCaps();
  107206. var timerQuery = caps.timerQuery;
  107207. if (!timerQuery) {
  107208. return null;
  107209. }
  107210. var token = new BABYLON._TimeToken();
  107211. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  107212. if (caps.canUseTimestampForTimerQuery) {
  107213. token._startTimeQuery = this._createTimeQuery();
  107214. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  107215. }
  107216. else {
  107217. if (this._currentNonTimestampToken) {
  107218. return this._currentNonTimestampToken;
  107219. }
  107220. token._timeElapsedQuery = this._createTimeQuery();
  107221. if (timerQuery.beginQueryEXT) {
  107222. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  107223. }
  107224. else {
  107225. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  107226. }
  107227. this._currentNonTimestampToken = token;
  107228. }
  107229. return token;
  107230. };
  107231. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  107232. var caps = this.getCaps();
  107233. var timerQuery = caps.timerQuery;
  107234. if (!timerQuery || !token) {
  107235. return -1;
  107236. }
  107237. if (caps.canUseTimestampForTimerQuery) {
  107238. if (!token._startTimeQuery) {
  107239. return -1;
  107240. }
  107241. if (!token._endTimeQuery) {
  107242. token._endTimeQuery = this._createTimeQuery();
  107243. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  107244. }
  107245. }
  107246. else if (!token._timeElapsedQueryEnded) {
  107247. if (!token._timeElapsedQuery) {
  107248. return -1;
  107249. }
  107250. if (timerQuery.endQueryEXT) {
  107251. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  107252. }
  107253. else {
  107254. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  107255. }
  107256. token._timeElapsedQueryEnded = true;
  107257. }
  107258. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  107259. var available = false;
  107260. if (token._endTimeQuery) {
  107261. available = this._getTimeQueryAvailability(token._endTimeQuery);
  107262. }
  107263. else if (token._timeElapsedQuery) {
  107264. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  107265. }
  107266. if (available && !disjoint) {
  107267. var result = 0;
  107268. if (caps.canUseTimestampForTimerQuery) {
  107269. if (!token._startTimeQuery || !token._endTimeQuery) {
  107270. return -1;
  107271. }
  107272. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  107273. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  107274. result = timeEnd - timeStart;
  107275. this._deleteTimeQuery(token._startTimeQuery);
  107276. this._deleteTimeQuery(token._endTimeQuery);
  107277. token._startTimeQuery = null;
  107278. token._endTimeQuery = null;
  107279. }
  107280. else {
  107281. if (!token._timeElapsedQuery) {
  107282. return -1;
  107283. }
  107284. result = this._getTimeQueryResult(token._timeElapsedQuery);
  107285. this._deleteTimeQuery(token._timeElapsedQuery);
  107286. token._timeElapsedQuery = null;
  107287. token._timeElapsedQueryEnded = false;
  107288. this._currentNonTimestampToken = null;
  107289. }
  107290. return result;
  107291. }
  107292. return -1;
  107293. };
  107294. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  107295. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  107296. };
  107297. // We also need to update AbstractMesh as there is a portion of the code there
  107298. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  107299. var engine = this.getEngine();
  107300. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  107301. this._isOccluded = false;
  107302. return;
  107303. }
  107304. if (engine.webGLVersion < 2 || this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  107305. this._isOccluded = false;
  107306. return;
  107307. }
  107308. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  107309. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  107310. if (isOcclusionQueryAvailable) {
  107311. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  107312. this._isOcclusionQueryInProgress = false;
  107313. this._occlusionInternalRetryCounter = 0;
  107314. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  107315. }
  107316. else {
  107317. this._occlusionInternalRetryCounter++;
  107318. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  107319. this._isOcclusionQueryInProgress = false;
  107320. this._occlusionInternalRetryCounter = 0;
  107321. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  107322. // if strict continue the last state of the object.
  107323. this._isOccluded = this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  107324. }
  107325. else {
  107326. return;
  107327. }
  107328. }
  107329. }
  107330. var scene = this.getScene();
  107331. if (scene.getBoundingBoxRenderer) {
  107332. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  107333. if (!this._occlusionQuery) {
  107334. this._occlusionQuery = engine.createQuery();
  107335. }
  107336. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  107337. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  107338. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  107339. this._isOcclusionQueryInProgress = true;
  107340. }
  107341. };
  107342. })(BABYLON || (BABYLON = {}));
  107343. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  107344. var BABYLON;
  107345. (function (BABYLON) {
  107346. /**
  107347. * Class used to generate noise procedural textures
  107348. */
  107349. var NoiseProceduralTexture = /** @class */ (function (_super) {
  107350. __extends(NoiseProceduralTexture, _super);
  107351. /**
  107352. * Creates a new NoiseProceduralTexture
  107353. * @param name defines the name fo the texture
  107354. * @param size defines the size of the texture (default is 256)
  107355. * @param scene defines the hosting scene
  107356. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  107357. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  107358. */
  107359. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  107360. if (size === void 0) { size = 256; }
  107361. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  107362. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  107363. _this._time = 0;
  107364. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  107365. _this.brightness = 0.2;
  107366. /** Defines the number of octaves to process */
  107367. _this.octaves = 3;
  107368. /** Defines the level of persistence (0.8 by default) */
  107369. _this.persistence = 0.8;
  107370. /** Gets or sets animation speed factor (default is 1) */
  107371. _this.animationSpeedFactor = 1;
  107372. _this._updateShaderUniforms();
  107373. return _this;
  107374. }
  107375. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  107376. var scene = this.getScene();
  107377. if (!scene) {
  107378. return;
  107379. }
  107380. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  107381. this.setFloat("brightness", this.brightness);
  107382. this.setFloat("persistence", this.persistence);
  107383. this.setFloat("timeScale", this._time);
  107384. };
  107385. NoiseProceduralTexture.prototype._getDefines = function () {
  107386. return "#define OCTAVES " + this.octaves;
  107387. };
  107388. /** Generate the current state of the procedural texture */
  107389. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  107390. this._updateShaderUniforms();
  107391. _super.prototype.render.call(this, useCameraPostProcess);
  107392. };
  107393. /**
  107394. * Serializes this noise procedural texture
  107395. * @returns a serialized noise procedural texture object
  107396. */
  107397. NoiseProceduralTexture.prototype.serialize = function () {
  107398. var serializationObject = BABYLON.SerializationHelper.Serialize(this, _super.prototype.serialize.call(this));
  107399. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  107400. return serializationObject;
  107401. };
  107402. /**
  107403. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  107404. * @param parsedTexture defines parsed texture data
  107405. * @param scene defines the current scene
  107406. * @param rootUrl defines the root URL containing noise procedural texture information
  107407. * @returns a parsed NoiseProceduralTexture
  107408. */
  107409. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  107410. var texture = BABYLON.SerializationHelper.Parse(function () { return new NoiseProceduralTexture(parsedTexture.name, parsedTexture._size, scene, undefined, parsedTexture._generateMipMaps); }, parsedTexture, scene, rootUrl);
  107411. return texture;
  107412. };
  107413. return NoiseProceduralTexture;
  107414. }(BABYLON.ProceduralTexture));
  107415. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  107416. })(BABYLON || (BABYLON = {}));
  107417. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  107418. var __assign = (this && this.__assign) || function () {
  107419. __assign = Object.assign || function(t) {
  107420. for (var s, i = 1, n = arguments.length; i < n; i++) {
  107421. s = arguments[i];
  107422. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  107423. t[p] = s[p];
  107424. }
  107425. return t;
  107426. };
  107427. return __assign.apply(this, arguments);
  107428. };
  107429. var BABYLON;
  107430. (function (BABYLON) {
  107431. /**
  107432. * This can helps recording videos from BabylonJS.
  107433. * This is based on the available WebRTC functionalities of the browser.
  107434. *
  107435. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_video
  107436. */
  107437. var VideoRecorder = /** @class */ (function () {
  107438. /**
  107439. * Create a new VideoCapture object which can help converting what you see in Babylon to
  107440. * a video file.
  107441. * @param engine Defines the BabylonJS Engine you wish to record
  107442. * @param options Defines options that can be used to customized the capture
  107443. */
  107444. function VideoRecorder(engine, options) {
  107445. if (options === void 0) { options = null; }
  107446. if (!VideoRecorder.IsSupported(engine)) {
  107447. throw "Your browser does not support recording so far.";
  107448. }
  107449. var canvas = engine.getRenderingCanvas();
  107450. if (!canvas) {
  107451. throw "The babylon engine must have a canvas to be recorded";
  107452. }
  107453. this._canvas = canvas;
  107454. this._canvas.isRecording = false;
  107455. this._options = __assign({}, VideoRecorder._defaultOptions, options);
  107456. var stream = this._canvas.captureStream(this._options.fps);
  107457. this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });
  107458. this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);
  107459. this._mediaRecorder.onerror = this._handleError.bind(this);
  107460. this._mediaRecorder.onstop = this._handleStop.bind(this);
  107461. }
  107462. /**
  107463. * Returns wehther or not the VideoRecorder is available in your browser.
  107464. * @param engine Defines the Babylon Engine to check the support for
  107465. * @returns true if supported otherwise false
  107466. */
  107467. VideoRecorder.IsSupported = function (engine) {
  107468. var canvas = engine.getRenderingCanvas();
  107469. return (!!canvas && typeof canvas.captureStream === "function");
  107470. };
  107471. Object.defineProperty(VideoRecorder.prototype, "isRecording", {
  107472. /**
  107473. * True wether a recording is already in progress.
  107474. */
  107475. get: function () {
  107476. return !!this._canvas && this._canvas.isRecording;
  107477. },
  107478. enumerable: true,
  107479. configurable: true
  107480. });
  107481. /**
  107482. * Stops the current recording before the default capture timeout passed in the startRecording
  107483. * functions.
  107484. */
  107485. VideoRecorder.prototype.stopRecording = function () {
  107486. if (!this._canvas || !this._mediaRecorder) {
  107487. return;
  107488. }
  107489. if (!this.isRecording) {
  107490. return;
  107491. }
  107492. this._canvas.isRecording = false;
  107493. this._mediaRecorder.stop();
  107494. };
  107495. /**
  107496. * Starts recording the canvas for a max duration specified in parameters.
  107497. * @param fileName Defines the name of the file to be downloaded when the recording stop. If null no automatic download will start and you can rely on the promise to get the data back.
  107498. * @param maxDuration Defines the maximum recording time in seconds.
  107499. * It default to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually.
  107500. * @return a promise callback at the end of the recording with the video data in Blob.
  107501. */
  107502. VideoRecorder.prototype.startRecording = function (fileName, maxDuration) {
  107503. var _this = this;
  107504. if (fileName === void 0) { fileName = "babylonjs.webm"; }
  107505. if (maxDuration === void 0) { maxDuration = 7; }
  107506. if (!this._canvas || !this._mediaRecorder) {
  107507. throw "Recorder has already been disposed";
  107508. }
  107509. if (this.isRecording) {
  107510. throw "Recording already in progress";
  107511. }
  107512. if (maxDuration > 0) {
  107513. setTimeout(function () {
  107514. _this.stopRecording();
  107515. }, maxDuration * 1000);
  107516. }
  107517. this._fileName = fileName;
  107518. this._recordedChunks = [];
  107519. this._resolve = null;
  107520. this._reject = null;
  107521. this._canvas.isRecording = true;
  107522. this._mediaRecorder.start(this._options.recordChunckSize);
  107523. return new Promise(function (resolve, reject) {
  107524. _this._resolve = resolve;
  107525. _this._reject = reject;
  107526. });
  107527. };
  107528. /**
  107529. * Releases internal resources used during the recording.
  107530. */
  107531. VideoRecorder.prototype.dispose = function () {
  107532. this._canvas = null;
  107533. this._mediaRecorder = null;
  107534. this._recordedChunks = [];
  107535. this._fileName = null;
  107536. this._resolve = null;
  107537. this._reject = null;
  107538. };
  107539. VideoRecorder.prototype._handleDataAvailable = function (event) {
  107540. if (event.data.size > 0) {
  107541. this._recordedChunks.push(event.data);
  107542. }
  107543. };
  107544. VideoRecorder.prototype._handleError = function (event) {
  107545. this.stopRecording();
  107546. if (this._reject) {
  107547. this._reject(event.error);
  107548. }
  107549. else {
  107550. throw new event.error;
  107551. }
  107552. };
  107553. VideoRecorder.prototype._handleStop = function () {
  107554. this.stopRecording();
  107555. var superBuffer = new Blob(this._recordedChunks);
  107556. if (this._resolve) {
  107557. this._resolve(superBuffer);
  107558. }
  107559. window.URL.createObjectURL(superBuffer);
  107560. if (this._fileName) {
  107561. BABYLON.Tools.Download(superBuffer, this._fileName);
  107562. }
  107563. };
  107564. VideoRecorder._defaultOptions = {
  107565. mimeType: "video/webm",
  107566. fps: 25,
  107567. recordChunckSize: 3000
  107568. };
  107569. return VideoRecorder;
  107570. }());
  107571. BABYLON.VideoRecorder = VideoRecorder;
  107572. })(BABYLON || (BABYLON = {}));
  107573. //# sourceMappingURL=babylon.videoRecorder.js.map
  107574. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(position,1.0)).xyz;\n#else\nvPositionUVW=position;\n#endif\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(positionUpdated,1.0)).xyz;\n#else\nvPositionUVW=positionUpdated;\n#endif\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec4 environmentRefraction=vec4(0.,0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD);\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef RGBDREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec4 environmentRadiance=vec4(0.,0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance.rgb*=vReflectionInfos.x;\nenvironmentRadiance.rgb*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\npointLightingInfo pointInfo;\nspotLightingInfo spotInfo;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction.rgb*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef AMBIENT\nvec3 ambientOcclusionForDirectDiffuse=mix(vec3(1.),ambientOcclusionColor,vAmbientInfos.w);\n#else\nvec3 ambientOcclusionForDirectDiffuse=ambientOcclusionColor;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionForDirectDiffuse*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","rgbdEncodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}","rgbdDecodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET \nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD \nattribute vec3 direction;\n#endif\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#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration>\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\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#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*vec4(viewPos,1.0);\n#endif\n#include<clipPlaneVertex>\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#include<clipPlaneFragmentDeclaration>\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec4 baseColor=texture2D(diffuseSampler,vUV);\nbaseColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\nbaseColor=applyImageProcessing(baseColor);\n#endif\n#endif\ngl_FragColor=baseColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\nin float angle;\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration2>\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nin vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\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#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*viewPosition;\n#endif \n#include<clipPlaneVertex>\n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#include<clipPlaneFragmentDeclaration2> \n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main() {\n#include<clipPlaneFragment> \noutFragColor=texture(textureSampler,vUV)*vColor;\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\noutFragColor=applyImageProcessing(outFragColor);\n#endif\n#endif\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;\nuniform vec4 color2;\n#endif\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform sampler2D randomSampler2;\nuniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef POINTEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#endif\n#ifdef HEMISPHERICEMITTER\nuniform float radius;\nuniform float radiusRange;\nuniform float directionRandomizer;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\nuniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CYLINDEREMITTER\nuniform float radius;\nuniform float height;\nuniform float radiusRange;\nuniform float directionRandomizer;\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 VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;\nuniform sampler2D noiseSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nfloat newAge=age+timeDelta;\n\nif (newAge>=life && stopFactor != 0.) {\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\noutAge=mod(newAge,outLife);\n\noutSeed=seed;\n\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\n\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n\n#ifdef POINTEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=vec3(0,0,0);\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(BOXEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3; \n#elif defined(HEMISPHERICEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);\ndirection=position+directionRandomizer*randoms3; \n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CYLINDEREMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat yPos=(randoms2.x-0.5)*height;\nfloat angle=randoms2.y*PI*2.;\nfloat inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));\nfloat positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));\nfloat xPos=positionRadius*cos(angle);\nfloat zPos=positionRadius*sin(angle);\nposition=vec3(xPos,yPos,zPos);\n\nangle=angle+((randoms3.x-0.5)*PI);\ndirection=vec3(cos(angle),randoms3.y-0.5,sin(angle));\ndirection=normalize(direction);\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\n#ifdef CONEEMITTERSPAWNPOINT\nfloat h=0.00001;\n#else\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h; \n#endif\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height.x;\nposition=vec3(randX,randY,randZ); \n\nif (abs(cos(coneAngle)) == 1.0) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\nvec3 initial=(emitterWM*vec4(normalize(direction),0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#endif\n} else {\nfloat directionScale=timeDelta;\noutAge=newAge;\nfloat ageGradient=newAge/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\noutPosition=position+direction*directionScale;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;\noutSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\noutDirection=direction+gravity*timeDelta;\n#ifdef NOISE\nvec3 localPosition=outPosition-emitterWM[3].xyz;\nfloat fetchedR=texture(noiseSampler,vec2(localPosition.y,localPosition.z)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedG=texture(noiseSampler,vec2(localPosition.x+0.33,localPosition.z+0.33)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedB=texture(noiseSampler,vec2(localPosition.z-0.33,localPosition.y-0.33)*vec2(0.5)+vec2(0.5)).r;\nvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\noutDirection=outDirection+force*timeDelta;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\noutAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat 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","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nfloat scales[16]=float[16](\n0.1,\n0.11406250000000001,\n0.131640625,\n0.15625,\n0.187890625,\n0.2265625,\n0.272265625,\n0.325,\n0.384765625,\n0.4515625,\n0.525390625,\n0.60625,\n0.694140625,\n0.7890625,\n0.891015625,\n1.0\n);\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\n\nfloat dotProduct=dot(rvec,normal);\nrvec=1.0-abs(dotProduct)>1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=scales[(i+int(random.x*16.0)) % 16]*tbn*sampleSphere[(i+int(random.y*16.0)) % 16];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\ndifference=depthSign*samplePosition.z-sampleDepth;\nfloat rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);\nocclusion+=(difference>=0.0 ? 1.0 : 0.0)*rangeCheck;\n}\nocclusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(position,1.0)).xyz;\n#else\nvPositionUVW=position;\n#endif\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\n\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n","noisePixelShader":"\n\nuniform float brightness;\nuniform float persistence;\nuniform float timeScale;\n\nvarying vec2 vUV;\n\nvec2 hash22(vec2 p)\n{\np=p*mat2(127.1,311.7,269.5,183.3);\np=-1.0+2.0*fract(sin(p)*43758.5453123);\nreturn sin(p*6.283+timeScale);\n}\nfloat interpolationNoise(vec2 p)\n{\nvec2 pi=floor(p);\nvec2 pf=p-pi;\nvec2 w=pf*pf*(3.-2.*pf);\nfloat f00=dot(hash22(pi+vec2(.0,.0)),pf-vec2(.0,.0));\nfloat f01=dot(hash22(pi+vec2(.0,1.)),pf-vec2(.0,1.));\nfloat f10=dot(hash22(pi+vec2(1.0,0.)),pf-vec2(1.0,0.));\nfloat f11=dot(hash22(pi+vec2(1.0,1.)),pf-vec2(1.0,1.));\nfloat xm1=mix(f00,f10,w.x);\nfloat xm2=mix(f01,f11,w.x);\nfloat ym=mix(xm1,xm2,w.y); \nreturn ym;\n}\nfloat perlinNoise2D(float x,float y)\n{\nfloat sum=0.0;\nfloat frequency=0.0;\nfloat amplitude=0.0;\nfor(int i=0; i<OCTAVES; i++)\n{\nfrequency=pow(2.0,float(i));\namplitude=pow(persistence,float(i));\nsum=sum+interpolationNoise(vec2(x*frequency,y*frequency))*amplitude;\n}\nreturn sum;\n}\n\nvoid main(void)\n{\nfloat x=abs(vUV.x);\nfloat y=abs(vUV.y);\nfloat noise=brightness+(1.0-brightness)*perlinNoise2D(x,y);\ngl_FragColor=vec4(noise,noise,noise,1.0);\n}\n"};
  107575. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;\nvarying float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;\nvarying float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;\nvarying float fClipDistance4;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n#ifdef CLIPPLANE2\nfClipDistance2=dot(worldPos,vClipPlane2);\n#endif\n#ifdef CLIPPLANE3\nfClipDistance3=dot(worldPos,vClipPlane3);\n#endif\n#ifdef CLIPPLANE4\nfClipDistance4=dot(worldPos,vClipPlane4);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}\n\nconst float rgbdMaxRange=255.0;\nvec4 toRGBD(vec3 color) {\nfloat maxRGB=max(0.0000001,max(color.r,max(color.g,color.b)));\nfloat D=max(rgbdMaxRange/maxRGB,1.);\nD=clamp(floor(D)/255.0,0.,1.);\n\nvec3 rgb=color.rgb*D;\n\nrgb=toGammaSpace(rgb);\nreturn vec4(rgb,D); \n}\nvec3 fromRGBD(vec4 rgbd) {\n\nrgbd.rgb=toLinearSpace(rgbd.rgb);\n\nreturn rgbd.rgb/rgbd.a;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\nuniform vec4 vLightFalloff{X};\n#elif defined(POINTLIGHT{X})\nuniform vec4 vLightFalloff{X};\n#elif defined(HEMILIGHT{X})\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\nvec4 vLightFalloff;\n#elif defined(POINTLIGHT{X})\nvec4 vLightFalloff;\n#elif defined(HEMILIGHT{X})\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef REFLECTION\nuniform mat4 reflectionMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat lon=atan(direction.z,direction.x);\nfloat lat=acos(direction.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=normalize(reflect(cameraToVertex,worldNormal));\nfloat lon=atan(r.z,r.x);\nfloat lat=acos(r.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\n#ifdef TONEMAPPING_ACES\n\n\n\n\n\nconst mat3 ACESInputMat=mat3(\nvec3(0.59719,0.07600,0.02840),\nvec3(0.35458,0.90834,0.13383),\nvec3(0.04823,0.01566,0.83777)\n);\n\nconst mat3 ACESOutputMat=mat3(\nvec3( 1.60475,-0.10208,-0.00327),\nvec3(-0.53108,1.10813,-0.07276),\nvec3(-0.07367,-0.00605,1.07602)\n);\nvec3 RRTAndODTFit(vec3 v)\n{\nvec3 a=v*(v+0.0245786)-0.000090537;\nvec3 b=v*(0.983729*v+0.4329510)+0.238081;\nreturn a/b;\n}\nvec3 ACESFitted(vec3 color)\n{\ncolor=ACESInputMat*color;\n\ncolor=RRTAndODTFit(color);\ncolor=ACESOutputMat*color;\n\ncolor=clamp(color,0.0,1.0);\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\n#ifdef TONEMAPPING_ACES\nresult.rgb=ACESFitted(result.rgb);\n#else\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nvarying float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nvarying float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nvarying float fClipDistance4;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE2\nif (fClipDistance2>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE3\nif (fClipDistance3>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE4\nif (fClipDistance4>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\nspotInfo=computeSpotLightingInfo(light{X}.vLightData);\n#ifdef LIGHT_FALLOFF_GLTF{X}\nspotInfo.attenuation=computeDistanceLightFalloff_GLTF(spotInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\nspotInfo.attenuation*=computeDirectionalLightFalloff_GLTF(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\nspotInfo.attenuation=computeDistanceLightFalloff_Physical(spotInfo.lightDistanceSquared);\nspotInfo.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\nspotInfo.attenuation=computeDistanceLightFalloff_Standard(spotInfo.lightOffset,light{X}.vLightFalloff.x);\nspotInfo.attenuation*=computeDirectionalLightFalloff_Standard(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w,light{X}.vLightData.w);\n#else\nspotInfo.attenuation=computeDistanceLightFalloff(spotInfo.lightOffset,spotInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\nspotInfo.attenuation*=computeDirectionalLightFalloff(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w,light{X}.vLightData.w,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#endif\ninfo=computeSpotLighting(spotInfo,viewDirectionW,normalW,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(POINTLIGHT{X})\npointInfo=computePointLightingInfo(light{X}.vLightData);\n#ifdef LIGHT_FALLOFF_GLTF{X}\npointInfo.attenuation=computeDistanceLightFalloff_GLTF(pointInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\npointInfo.attenuation=computeDistanceLightFalloff_Physical(pointInfo.lightDistanceSquared);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\npointInfo.attenuation=computeDistanceLightFalloff_Standard(pointInfo.lightOffset,light{X}.vLightFalloff.x);\n#else\npointInfo.attenuation=computeDistanceLightFalloff(pointInfo.lightOffset,pointInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\n#endif\ninfo=computePointLighting(pointInfo,viewDirectionW,normalW,light{X}.vLightDiffuse.rgb,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(HEMILIGHT{X})\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(DIRLIGHT{X})\ninfo=computeDirectionalLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#elif defined(HEMILIGHT{X})\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#elif defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec4 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec4 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec4 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#if defined(USEPHYSICALLIGHTFALLOFF) || defined(USEGLTFLIGHTFALLOFF)\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 view,vec3 normal) {\n\nvec3 reflection=reflect(view,normal);\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nstruct pointLightingInfo\n{\nvec3 lightOffset;\nfloat lightDistanceSquared;\nfloat attenuation;\n};\nstruct spotLightingInfo\n{\nvec3 lightOffset;\nfloat lightDistanceSquared;\nvec3 directionToLightCenterW;\nfloat attenuation;\n};\nfloat computeDistanceLightFalloff_Standard(vec3 lightOffset,float range)\n{\nreturn max(0.,1.0-length(lightOffset)/range);\n}\nfloat computeDistanceLightFalloff_Physical(float lightDistanceSquared)\n{\nreturn 1.0/((lightDistanceSquared+0.001));\n}\nfloat computeDistanceLightFalloff_GLTF(float lightDistanceSquared,float inverseSquaredRange)\n{\nconst float minDistanceSquared=0.01*0.01;\nfloat lightDistanceFalloff=1.0/(max(lightDistanceSquared,minDistanceSquared));\nfloat factor=lightDistanceSquared*inverseSquaredRange;\nfloat attenuation=clamp(1.0-factor*factor,0.,1.);\nattenuation*=attenuation;\n\nlightDistanceFalloff*=attenuation;\nreturn lightDistanceFalloff;\n}\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range,float inverseSquaredRange)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDistanceLightFalloff_Physical(lightDistanceSquared);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange);\n#else\nreturn computeDistanceLightFalloff_Standard(lightOffset,range);\n#endif\n}\nfloat computeDirectionalLightFalloff_Standard(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff_Physical(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle)\n{\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfloat falloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff_GLTF(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngleScale,float lightAngleOffset)\n{\n\n\n\nfloat cd=dot(-lightDirection,directionToLightCenterW);\nfloat falloff=clamp(cd*lightAngleScale+lightAngleOffset,0.,1.);\n\nfalloff*=falloff;\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent,float lightAngleScale,float lightAngleOffset)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset);\n#else\nreturn computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent);\n#endif\n}\npointLightingInfo computePointLightingInfo(vec4 lightData) {\npointLightingInfo result;\nresult.lightOffset=lightData.xyz-vPositionW;\nresult.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);\nreturn result;\n}\nspotLightingInfo computeSpotLightingInfo(vec4 lightData) {\nspotLightingInfo result;\nresult.lightOffset=lightData.xyz-vPositionW;\nresult.directionToLightCenterW=normalize(result.lightOffset);\nresult.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);\nreturn result;\n}\nlightingInfo computePointLighting(pointLightingInfo info,vec3 viewDirectionW,vec3 vNormal,vec3 diffuseColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nfloat lightDistance=sqrt(info.lightDistanceSquared);\nvec3 lightDirection=normalize(info.lightOffset);\n\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*info.attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*info.attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(spotLightingInfo info,vec3 viewDirectionW,vec3 vNormal,vec4 lightDirection,vec3 diffuseColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\nfloat lightDistance=sqrt(info.lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+info.directionToLightCenterW);\nNdotL=clamp(dot(vNormal,info.directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*info.attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*info.attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeDirectionalLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nfloat lightDistance=length(-lightData.xyz);\nvec3 lightDirection=normalize(-lightData.xyz);\n\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn toLinearSpace(textureColor);\n}","clipPlaneVertexDeclaration2":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nout float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;\nout float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;\nout float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;\nout float fClipDistance4;\n#endif","clipPlaneFragmentDeclaration2":"#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nin float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nin float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nin float fClipDistance4;\n#endif","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};